我正在开发一个用户控件库,在其中我需要为程序员提供一个属性网格来自定义我的控件的属性。
如果程序员使用
则
如何做到这一点?
如果程序员使用
System.Windows.Forms.PropertyGrid
(或Visual Studio的设计器),则
System.Windows.Forms.PropertyGrid
中的一些属性字段应该根据同一用户控件的某些其他属性启用/禁用。如何做到这一点?
示例场景
这不是实际示例,仅为说明。
例如:UserControl1
有两个自定义属性:
MyProp_Caption: 一个字符串
和
MyProp_Caption_Visible: 一个布尔值
现在,只有当MyProp_Caption_Visible为true时,MyProp_Caption才能在PropertyGrid中启用。
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 is a simple Form with the following two data members
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字段?