Take advantage of the PropertyGrid control of the .NET framework

zhaozj2021-02-16  82

Take advantage of the PropertyGrid control of the .NET framework

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.

Suitable for: 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 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 MaxRepeatRate () As Integer Get Return _maxRepeatRate End Get Set (ByVal Value As Integer) _maxRepeatRate = Value End set end proty () as boolean get return _SETTINGSCHANGED END GET (BYVAL VALUE AS BOOLEAN) _SETTINGSCHANGED = VALUE END SE t 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 Use the application! "; Private int itemsInMRU = 4; private int maxRepeatRate = 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 MaxRepeatRate {get {return maxRepeatRate;} set {maxRepeatRate = value;}} public int ItemsInMRUList {get {return itemsInMRU;} set {itemsInMRU = value;}} public bool SettingsChanged {get {return settingsChanged;} set { Settingschanged = value;}} public string appver;} set {appversion = value;}}}}}} The PropertyGrid on the Options window will use this class, so add the class definition to the application project, when added You can create a new file or add it below the existing form source code.

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, 250) Me.Controls.Add (OptionsPropertyGrid) Me.Text = "Options dialog"' Create AppSettings Class and display 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?

Changing the appearance feature of PropertyGrid 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 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 PropertyReadOnlyAttribute (True), _ DefaultValueAttribute ( "Welcome application!")> _ Public Property GreetingText () AS String Get Return_GreetingText End Get Set (Byval Value As String) _GreetingText = Value End End Property

DefaultValueAttribute (4)> _ public property itemsinmrulist () AS integer get return_itemsinmru end set (byval value as integer) _ItemsInMRU = value end vend

CategoryAttribute ( "Global Settings"), _ DefaultValueAttribute (10)> _ Public Property MaxRepeatRate () As Integer Get Return _maxRepeatRate End Get Set (ByVal Value As Integer) _maxRepeatRate = 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 application! "; private int maxRepeatRate = 10; private int itemsInMRU = 4; private bool settingsChanged = false; private string appVersion =" 1.0 " ; [CategoryAttribute ( "document set"), DefaultValueAttribute (true)] public bool SaveOnClose {get {return saveOnClose;} set {saveOnClose = value;}} [CategoryAttribute ( "global settings"), ReadOnlyAttribute (true), DefaultValueAttribute ( " Welcome 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."), CAT egoryAttribute ( "Global Settings"), DefaultValueAttribute (10)] public int MaxRepeatRate {get {return maxRepeatRate;} set {maxRepeatRate = value;}} [BrowsableAttribute (false), DefaultValueAttribute (false)] public bool SettingsChanged {get {return settingsChanged ;} set {settingsChanged = value;}} [CategoryAttribute ( "release"), DefaultValueAttribute ( "1.0"), ReadOnlyAttribute (true)] public string appVersion {get {appVersion return;} 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: After using the property of the category and default value displayed in PropertyGrid Use this version of the option window, you should notice the following: When the window is displayed, the SaveonClose property will be highlighted first. 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. Display complex attributes until now, the option window display is a simple type, such as an integer, Boolean and string. 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 of support 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 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

_ Public property saveonclose () as boolean get return _saveonclose End get set (byval value as boolean) saveonclose = value end set dend

_

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 Colorget

Return_toolbarcolor

END GET

SET (ByVal Value As Color)

_Toolbarcolor = Value

End set

End Property

_ Public property GreetingText () AS STRING GET RETURN _GREETINGTEXT END GET (BYVAL VALUE AS STRING) _GreetingText = Value End End Property

_ Public property itemsinmrulist () as integer get return _itemsinmru end set (byval value as integer) _ItemsinMRU = Value End set entry

_ Public Property maxrepetrate () AS integer get return _maxrepeatrate end set (byval value as integer) _MaxRepetrate = value end vendy

_ Public Property SettingSchanged () As Boolean Get 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 End Property End Class

// C # [DefaultPropertyAttribute ( "SaveOnClose")] public class AppSettings {private bool saveOnClose = true; private string greetingText = "Welcome application!"; Private int maxRepeatRate = 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 set"), DefaultValueAttribute (true)] public bool SaveOnClose {get {return saveOnClose;} set {saveOnClose = value;}}

[CategoryAttribute ("Document Settings")]

Public Size Windowsize

{

Get {return windowsize;}

Set {windowsize = value;}

}

[CategoryAttribute ("Document Settings")] 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 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 milliseconds repetition rate "), CategoryAttribute (" global settings "), DefaultValueAttribute (10)] public int maxRepeatRate {get {return maxRepeatRate;} set {maxRepeatRate = value;}} [BrowsableAttribute (false), DefaultValueAttribute (false)] public bool SettingsChanged {get {return settingsChanged;} set {settingsChanged = value;} } [CategoryAttribute ("Version"), DefaultValueAttribute ("1.0"), ReadOntatorTribute (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 of PropertyGrid, Note that the WindowFont property comes with a omitted number (...) button, pressing this 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 customized types now, you need to add additional two properties to 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 SpellingOptions Private_SPellCheckwhileTyping As Boolean = True Private_spellcheckcaps as boolean = false private _ssuggestcorrections as boolean = true

_ Public property spellcheckwhiletyping () as boolean get return _spellcheckwhiletyping end set (byval value as boolean) _SPELLCHECKWHILETYPING = Value End Set End Property

_ Public Property SpellCheckcaps () AS Boolean Get Return_SpellCheckcaps End (Byval Value As Boolean) _SPELLCHECKCAPS = VALUE End Set End Property

_ Public Property SuggestCorrections () AS Boolean Get Return_SuggeStcorRences End (Byval Value As Boolean) _SuggeStcorRections = Value End Set End Property End Class

// C # [DescriptionAttribute ( "Expand to see the application of spelling options.")] Public class SpellingOptions {private bool spellCheckWhileTyping = true; private bool spellCheckCAPS = false; private bool suggestCorrections = true; [DefaultValueAttribute (true)] public bool SpellCheckWhileTyping {get {return spellCheckWhileTyping;} set {spellCheckWhileTyping = value;}} [DefaultValueAttribute (false)] public bool spellCheckCAPS {get {return spellCheckCAPS;} set {spellCheckCAPS = value;}} [DefaultValueAttribute (true)] public bool SuggestCorrections {get {RETURN SUGGESTCORRES;} set {suggestcorrections = value;}}} Compile and run the option window application again. The following screen snapshot shows the appearance of the application. Figure 5: Custom data types of non-type converters displayed in PropertyGrid Please note the appearance of the SpellCheckOptions attribute. 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 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 {} the same if destinationType parameters using this type converter class (SpellingOptions class example) the type, the cover CanConvertTo method and return true; Otherwise returns 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)) Then Return True End If Return MyBase.CanConvertTo (context, destinationType) End Function // C # public override bool CanConvertTo (ITypeDescriptorContext context, System.Type destinationType) {if (destinationType == typeof (SpellingOptions)) return true; return base.CanConvertTo (context, destinationType);} method ConvertTo cover, and to ensure that the parameter is a String destinationType And the type of value is the same as classes using this type of converter (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 ITypeDescriptorContext, _ 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 SELLINGOPTIONS = CTYPE (VALUE, SpellingOptions) Return "Check:" & So.SpellCheckwhileTyping & _ ", check sensitive:" & solCheckcaps & _ ", suggestion correction:" & so.SuggestCorrections 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 (SPELLINGOPTIONS SO = (SpellingOptions) Value; Return "Check:" So.spellCheckWhileTyping ", check the case:" so.spellcheckcaps ", suggestion correction:" So.suggest Corrections;} Return Base.convertto (Context, Culture, Value, Destinationt YPE);} (Optional) You can convert from the string by the specified type converter, you can enable the editing of the object string represented 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 (ITypeDescriptorContext context, System.Type sourceType) {if (sourceType == typeof (string)) return true; return base.CanConvertFrom (context, sourceType);} to enable editing target base class, the same Need to override the ConvertFROM method and make sure the value parameters are 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) Then 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 (suggCorr) Return so End If Catch Throw New ArgumentException (_ "can not" "& CStr (value) & _" " Convert to SPELLINGOPTIONS Type ") End Try End IF Return mybase.con vertFrom (context, culture, value) End Function // C # public override object ConvertFrom (ITypeDescriptorContext context, CultureInfo culture, object value) {if (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 (Colon 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 (); solverCheckwhileTyping = Boolean.Parse (checkWhileTyping); so.SpellCheckCAPS = Boolean.Parse (checkCaps); so.SuggestCorrections = Boolean.Parse (suggCorr); 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 see the target class using this class. You can do this by applying TypeConvertRibute to the Target Class (SperningOptions class in the example). 'Visual Basic' is applied to the TypeConverter feature of the SpellingOptions class. _ Public class spellingOptions ... End class // C # // Apply to the TypeConverter feature of the SpellingOptions class. [TypeConvertRIBUTE (TypeOf (SpellingOptionsConverter)), DescriptionAttribute ("Expands to view the application's spelling option.")] ​​Public class spellingOptions {...} Compile and run the option window application again. The following screen snapshot shows the current look at the option window. Figure 6: Custom data type with type converter displayed in PropertyGrid Note: If you only need to expand object support, it is only necessary to customize the string

TypeConverTeratTribute is applied to the class. will

ExpandableObjectConverter is specified as type converter type.

Adding a domain list and a simple drop-down list property support for an enumerated property that returns an enumeration based on the Enum type, the 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: StringConvertR {} Overwrite 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 ITypeDescriptorContext) As Boolean Return True End Function // C # public override bool GetStandardValuesSupported (ITypeDescriptorContext context) {return true;} return covering GetStandardValues ​​method and filled StandardValuesCollection standard values. 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 ITypeDescriptorContext) _ As StandardValuesCollection Return New StandardValuesCollection (New String () { "new file" _ "File 1", _ "Document 1"}) End Function // C # Public Override StandardValuesCollection getStandardValues ​​(iTRIPTORCONTEXT CONTEXT) {Return New StandardValuesCollection (New String [] {"New File", "File 1", "Document 1"});} (optional) If you want the user to type it in the drop-down list is not included in the drop-down list The value, please override the getStandardValexClusive 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 GetStandardValuesExclusive (ITypeDescriptorContext context) {return false;} class has its own type converter for displaying a dropdown list After you need to determine the goal of using 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' Application to the TypeConverter feature of the defaultfilename property. _ 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 (typeof (FileNameConverter)), CategoryAttribute ( "Document Settings")] public string DefaultFileName {get {return defaultFileName;} set {defaultFileName = value;}} Compile and run again Options window of the application. The following screen snapshot shows the current look at the option window. Note the appearance of the defaultfilename property. Figure 7: Displaying the drop-down domain list in the PropertyGrid provides custom UI as described above, .NET Framework Types Use the TypeConverter and UITYPEEDITOR classes (and other classes) to provide PropertyGrid editing support. 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 graphs for display attributes in PropertyGrid You can also provide your own drop-down list control, which is used to provide users with a controlled control with a 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.

转载请注明原文地址:https://www.9cbs.com/read-15211.html

New Post(0)