【问题标题】:C# Enabling/Disabling fields in PropertyGridC# 启用/禁用 PropertyGrid 中的字段
【发布时间】:2013-09-24 15:03:21
【问题描述】:

我正在开发一个用户控件库,我需要在其中为程序员提供一个属性网格来自定义我的控件的属性。
如果程序员使用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?

【问题讨论】:

标签: c# propertygrid


【解决方案1】:

(由 OP 在问题编辑中回答。转换为社区 wiki 答案。请参阅Question with no answers, but issue solved in the comments (or extended in chat)

OP 写道:

解决了!

感谢@Simon Mourier!发布编辑后的代码。 结果:

【讨论】:

    猜你喜欢
    • 2023-03-31
    • 2012-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-04
    相关资源
    最近更新 更多