Mark RideoutMICROFT CORPORATION
Summary: This article is intended to help you understand the PropertyGrid control in the Microsoft .NET framework, and how to customize the control for your application.
Applicable to: Microsoft® .NET® Framework Microsoft® Visual Studio® .NET
table of Contents
PropertyGrid Control Introduction Create a PropertyGrid control Where to use the PropertyGrid control Select Object Customization PropertyGrid control to display complex properties to provide custom UI small knots
PropertyGrid Control Introduction
If you have used Microsoft® Visual Basic® or Microsoft Visual Studio .Net, you must use the property browser to browse, view, and edit the properties of one or more objects. The .NET Framework PropertyGrid control is the core of the Visual Studio .NET property browser. The PropertyGrid control displays the object or type of properties and mainly retrieves the properties of the item by using the reflection. (Reflection is a technology that provides type information at runtime.)
The following screen snapshot shows the appearance of PropertyGrid on the form.
Figure 1: PropertyGrid on the form
PropertyGrid contains the following sections:
Property Expand Properties Category Title Properties Description Property Editor Properties tab Command pane (Display Control Designer provides designer operation)
Create a PropertyGrid control
To create a PropertyGrid control using Visual Studio .Net, you need to add this control to the toolbox because the control is not included in the default. In the Tools menu, select Customize Toolbox (Custom Toolbox). Select the Framework Components tab in the dialog box, then select PropertyGrid.
If you compile code from the command line, use the / reference option and specify system.windows.forms.dll.
The following code shows how to create a PropertyGrid control and add it to the form.
'Visual Basic
Imports system
Imports system.drawing
Imports system.componentmodel
Imports System.Windows.Forms
Imports system.globalization
Public Class OptionsDialog
Inherits System.Windows.Forms.form
Private optionspropertyGrid as system.windows.forms.propertygrid
Public Sub New ()
Mybase.new ()
Optionspropertygrid = new propertyGrid ()
Optionspropertygrid.size = new size (300, 250)
Me.Controls.add (optionspropertygrid)
Me.Text = "Options dialog"
End Sub
END CLASS
// C #
Using system;
Using system.drawing;
Using system.componentmodel;
Using system.windows.forms;
USING SYSTEM.GLOBALIZATION;
Public class optionsdialog: system.windows.forms.form {
Private system.windows.forms.propertygrid optionspropertygrid;
Public optionsDialog ()
{
OptionspropertyGrid = new propertyGrid ();
Optionspropertygrid.size = new size (300, 250);
This.Controls.Add (optionspropertygrid);
This.Text = "Options dialog";
}
[Stathread]
Static void main ()
{
Application.run (New OptionsDialog ());
}
}
Where to use the PropertyGrid control
Many places in the app, you can make users interact with PropertyGrid to get a richer editing experience. For example, an application contains "settings" or options that multiple users can set, some of which may be very complicated. You can use a radio button, a combo box, or a text box to represent these options. However, this article will gradually describe how to use the PropertyGrid control to create an option window to set the application option. The OptionsDialog form created above is the beginning of the option window. Now, we create a class called AppSettings that contains all properties mapped to the application settings. If you create a separate class without using multiple decentralized variables, the settings will be more convenient for management and maintenance.
'Visual Basic
Public class appsettings
Private _saveonclose as boolean = true
Private _greetingText As String = "Welcome to the application!"
Private _maxrepeatrate as integer = 10
Private _ItemsinMRU as INTEGER = 4
Private _SettingSchanged as boolean = false
Private _appversion as string = "1.0"
Public property saveonclose () as boolean
Get
Return_saveonclose
END GET
Set (ByVal Value As Boolean)
Saveonclose = Value
End set
End Property
Public property GreetingText () AS STRING
Get
Return_GreetingText
END GET
Set (byval value as string)
_GreetingText = Value
End set
End Property
Public property itemsinmrulist () AS Integer
Get
Return_ItemsinMru
END GET
Set (ByVal Value As Integer)
_ItemsinMRU = Value
End set
End Property
Public property maxrepetrate () AS INTEGER
Get
Return_maxrepeatrate
END GET
Set (ByVal Value As Integer)
_MaxRepetrate = Value
End set
End Property
Public property settingschanged () as booleanget
Return_SettingSchanged
END GET
Set (ByVal Value As Boolean)
_SETTINGSCHANGED = VALUE
End set
End Property
Public property appversion () AS STRING
Get
Return_appversion
END GET
Set (byval value as string)
_appversion = value
End set
End Property
END CLASS
// C #
Public class appsettings {
PRIVATE BOOL Saveonclose = true;
Private String GreetingText = "Welcome to the app!";
Private int itemsinmru = 4;
Private int maxrepetrate = 10;
Private bool settingschanged = false;
Private string appversion = "1.0";
Public Bool SaveonClose
{
Get {return saveonclose;}
SET {SaveonClose = VALUE;
}
Public String GreetingText
{
Get {return greetingtext;}
Set {greetingtext = value;
}
Public int maxrepetrate
{
Get {return maxrepetrate;}
Set {maxrepeatrate = value;
}
Public Int itemsinmrulist
{
Get {return itemsinMRU;}
Set {itemsinmru = value;
}
Public Bool SettingSchanged
{
Get {return settingschanged;}
Set {settingschanged = value;
}
Public String Appversion
{
Get {return appversion;}
Set {appversion = value;
}
}
The PropertyGrid on the Option window will use this class, so add the class definition to the application project, create a new file or add it below the existing form source code when adding.
Select object
To identify the content displayed by the PropertyGrid, set the propertyGrid.selectedObject property to an object instance. The PropertyGrid will then complete the rest. Every time you set SelectedObject, all the PropertyGrid refreshes the displayed properties. This provides a simple way to force refresh attributes or switch objects at runtime. You can also call the PropertyGrid.refresh method to refresh the property.
Next, you need to update the code in the OptionsDialog constructor to create an appSettings object and set it to the value of the PropertyGrid.selectedObject property.
'Visual Basic
Public Sub New ()
Mybase.new ()
Optionspropertygrid = new propertyGrid ()
Optionspropertygrid.size = new size (300, 25) me.controls.add (optionspropertygrid)
Me.Text = "Options dialog"
'Creating a AppSettings class and displays this class in the PropertyGrid.
DIM Appset as appsettings = new appsettings ()
Optionspropertygrid.selectedObject = Appset
End Sub
// C #
Public optionsDialog ()
{
OptionspropertyGrid = new propertyGrid ();
Optionspropertygrid.size = new size (300, 250);
This.Controls.Add (optionspropertygrid);
This.Text = "Options dialog";
// Create an AppSettings class and display the class in the PropertyGrid.
Appsettings appset = new appsettings ();
Optionspropertygrid.selectedObject = Appset
}
Compile and run the app. The following screen snapshot shows the appearance of the application.
Figure 2: AppsetTings class selected in PropertyGrid
Custom PropertyGrid control
You can modify some of the appearance characteristics of PropertyGrid to meet your needs. You can change the display of some properties, or even selecting the attributes. So how do you customize the PropertyGrid?
Change the appearance characteristics of PropertyGrid
Many appearance features of PropertyGrid can be customized. Part below is listed below:
Change the background color, changing font color or hidden description panes by HelpBackColor, HelpForeColor, and HelpVisible properties. You can hide the toolbar through the Toolbarvisible property. You can change the color of the toolbar through the BackColor property. You can display the big toolbar button through the LARGEBUTTONS property. Use the PropertySort property to sort and classify attributes in alphabetical order. Change the color of the splitter through the BackColor property. Grid lines and borders can be changed through the LineColor property.
The Options window in this example does not require a toolbar, so you can set Toolbarvisible to false. The rest of the property retains the default settings.
Change the display mode of the property
To change some properties, you can apply different features for these properties. Features is used to add annotations markers for programming elements such as types, fields, methods, and attributes, which can be retrieved using reflection at runtime. Part below is listed below:
DescriptionAttribute - Sets the description of the properties to describe the properties text in the Help pane below the property. This is an effective way to provide help text for active properties (ie attributes with focus). This feature can be applied to the maxrepetrate property. CategoryAttribute - Set the category that the properties belong in the grid. This feature is very useful when you need to group attributes by category name. If the category is not specified for the property, this property will be assigned to the miscellaneous category. This feature can be applied to all properties. BrowsableAttribute - Indicates whether the properties are displayed in the grid. This feature can be used to hide attributes in the grid. By default, public properties are always displayed in the grid. This feature can be applied to the SettingSchangeD property. ReadOnlyAttribute - Indicates if the property is read-only. This feature can be used to prohibit editing properties in the grid. By default, public properties with GET and SET access functions are editable in the grid. This feature can be applied to the AppVersion property. DefaultValueAttribute - Indicates the default value of the properties. This feature can be used if you want to provide the default value for properties and then make sure that the value value is the same as the default. This feature can be applied to all properties. DEFAULTPROPERTYATTRIBUTE - Indicates the default properties of the class. When you select a class in the grid, you will first highlight the default properties of this class. This feature can be applied to the AppSettings class. Now, we apply some of the features to the AppSettings class to change the properties in the display mode of the propertyGrid.
'Visual Basic
Public class appsettings
Private _saveonclose as boolean = true
Private _greetingText As String = "Welcome to the application!"
Private _maxrepeatrate as integer = 10
Private _ItemsinMRU as INTEGER = 4
Private _SettingSchanged as boolean = false
Private _appversion as string = "1.0"
DefaultValueAttribute (TRUE)> _ Public property saveonclose () as boolean Get Return_saveonclose END GET Set (ByVal Value As Boolean) Saveonclose = Value End set End Property ReadonlyAttribute (TRUE), _ DEFAULTVALUEATTRIBUTE ("Welcome to the app!")> _ _ Public property GreetingText () AS STRING Get Return_GreetingText END GET Set (byval value as string) _GreetingText = Value End set End Property DefaultValueAttribute (4)> _ Public property itemsinmrulist () AS Integer Get Return_ItemsinMru END GET Set (ByVal Value As Integer) _ItemsinMRU = Value End set End Property CategoryAttribute ("Global Settings"), _ DefaultValueAttribute (10)> _ Public property maxrepetrate () AS INTEGER Get Return_maxrepeatrate END GET Set (ByVal Value As Integer) _MaxRepetrate = Value End set End Property DefaultValueAttribute (FALSE)> _ Public property settingschanged () as boolean Get Return_SettingSchanged END GET Set (ByVal Value As Boolean) _SETTINGSCHANGED = VALUE End set End Property DefaultValueAttribute ("1.0"), _ ReadonlyAttribute (TRUE)> _ Public property appversion () AS STRING Get Return_appversion END GET Set (byval value as string) _appversion = value End set End Property END CLASS // C # [DefaultPropertyAttribute ("SaveonClose")]] Public class appsettings { PRIVATE BOOL Saveonclose = true; Private String GreetingText = "Welcome to the app!"; Private int maxrepetrate = 10; Private int itemsinmru = 4; Private bool settingschanged = false; Private string appversion = "1.0"; [CategoryAttribute ("Document Settings"), DefaultValueAttribute (TRUE)] Public Bool SaveonClose { Get {return saveonclose;} SET {SaveonClose = VALUE; } [CategoryAttribute ("Global Settings"), ReadonlyAttribute (TRUE), DefaultValueAttribute ("Welcome to the app!")] Public String GreetingText { Get {return greetingtext;} Set {greetingtext = value; } [CategoryAttribute ("Global Settings"), DefaultValueAttribute (4)] Public Int itemsinmrulist { Get {return itemsinMRU;} Set {itemsinMRU = value;}} [DescriptionAttribute ("Text Repeat Rate in milliseconds."), CategoryAttribute ("Global Settings"), DefaultValueAttribute (10)] Public int maxrepetrate { Get {return maxrepetrate;} Set {maxrepeatrate = value; } [BrowsableAttribute (False), DefaultValueAttribute (false)] Public Bool SettingSchanged { Get {return settingschanged;} Set {settingschanged = value; } [CategoryAttribute ("Version"), DefaultValueAttribute ("1.0"), ReadonlyAttribute (TRUE)] Public String Appversion { Get {return appversion;} Set {appversion = value; } } After applying these features to the AppSettings class, compile and run the application. The following screen snapshot shows the appearance of the application. Figure 3: Properties with category and default values displayed in PropertyGrid After using this version of the option window, you will notice the following: When the window is displayed, the SaveOnClose property is first highlighted. When you select the maxrepetrate property, the "Text Repetition represented in milliseconds" will be displayed in the Help pane. The SaveonClose property is displayed under the Document Settings category. Other attributes are displayed under the Global Settings and Version categories, respectively. SettingSchangeD properties will no longer be displayed. The appVersion property is read-only. Read-only properties are displayed in gray text. If the value containing the SaveonClose property is not true, the value will be displayed in bold. PropertyGrid uses bold text to indicate the properties that contain non-default values. Show complex attributes Up to now, the option window is displayed as a simple type, such as integer, Boolean and strings. So how do I display more complex types? What is handled if the application needs to track information such as window size, document font or toolbar colors? Some data types provided by the .NET framework have special display features that can make these types more availability in the PropertyGrid. Support for providing the type First, update the AppSettings class, add new properties to the window size (size type), window font (font type), and toolbar color (Color Type). 'Visual Basic Public class appsettings Private _saveonclose as boolean = true Private _greetingText As String = "Welcome to the application!" Private _maxrepeatrate as integer = 10 Private _ItemsinMRU as INTEGER = 4 Private _SettingSchanged as boolean = false Private _appversion as string = "1.0" private _windowsize as size = new size (100, 100) Private_windowfont as font = new font ("Song Body", 9, FontStyle.Regular Private _toolbarcolor as color = systemcolors.control DefaultValueAttribute (TRUE)> _ Public property saveonclose () as boolean Get Return_saveonclose END GET Set (ByVal Value As Boolean) Saveonclose = Value End set End Property Public property windowsize () as size Get Return_Windowsize END GET Set (ByVal Value As Size) _Windowsize = Value End set End Property Public property WindowFont () AS FONT Get Return_windowfont END GET SET (ByVal Value As Font) _WindowFont = Value End set End Property Public Property Toolbarcolor () As Color Get Return_toolbarcolor END GET SET (ByVal Value As Color) _Toolbarcolor = Value End set End Property ReadonlyAttribute (TRUE), _ DEFAULTVALUEATTRIBUTE ("Welcome to the app!")> _ _ Public property GreetingText () AS STRING Get Return_GreetingText END GET Set (byval value as string) _GreetingText = Value End set End Property DefaultValueAttribute (4)> _ Public property itemsinmrulist () AS Integer Get Return_ItemsinMru END GET Set (ByVal Value As Integer) _ItemsinMRU = Value End set End Property CategoryAttribute ("Global Settings"), _ DefaultValueAttribute (10)> _ Public property maxrepetrate () AS INTEGER Get Return_MaxrepetrateEnd Get Set (ByVal Value As Integer) _MaxRepetrate = Value End set End Property DefaultValueAttribute (FALSE)> _ Public property settingschanged () as boolean Get Return_SettingSchanged END GET Set (ByVal Value As Boolean) _SETTINGSCHANGED = VALUE End set End Property DefaultValueAttribute ("1.0"), _ ReadonlyAttribute (TRUE)> _ Public property appversion () AS STRING Get Return_appversion END GET Set (byval value as string) _appversion = value End set End Property END CLASS // C # [DefaultPropertyAttribute ("SaveonClose")]] Public class appsettings { PRIVATE BOOL Saveonclose = true; Private String GreetingText = "Welcome to the app!"; Private int maxrepetrate = 10; Private int itemsinmru = 4; Private bool settingschanged = false; Private string appversion = "1.0"; Private size windowsize = new size (100,100); Private font windowfont = new font ("Song", 9, FontStyle.Regular; Private color Toolbarcolor = systemcolors.control; [CategoryAttribute ("Document Settings"), DefaultValueAttribute (TRUE)] Public Bool SaveonClose { Get {return saveonclose;} SET {SaveonClose = VALUE; } [CategoryAttribute ("Document Settings")] Public Size Windowsize, PUBLIC SIZE WINDOWSE { Get {return windowsize;} Set {windowsize = value;} } [CategoryAttribute ("Document Settings")] Public Font WindowFont, PUBLIC FONT WINDOWFONT { Get {return windowfont;} Set {windowfont = value;} } [CategoryAttribute ("Global Settings")]] Public Color Toolbarcolor { Get {return tobarcolor; Set {Toolbarcolor = Value; } [CategoryAttribute ("Global Settings"), ReadonlyAttribute (True), DefaultValueAttribute ("Welcome to the application!")] Public String GreetingText { Get {return greetingtext;} Set {greetingtext = value; } [CategoryAttribute ("Global Settings"), DefaultValueAttribute (4)] Public Int itemsinmrulist { Get {return itemsinMRU;} Set {itemsinmru = value; } [DescriptionAttribute ("Text Repeat Rate in milliseconds."), CategoryAttribute ("Global Settings"), DefaultValueAttribute (10)] Public int maxrepetrate { Get {return maxrepetrate;} Set {maxrepeatrate = value; } [BrowsableAttribute (False), DefaultValueAttribute (false)] Public Bool SettingSchanged { Get {return settingschanged;} Set {settingschanged = value; } [CategoryAttribute ("Version"), DefaultValueAttribute ("1.0"), ReadonlyAttribute (TRUE)] Public String Appversion { Get {return appversion;} Set {appversion = value; } } The following screen snapshot shows the appearance of the new attribute in the PropertyGrid. Figure 4: Displaying the .NET framework data type in the PropertyGrid Note that the WindowFont property comes with a omitted number (...) button, pressing the button to display the font selection dialog. In addition, this property can also be expanded to display more Font properties. Some font properties provide a drop-down list for the value of the font and the details. You can expand the Windowsize property to display more properties of the Size type. Finally, please note that the Toolbarcolor property contains a sample of selected colors, and a custom drop-down list for selecting different colors. For these and other data types, the .NET framework provides other classes that make the editing in the propertyGrid easier. Support for custom types Now you need to add additional two properties in the AppSettings class, namely defaultfilename, and spellcheckOptions. The DefaultFileName property is used to get or set strings; the SpellCheckOptions property is used to get an instance of the SpellingOptions class. The SpellingOptions class is a new class that manages the spell check properties of the application. For when to create a separate class to manage objects, there is no strict specification, but depending on your entire design. Adding the SpellingOptions class definition to the application project - can be added to the new file or below the form source code. 'Visual Basic Public class spellingoptionsprivate _spellcheckwhiletyping as boolean = true Private _spellcheckcaps as boolean = false Private _suggestcorrections as boolean = TRUE Public property SpellCheckwhileTyping () as boolean Get Return_SPELLCHECKWHILETYPING END GET Set (ByVal Value As Boolean) _SPELLCHECKWHILETYPING = VALUE End set End Property Public property spellcheckcaps () as boolean Get Return_SPellCheckcaps END GET Set (ByVal Value As Boolean) _SPELLCHECKCAPS = VALUE End set End Property Public property suggestcorrections () as boolean Get Return _Suggest Corrections END GET Set (ByVal Value As Boolean) _SuggeStcorrections = Value End set End Property END CLASS // C # [DescriptionAttribute ("Expand to view the spelling options for the application.")]] Public Class SpellingOptions { Private Bool SpellCheckwhileTyping = True; Private Bool SpellCheckcaps = false; PRIVATE BOOL SUGGESTCORRERRES = True; [DefaultValueAttribute (TRUE)] Public Bool SpellCheckWhileTyping { Get {return spllcheckwhiletyping; Set {spllcheckwhiletyping = value; } [DefaultValueAttribute (FALSE)] Public Bool SpellCheckcaps { Get {return SpellCheckcaps; Set {spellcheckcaps = value; } [DefaultValueAttribute (TRUE)] Public Bool Suggest Corrections { Get {return suggestcorrections; Set {suggestcorrections = value; } } Compile and run the option window app again. The following screen snapshot shows the appearance of the application. Figure 5: Custom data types of non-type converters displayed in PropertyGrid Note the appearance of the SpellCheckOptions property. Unlike the .NET framework type, it does not expand or displays a custom string representation. How do you handle the same editing experience as the .NET frame type in your complex type. The .NET Framework Type With the TypeConverter and the UITYPEEDITOR class, you can use these classes. Add to expand properties support To enable PropertyGrid to expand the SpellingOptions property, you need to create TypeConverter. TypeConverter provides a way from one type to another. PropertyGrid uses TypeConvert to convert the object type to string and use this string to display the object value in the grid. During editing, TypeConverter converts String back to the object type. The EXPANDABLEOBJECTCONVERTER class provided by the .NET framework can simplify this process. Provide expandable object support Create a class that is inherited from ExpandableObjectConverter. 'Visual Basic Public Class SpellingOptionsConverter Inherits ExpandableObjectConverter END CLASS // C # Public Class SpellingOptionsConverter: ExpandableObjectConverter {} If the DestinationType parameter is the same as the type of class using this type of converter (the spellingOptions class in the example), override the CANCONVERTTO method and returns true; otherwise return the value of the base class CANCONVERTTO method. 'Visual Basic Public overloads overrides function canconvertto (_ ByVal Context As ITYPEDESCRIPTORCONTEXT, _ BYVAL DESTINATIONTYPE As Type) as boolean IF (destinationType is gettype (spellingoptions). Return True END IF Return mybase.canconvertto (context, destinationtype) End function // c # Public Override Bool CanconvertTo (ItypeScriptorContext Context, System.Type DestinationType) { IF (destinationType == TypeOf (SpellingOption)) Return True; Return Base.canconvertTo (Context, DestinationType); } Overlay the ConvertTo method and make sure the DestinationType parameter is a string, and the type of value is the same as classes that use this type of converter (the spellingOptions class in the example). If any of the cases are false, the values of the base class ConvertTo method will be returned; otherwise, the string of the returned value object is represented. String indicates that each attribute of the class will be separated using a unique separator. Since the entire string will be displayed in the PropertyGrid, you need to select a separator that does not affect readability, the effect of comma is usually better. 'Visual Basic Public overloads overrides function convertto (_byval context as itypesscriptorContext, _ Byval Culture As CultureInfo, _ Byval value as object, _ Byval destinationType as system.type) As Object IF (destinationType is gettype (system.string) _ Andalso Typeof Value Is SpellingOptions) THEN Dim so as spellingoptions = ctype (value, spellingoptions) Return "Check:" & solCheckwhileTyping & _ ", Check the case:" & solCheckcaps & _ ", Suggestion correction:" & solgeestcorrections END IF Return mybase.convertto (Context, Culture, Value, DestinationType) End function // c # Public Override Object ConvertTo (ITYPEDESCRIPTORCONTEXT CONTEXT, CultureInfo Culture, Object Value, System.Type DestinationType) { IF (destinationType == TypeOf (System.String) && Value is spellingoptions) { SpellingOptions so = (spellingoptions) value; Return "Checks:" So.spellCheckWhileTyping ", Check the case:" So.SpellCheckcaps ", Recommendation correction:" so.suggestcorrections; } Return Base.ConvertTo (Context, Culture, Value, DestinationType); } (Optional) You can convert from the string by specifying the type converter, you can enable the editing of the object string representation in the grid. To do this, you first need to overwrite the CANCONVERTFROM method and return true (if the source Type parameter is string type); otherwise, return the value of the base class CANCONVERTFROM method. 'Visual Basic Public overloads overrides function canconvertfrom ByVal Context As ITYPEDESCRIPTORCONTEXT, _ Byval SourceType As System.Type) as boolean IF (SourceType is gettype (string) THEN Return True END IF Return mybase.canconvertfrom (Context, SourceType) End function // c # Public Override Bool CanconvertFrom (ItypeScriptorContext Context, System.Type SourceType) { IF (SourceType == TypeOf (String) Return True; Return Base.canconvertFrom (Context, SourceType); } To enable editing of the object base class, you also need to override the ConvertFROM method and make sure the value parameter is a string. If not String, return the value of the base class ConvertFrom method; otherwise, return a new instance of a class based on value parameters (SpellingOptions class in the example). You need to analyze the values of each attribute of the class according to value parameters. The format of the SLR string created in the ConvertTo method will help your resolution. 'Visual Basic Public overloads overrides function convertfrom ByVal Context As ITYPEDESCRIPTORCONTEXT, _ Byval Culture As CultureInfo, _ Byval value as object) as Object IF (TypeOf Value Is String " Try DIM S As String = CSTR (Value) DIM colon as integer = s.indexof (":") DIM COMMA AS INTEGER = S.Indexof (",") IF (Colon <> -1 Andalso COMMA <> -1) THEN Dim CheckwhileTyping As string = s.substring (Colon 1, _ (Comma - COLON - 1)) Colon = s.indexof (":", COMMA 1) Comma = s.indexof (",", COMMA 1) DIM Checkcaps as string = s.substring (colon 1, _ (Comma - COLON - 1)) Colon = s.indexof (":", COMMA 1) DIM suggorr as string = s.substring (Colon 1) DIM SO as SpellingOptions = New SpellingOptions () So.SpellCheckwhileTyping = Boolean.Parse (CheckwhileTyping) So.SpellCheckcaps = Boolean.Parse (Checkcaps) So.suggestcorrections = boolean.parse (suggorr) Return SO END IF Catch Throw new argumentexception "Unable to" & CSTR (Value) &_ "Convert to SpellingOptions")) END TRY END IF Return mybase.convertfrom (Context, Culture, Value) End function // c # Public Override Object ConvertFrom (ItypeDescriptorContext Context, CultureInfo Culture, Object Value { Value Is String { Try { String s = (string) Value; INT colon = s.indexof (':'); int COMMA = S.Indexof (','); IF (Colon! = -1 && Comma! = -1) { String checkwhiletyping = s.substring (colorn 1, (COMMA - COLON - 1))); Colon = S.Indexof (':', COMMA 1); COMMA = S.Indexof (',', COMMA 1); String checkcaps = s.substring (Colon 1, (COMMA - COLON-1)); Colon = S.Indexof (':', COMMA 1); String suggorr = s.substring (Colon 1); SpellingOptions so = new spellingoptions (); So.SpellCheckwhileTyping = Boolean.Parse (CheckwhileTyping); So.SpellCheckcaps = Boolean.Parse (Checkcaps); So.suggestcorrections = boolean.parse (suggr); Return SO; } } Catch { Throw new argumentexception "Unable to" " (String) Value "Convert to SpellingOptions"); } } Return Base.ConvertFrom (Context, Culture, Value); } There is already a type converter class now, you will need to determine the target class using this class. You can do this by applying TypeConvertRibute to the Target Class (SperningOptions class in the example). 'Visual Basic 'Apply to the TypeConverter feature of the SpellingOptions class. DescriptionAttribute ("Expand to view the application's spelling option.")> _ Public Class SpellingOptions ... END CLASS // C # // Apply to the TypeConvert of the SpellingOptions class. [TypeConvertRibute (TypeOf (SpellingOptionsConverter), DescriptionAttribute ("Expand to view the spelling options for the application.")]] Public Class SpellingOptions {...} Compile and run the option window app again. The following screen snapshot shows the current look at the option window. Figure 6: Custom data type with type converters displayed in PropertyGrid Note: If you only need to expand object support, you don't need to customize a string, you only need TypeConverTeratTribute is applied to the class. will ExpandableObjectConverter is specified as type converter type. Add domain lists and simple drop-down list properties support For an enorm type return an enumeration, PropertyGrid will automatically display enumeration values in the drop-down list. ENUMCONVERTER also provides this feature. For your own properties, you may want to provide users with a valid value list (sometimes referred to as a list or domain list), and its type is not based on ENUM. If the domain value is not known before running, or the value can be changed, it belongs to this. Modify the option window to provide a domain list of the default file name that users can select. You have added the DefaultFileName property to the AppSettings class. The next step is to display the drop-down list of the properties in the PropertyGrid to provide domain lists. Provide simple drop-down list properties support Create a class inherited from the type converter class. Since the defaultFileName property belongs to the String type, you can inherit from StringConverter. If the type converter of the attribute type does not exist, you can inherit from TypeConvert; it is not required. 'Visual Basic Public Class FileNameConverter Inherits StringConverter END CLASS // C # Public Class FilenaMeconverter: StringConverter {} Override the getStandardValuessupported method and returns True, indicating that this object supports a set of standard values that can be selected from the list. 'Visual Basic Public overloads overrides function getStandardValuessupported (_ Byval context as itypescriptorContext) as boolean Return True END FUNCTION // C # Public Override Bool GetStandardValuessupported ITypedScriptorContext context) { Return True; } Overcome the GetStandVALUES method and returns StandardValeScollection that populates the standard value. One way to create a StandardValuesCollection is to provide a value group in the constructor. For options window applications, you can use the String array that populates the recommended default file name. 'Visual Basic Public overloads overrides function getStandardValues Byval context as itypescriptorContext) AS StandardValeScollection Return New StandardValeScollection (New String () {"New File", _ "File 1", _ "Document 1"}) END FUNCTION // C # Public Override StandardValeScollection GetStandardValues (ItypeDescriptorContext Context) { Return New StandardValeScollection (New String "{" New File ", "File 1", "Document 1"}); (Optional) If you want the user to type the value that is not included in the drop-down list, override the getStandardValeSexClusive method and return false. This simply turns the drop-down list style into a combination frame pattern. 'Visual Basic Public overloads Overrides Function GetStandardValuesexClusive (_BYVAL Context As ITYPEDESCRIPTORCONTEXT) AS BOOLEAN Return False END FUNCTION // C # Public Override Bool GetStandardValeSexClusive ITypedScriptorContext context) { Return False; } After you have your own type converter class for display the drop-down list, you need to determine the target of this class. In this example, the target is a defaultFileName property because the type converter is for this property. Apply TypeConvertRibute to the target properties. 'Visual Basic 'Apply to the TypeConverter feature of the DefaultFileName property. CategoryAttribute ("Document Settings")> _ Public property defaultfilename () AS String Get Return_DefaultFileName END GET Set (byval value as string) _Defaultfilename = value End set End Property // C # // Apply to the TypeConvertFerter feature of the defaultFileName property. [TypeConverter (TypeNameConverter), CategoryAttribute ("Document Settings")] Public String DefaultFileName { Get {return defaultfilename;} Set {defaultFilename = value; } Compile and run the option window app again. The following screen snapshot shows the current look at the option window. Note the appearance of the defaultfilename property. Figure 7: Display the drop-down domain list in the PropertyGrid Provide custom UI for properties As mentioned above, the .NET framework type provides PropertyGrid editing support using the TypeConverter and UITYPEEDITOR classes (and other classes). For information on how to use TypeConverter, see Support for Custom Types; you can also use the UITYPEEDITOR class from the definition of PropertyGrid. You can provide small graphical representations and property values in PropertyGrid, similar to what provided for Image and Color classes. To do this in a custom, please inherit from UITYPEEDITOR, override getPAINTVALUESUPPORTED and return true. Then, cover the UITYDITOR.PAINTVALUE method and draw the graphics using the PaintValueEventArgs.graphics parameter in its own method. Finally, apply Editor features to class or properties that use the UITYPEEDITOR class. The following screen snapshot shows the appearance. Figure 8: Custom graphic display attribute in PropertyGrid You can also provide your own drop-down list control, which is used to provide users with a controlled control with the control. To do this, inherit from UITYPEEDITOR, override getIsterStyle, then return a UITYPEEDITOREDITSTYLE enumeration value, such as Dropdown. Your custom drop-down list controls must be inherited from Control or Control derived classes such as UserControl. Then, override the UITYPEEDITOR.EDITVALUE method. Call the iServiceProvider.getService method using the iServiceProvider parameter for an IWindowsFormSeditorvice instance. Finally, call the iWindowsformSeditorService.dropdownControl method to display your custom drop-down list control. Keep in mind to apply Editor feature to class or properties that use the UITYPEEDITOR class. The following screen snapshot shows the appearance. Figure 9: Custom drop-down list controls for display attributes in PropertyGrid In addition to using the TypeEditor and the UITYPEEDITOR class, you can customize the PropertyGrid to display other property tabs. The property tab inherits from the PropertyTAB class. If you have used the property browser in Microsoft Visual C #TM .NET, you may see custom PropertyTabs. The Events tab (buttons with lightning graphics) is a custom PropertyTab. The following screen snapshot shows another example of custom PropertyTab. You can use the PropertyTAB Edit button boundary point to create a custom button shape. Figure 10: Displays a custom tab in the PropertyGrid For more information on using the UITYDITOR class custom PropertyGrid, as well as the above-described custom user interface code, see Shawn Burke. Make Your Components Really Rad With Visual Studio .NET Property Browser (English). summary The PROPERYGRID control provided by the .NET framework has a wealth of editing features, you can use these editing features to improve your user interface. PropertyGrid's customization is very simple, you can use this control in any application. In addition, since the Visual Studio .Net property browser is based on the propertyGrid, you can use these technologies to provide a richer design experience.