创建 PropertyGrid 控件
何处使用 PropertyGrid 控件
选择对象
自定义 PropertyGrid 控件
显示复杂属性
为属性提供自定义 UI
小结
' Visual BasicImports SystemImports System.DrawingImports System.ComponentModelImports System.Windows.FormsImports System.GlobalizationPublic 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 = "选项对话框" End SubEnd 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 = "选项对话框"; } [STAThread] static void Main() { Application.Run(new OptionsDialog()); }}
OptionsDialog
窗体即是选项窗口的开始。现在,我们创建一个名为
AppSettings
的类,其中包含映射到应用程序设置的所有属性。如果创建单独的类而不使用多个分散的变量,设置将更便于管理和维护。
' Visual BasicPublic Class AppSettings Private _saveOnClose As Boolean = True Private _greetingText As String = "欢迎使用应用程序!" 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 Property 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 Set End PropertyEnd Class//C#public class AppSettings{ private bool saveOnClose = true; private string greetingText = "欢迎使用应用程序!"; 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 AppVersion { get { return appVersion; } set { appVersion = value; } }}
OptionsDialog
构造函数中的代码,以创建一个
AppSettings
对象,并将其设置为
PropertyGrid.SelectedObject 属性的值。
' Visual Basic Public Sub New() MyBase.New() OptionsPropertyGrid = New PropertyGrid() OptionsPropertyGrid.Size = New Size(300, 250) Me.Controls.Add(OptionsPropertyGrid) Me.Text = "选项对话框"' 创建 AppSettings 类并在 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 = "选项对话框";// 创建 AppSettings 类并在 PropertyGrid 中显示该类。
AppSettings appset = new AppSettings();
OptionsPropertyGrid.SelectedObject = appset;
}
MaxRepeatRate
属性。 SettingsChanged
属性。 AppVersion
属性。 AppSettings
类。 AppSettings
类,以更改属性在
PropertyGrid 中的显示方式。
' Visual Basic<DefaultPropertyAttribute("SaveOnClose")> _
Public Class AppSettings Private _saveOnClose As Boolean = True Private _greetingText As String = "欢迎使用应用程序!" Private _maxRepeatRate As Integer = 10 Private _itemsInMRU As Integer = 4 Private _settingsChanged As Boolean = False Private _appVersion As String = "1.0"<CategoryAttribute("文档设置"), _
DefaultValueAttribute(True)> _
Public Property SaveOnClose() As Boolean Get Return _saveOnClose End Get Set(ByVal Value As Boolean) SaveOnClose = Value End Set End Property<CategoryAttribute("全局设置"), _
ReadOnlyAttribute(True), _
DefaultValueAttribute("欢迎使用应用程序!")> _
Public Property GreetingText() As String Get Return _greetingText End Get Set(ByVal Value As String) _greetingText = Value End Set End Property<CategoryAttribute("全局设置"), _
DefaultValueAttribute(4)> _
Public Property ItemsInMRUList() As Integer Get Return _itemsInMRU End Get Set(ByVal Value As Integer) _itemsInMRU = Value End Set End Property<DescriptionAttribute("以毫秒表示的文本重复率。"), _
CategoryAttribute("全局设置"), _
DefaultValueAttribute(10)> _
Public Property MaxRepeatRate() As Integer Get Return _maxRepeatRate End Get Set(ByVal Value As Integer) _maxRepeatRate = Value End Set End Property<BrowsableAttribute(False),
DefaultValueAttribute(False)> _
Public Property SettingsChanged() As Boolean Get Return _settingsChanged End Get Set(ByVal Value As Boolean) _settingsChanged = Value End Set End Property<CategoryAttribute("版本"), _
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 PropertyEnd Class//C#[DefaultPropertyAttribute("SaveOnClose")]
public class AppSettings{ private bool saveOnClose = true; private string greetingText = "欢迎使用应用程序!"; private int maxRepeatRate = 10; private int itemsInMRU = 4; private bool settingsChanged = false; private string appVersion = "1.0";[CategoryAttribute("文档设置"),
DefaultValueAttribute(true)]
public bool SaveOnClose { get { return saveOnClose; } set { saveOnClose = value;} }[CategoryAttribute("全局设置"),
ReadOnlyAttribute(true),
DefaultValueAttribute("欢迎使用应用程序!")]
public string GreetingText { get { return greetingText; } set { greetingText = value; } }[CategoryAttribute("全局设置"),
DefaultValueAttribute(4)]
public int ItemsInMRUList { get { return itemsInMRU; } set { itemsInMRU = value; } }[DescriptionAttribute("以毫秒表示的文本重复率。"),
CategoryAttribute("全局设置"),
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("版本"),
DefaultValueAttribute("1.0"),
ReadOnlyAttribute(true)]
public string AppVersion { get { return appVersion; } set { appVersion = value; } }}
AppSettings
类后,编译并运行该应用程序。下面的屏幕快照显示了应用程序的外观。
SaveOnClose
属性。 MaxRepeatRate
属性时,说明帮助窗格中将显示“以毫秒表示的文本重复率”。 SaveOnClose
属性显示在“文档设置”类别下。其他属性分别显示在“全局设置”和“版本”类别下。 SettingsChanged
属性将不再显示。 AppVersion
属性为只读。只读属性以灰显文本显示。 SaveOnClose
属性包含的值不是 true,该值将以粗体显示。PropertyGrid 使用粗体文本表示包含非默认值的属性。 AppSettings
类,为窗口大小(
Size 类型)、窗口字体(
Font 类型)和工具栏颜色(
Color 类型)添加新属性。
' Visual Basic<DefaultPropertyAttribute("SaveOnClose")> _Public Class AppSettings Private _saveOnClose As Boolean = True Private _greetingText As String = "欢迎使用应用程序!" 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("宋体", 9, FontStyle.Regular)
Private _toolbarColor As Color = SystemColors.Control
<CategoryAttribute("文档设置"), _ DefaultValueAttribute(True)> _ Public Property SaveOnClose() As Boolean Get Return _saveOnClose End Get Set(ByVal Value As Boolean) SaveOnClose = Value End Set End Property<CategoryAttribute("文档设置")> _
Public Property WindowSize() As Size
Get
Return _windowSize
End Get
Set(ByVal Value As Size)
_windowSize = Value
End Set
End Property
<CategoryAttribute("文档设置")> _
Public Property WindowFont() As Font
Get
Return _windowFont
End Get
Set(ByVal Value As Font)
_windowFont = Value
End Set
End Property
<CategoryAttribute("全局设置")> _
Public Property ToolbarColor() As Color
Get
Return _toolbarColor
End Get
Set(ByVal Value As Color)
_toolbarColor = Value
End Set
End Property
<CategoryAttribute("全局设置"), _ ReadOnlyAttribute(True), _ DefaultValueAttribute("欢迎使用应用程序!")> _ Public Property GreetingText() As String Get Return _greetingText End Get Set(ByVal Value As String) _greetingText = Value End Set End Property <CategoryAttribute("全局设置"), _ DefaultValueAttribute(4)> _ Public Property ItemsInMRUList() As Integer Get Return _itemsInMRU End Get Set(ByVal Value As Integer) _itemsInMRU = Value End Set End Property <DescriptionAttribute("以毫秒表示的文本重复率。"), _ CategoryAttribute("全局设置"), _ DefaultValueAttribute(10)> _ Public Property MaxRepeatRate() As Integer Get Return _maxRepeatRate End Get Set(ByVal Value As Integer) _maxRepeatRate = Value End Set End Property <BrowsableAttribute(False), DefaultValueAttribute(False)> _ Public Property SettingsChanged() As Boolean Get Return _settingsChanged End Get Set(ByVal Value As Boolean) _settingsChanged = Value End Set End Property <CategoryAttribute("版本"), _ 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 PropertyEnd Class//C#[DefaultPropertyAttribute("SaveOnClose")]public class AppSettings{ private bool saveOnClose = true; private string greetingText = "欢迎使用应用程序!"; 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("宋体", 9, FontStyle.Regular);
private Color toolbarColor = SystemColors.Control;
[CategoryAttribute("文档设置"), DefaultValueAttribute(true)] public bool SaveOnClose { get { return saveOnClose; } set { saveOnClose = value;} }[CategoryAttribute("文档设置")]
public Size WindowSize
{
get { return windowSize; }
set { windowSize = value;}
}
[CategoryAttribute("文档设置")]
public Font WindowFont
{
get {return windowFont; }
set { windowFont = value;}
}
[CategoryAttribute("全局设置")]
public Color ToolbarColor
{
get { return toolbarColor; }
set { toolbarColor = value; }
}
[CategoryAttribute("全局设置"), ReadOnlyAttribute(true), DefaultValueAttribute("欢迎使用应用程序!")] public string GreetingText { get { return greetingText; } set { greetingText = value; } } [CategoryAttribute("全局设置"), DefaultValueAttribute(4)] public int ItemsInMRUList { get { return itemsInMRU; } set { itemsInMRU = value; } } [DescriptionAttribute("以毫秒表示的文本重复率。"), CategoryAttribute("全局设置"), 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("版本"), DefaultValueAttribute("1.0"), ReadOnlyAttribute(true)] public string AppVersion { get { return appVersion; } set { appVersion = value; } }}
WindowFont
属性带有一个省略号 (...) 按钮,按下该按钮将显示字体选择对话框。此外,还可以展开该属性以显示更多的
Font 属性。某些
Font 属性提供有关字体的值和详细信息的下拉列表。您可以展开
WindowSize
属性以显示
Size 类型的更多属性。最后,请注意,
ToolbarColor
属性包含一个选定颜色的样本,以及一个用于选择不同颜色的自定义下拉列表。对于这些以及其他数据类型,.NET 框架提供了其他的类,可以使在
PropertyGrid 中的编辑更加容易。
AppSettings
类中添加另外两个属性,即
DefaultFileName
和
SpellCheckOptions
。
DefaultFileName
属性用于获取或设置字符串;
SpellCheckOptions
属性用于获取或设置
SpellingOptions
类的实例。
SpellingOptions
类是一个新类,用于管理应用程序的拼写检查属性。对于何时创建单独的类以管理对象的属性,并没有严格的规定,而取决于您的整个类设计。将
SpellingOptions
类定义添加到应用程序项目中 - 可以添加到新文件中,也可以添加到窗体源代码的下方。
' Visual Basic<DescriptionAttribute("展开以查看应用程序的拼写选项。")> _Public Class SpellingOptions Private _spellCheckWhileTyping As Boolean = True Private _spellCheckCAPS As Boolean = False Private _suggestCorrections As Boolean = True <DefaultValueAttribute(True)> _ Public Property SpellCheckWhileTyping() As Boolean Get Return _spellCheckWhileTyping End Get Set(ByVal Value As Boolean) _spellCheckWhileTyping = Value End Set End Property <DefaultValueAttribute(False)> _ Public Property SpellCheckCAPS() As Boolean Get Return _spellCheckCAPS End Get Set(ByVal Value As Boolean) _spellCheckCAPS = Value End Set End Property <DefaultValueAttribute(True)> _ Public Property SuggestCorrections() As Boolean Get Return _suggestCorrections End Get Set(ByVal Value As Boolean) _suggestCorrections = Value End Set End PropertyEnd Class//C#[DescriptionAttribute("展开以查看应用程序的拼写选项。")]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 suggestCorrections; } set { suggestCorrections = value; } }}
SpellcheckOptions
属性的外观。与 .NET 框架类型不同,它不展开或显示自定义的字符串表示。如果要在自己的复杂类型中提供与 .NET 框架类型相同的编辑体验,该如何处理呢?.NET 框架类型使用
TypeConverter 和
UITypeEditor 类提供大部分
PropertyGrid 编辑支持,您也可以使用这些类。
SpellingOptions
属性,您需要创建
TypeConverter。
TypeConverter 提供了从一种类型转换为另一种类型的方法。
PropertyGrid 使用
TypeConverter 将对象类型转换为
String,并使用该
String 在网格中显示对象值。在编辑过程中,
TypeConverter 会将
String 转换回对象类型。.NET 框架提供的
ExpandableObjectConverter 类可以简化这一过程。
' Visual BasicPublic Class SpellingOptionsConverter Inherits ExpandableObjectConverterEnd Class//C#public class SpellingOptionsConverter:ExpandableObjectConverter { }
destinationType
参数与使用此类型转换器的类(示例中的 SpellingOptions
类)的类型相同,则覆盖 CanConvertTo 方法并返回 true;否则返回基类 CanConvertTo 方法的值。' Visual BasicPublic 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);}
destinationType
参数是一个 String,并且值的类型与使用此类型转换器的类(示例中的 SpellingOptions
类)相同。如果其中任一情况为 false,都将返回基类 ConvertTo 方法的值;否则,返回值对象的字符串表示。字符串表示需要使用唯一分隔符将类的每个属性隔开。由于整个字符串都将显示在 PropertyGrid 中,因此需要选择一个不会影响可读性的分隔符,逗号的效果通常比较好。' Visual BasicPublic 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 SpellingOptions) Then Dim so As SpellingOptions = CType(value, SpellingOptions) Return "在键入时检查: " & so.SpellCheckWhileTyping & _ ",检查大小写: " & so.SpellCheckCAPS & _ ",建议更正: " & 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(System.String) && value is SpellingOptions){ SpellingOptions so = (SpellingOptions)value; return "在键入时检查:" + so.SpellCheckWhileTyping + ",检查大小写: " + so.SpellCheckCAPS + ",建议更正: " + so.SuggestCorrections; } return base.ConvertTo(context, culture, value, destinationType);}
' Visual BasicPublic 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);}
SpellingOptions
类)的新实例。您需要根据值参数解析类的每个属性的值。了解在 ConvertTo 方法中创建的分隔字符串的格式将有助于您的解析。' Visual BasicPublic 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 suggCorr 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( _ "无法将“" & CStr(value) & _ "”转换为 SpellingOptions 类型") End Try End If Return MyBase.ConvertFrom(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 suggCorr = s.Substring(colon + 1); SpellingOptions so = new SpellingOptions(); so.SpellCheckWhileTyping =Boolean.Parse(checkWhileTyping); so.SpellCheckCAPS = Boolean.Parse(checkCaps); so.SuggestCorrections = Boolean.Parse(suggCorr); return so; } } catch { throw new ArgumentException( "无法将“" + (string)value + "”转换为 SpellingOptions 类型"); } } return base.ConvertFrom(context, culture, value);}
SpellingOptions
类)来执行此操作。' Visual Basic' 应用于 SpellingOptions 类的 TypeConverter 特性。<TypeConverter(GetType(SpellingOptionsConverter)),
_DescriptionAttribute("展开以查看应用程序的拼写选项。")> _Public Class SpellingOptions ...End Class//C#// 应用于 SpellingOptions 类的 TypeConverter 特性。 [TypeConverterAttribute(typeof(SpellingOptionsConverter)),
DescriptionAttribute("展开以查看应用程序的拼写选项。")]public class SpellingOptions{ ... }
注意:
如果只需要可展开对象支持,而不需要自定义字符串表示,则只需将
TypeConverterAttribute 应用到类中。将
ExpandableObjectConverter 指定为类型转换器类型。
DefaultFileName
属性添加到
AppSettings
类。下一步是在
PropertyGrid 中显示属性的下拉列表,以提供域列表。
DefaultFileName
属性属于 String 类型,因此可以从 StringConverter 中继承。如果属性类型的类型转换器不存在,则可以从 TypeConverter 继承;这里并不需要。' Visual BasicPublic Class FileNameConverter Inherits StringConverterEnd Class//C#public class FileNameConverter: StringConverter { }
' Visual BasicPublic Overloads Overrides Function GetStandardValuesSupported( _ ByVal context As ITypeDescriptorContext) As Boolean Return TrueEnd Function//C#public override bool GetStandardValuesSupported( ITypeDescriptorContext context) { return true;}
' Visual BasicPublic Overloads Overrides Function GetStandardValues( _ ByVal context As ITypeDescriptorContext) _ As StandardValuesCollection Return New StandardValuesCollection(New String() {"新文件", _ "文件1", _ "文档1"})End Function //C#public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { return new StandardValuesCollection(new string[]{"新文件", "文件1", "文档1"});}
' Visual BasicPublic Overloads Overrides Function GetStandardValuesExclusive( _ ByVal context As ITypeDescriptorContext) As Boolean Return FalseEnd Function//C#public override bool GetStandardValuesExclusive( ITypeDescriptorContext context) { return false;}
DefaultFileName
属性,因为类型转换器是针对该属性的。将 TypeConverterAttribute 应用到目标属性中。' Visual Basic' 应用到 DefaultFileName 属性的 TypeConverter 特性。<TypeConverter(GetType(FileNameConverter)),
_
CategoryAttribute("文档设置")> _Public Property DefaultFileName() As String Get Return _defaultFileName End Get Set(ByVal Value As String) _defaultFileName = Value End SetEnd Property//C#// 应用到 DefaultFileName 属性的 TypeConverter 特性。 [TypeConverter(typeof(FileNameConverter)),
CategoryAttribute("文档设置")]public string DefaultFileName{ get{ return defaultFileName; } set{ defaultFileName = value; }}
DefaultFileName
属性的外观。
0人
|
了这篇文章 |
点击图片可刷新验证码请点击后输入验证码博客过2级,无需填写验证码
同时赞一个