SharePoint 2013 WebPart with custom properties

If you created a WebPart for SharePoint 2013 and you want the user to customize it, you will need properties.
Setting them up is not that easy as you think. You need to edit two files. Lets begin with the <yourWebPart>.ascx.cs file. What you will do there is setting up the propertiesobjects. Later you can use them to read the values the user typed in.
I make a difference between two kind of properties: 'easy' and 'not that easy properties'. I do not call it 'not that easy', because it is hard to use, I call it that way because you need a line of code more.
An easy propertiy would be a textfield. The code you need to add would look like this.

1
2
3
4
5
6
7
[WebBrowsable(true),
WebDisplayName("<youtDisplayname>"),
WebDescription("<yourDescription>"),
Personalizable(PersonalizationScope.Shared),
Category("<yourCategoryname>")]

public string customTextProperty { get; set; }


A 'not that easy' property would be a choise field. To use it you will need an enumerater and would look like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public enum myCustomEnum
{
 customOption1,
 customOption2
}
[WebBrowsable(true),
WebDisplayName("<youtDisplayname>"),
WebDescription("<yourDescription>"),
Personalizable(PersonalizationScope.Shared),
Category("<yourCategoryname>")]
public myCustomEnum customChoiseProperty { get; set; }

The enumerater contains the values that should be in the choise field.

The attribute WebBrowsable enables the user to edit this property. If it is false this property do not appear in the settings. Into WebDisplayName you should enter a user friendly name, because this will be displayed in the settings. Also the WebDescrition should be user friendly, because it is a short instruction what the user changes. The Personalizable property is an enumerator. It contains the values Shared (settings will be for all user) and User (each user makes settings for himself).  Category is a group where the properties will be displayed in.

After setting this up you need to edit the <yourWebPart>.webpart file. This file is a xml file and you need to enter your properties into the <properties>-tag right under the title and description. It also contains the defaultvalue.
For an 'easy' property the new tag would look like this:

<property name="customTextProperty" type="string">This is the defaultvalue.</property>

And for a 'not that easy' poperty it looks like this:

<property name="customChoiseProperty" type="DemoWebPart.HelloWordlWebPart.VisualWebPart1+myCustomEnum, $SharePoint.Project.AssemblyFullName$">customOption1</property>

The confusing thing is that you need to enter the full name of the enumerator and of the assembly to bind it as value.
Now your WebPart contains custom properties, all you need to do is to deploy it and after pressing the 'Edit Web Part' button it should look like this:








Comments

Popular posts from this blog

How to support multiple languages in WPF