我正在开发一个用户控件库,我需要在其中为程序员提供一个属性网格来自定义我的控件的属性。
如果程序员使用System.Windows.Forms.PropertyGrid
(或 Visual Studio 的设计器)
中的某些属性字段,System.Windows.Forms.PropertyGrid
则应根据同一用户控件的某些其他属性启用/禁用。
怎么做?
示例场景
这不是实际的例子,而只是一个说明。
例如:UserControl1
有两个自定义属性:
MyProp_Caption:一个字符串
和
MyProp_Caption_Visible:一个布尔值
现在,只有当MyProp_Caption_Visible为 true时,才应在 PropertyGrid 中启用MyProp_Caption 。
UserControl1 的示例代码
public class UserControl1: UserControl <br/>
{
public UserControl1()
{
// skipping details
// label1 is a System.Windows.Forms.Label
InitializeComponent();
}
[Category("My Prop"),
Browsable(true),
Description("Get/Set Caption."),
DefaultValue(typeof(string), "[Set Caption here]"),
RefreshProperties(RefreshProperties.All),
ReadOnly(false)]
public string MyProp_Caption
{
get
{
return label1.Text;
}
set
{
label1.Text = value;
}
}
[Category("My Prop"),
Browsable(true),
Description("Show/Hide Caption."),
DefaultValue(true)]
public bool MyProp_Caption_Visible
{
get
{
return label1.Visible;
}
set
{
label1.Visible = value;
// added as solution:
// do additional stuff to enable/disable
// MyProp_Caption prop in the PropertyGrid depending on this value
PropertyDescriptor propDescr = TypeDescriptor.GetProperties(this.GetType())["MyProp_Caption"];
ReadOnlyAttribute attr = propDescr.Attributes[typeof(ReadOnlyAttribute)] as ReadOnlyAttribute;
if (attr != null)
{
System.Reflection.FieldInfo aField = attr.GetType().GetField("isReadOnly", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
aField.SetValue(attr, !label1.Visible);
}
}
}
}
此 UserControl1 上 PropertyGrid 的示例代码
tstFrm 是一个简单的 Form 有以下两个数据成员
private System.Windows.Forms.PropertyGrid propertyGrid1; private UserControl1 userControl11;
我们可以通过 propertyGrid1 自定义 userControl1,如下所示:
public partial class tstFrm : Form
{
public tstFrm()
{
// tstFrm embeds a PropertyGrid propertyGrid1
InitializeComponent();
propertyGrid1.SelectedObject = userControl11;
}
}
如何根据 MyProp_Caption_Visible 的值启用/禁用属性网格中的字段 MyProp_Caption?