根据某种条件,在运行时C#Winforms中的propertyGrid中具有特定类别名称的所有属性



我的应用程序中有一个属性网格,该网格在运行时显示了选定控件的属性。

最近,需要在已经存在的控件中添加一些额外的属性。为了适应这一点,引入了一个新类别,添加了新的属性。

现在,我正在寻找一种机制,可以根据应用程序中的运行时条件隐藏这些新添加的属性。但是我没有适当的解决方案。

新添加的代码:

    [ReadOnly(true)]
    [Browsable(true)]
    [Category("Extra")]
    public int? FormID { get; set; }
    [Browsable(true)]
    [Category("Extra")]
    public int? jrxml_Id { get; set; }

我期望的工作:

    [ReadOnly(true)]
    [Browsable(matchSomeRunTimeCondition)]
    [Category("Extra")]
    public int? FormID { get; set; }
    [Browsable(matchSomeRunTimeCondition)]
    [Category("Extra")]
    public int? jrxml_Id { get; set; }

为什么它不起作用?

因为Browsable属性只能接受常数。matchSomeRunTimeCondition不是常数。当应用程序仍在运行时,用户可以在他想要的时候更改它。

在代码中,如果我可以用来使这些函数在运行时间内使这些函数使用,我将真的很奇怪,如果有人可以帮助我编写这样的功能或条件性语句:

if(属性的类别==" extra"){

//请勿在PropertyGrid中显示此属性。

//或换句话说,在运行时制作browasable属性false。

}

我应用程序中的不同控件具有不同的属性,需要在运行时隐藏。

我有所有这些属性的列表,我想隐藏在属性格里德中显示的应用程序中选择的每个对象中。

,但我需要帮助如何实现这一目标。

注意:我开放的是将可浏览属性设置为True/false在编译时。但是我希望一种机制在我的应用程序中设置此机制,并需要帮助。

寻找代码解决方案。

我的编码环境(由于公司的传统支持而无法改变):

  • Visual Studio 2010
  • .net 3.5
  • Windows 10 OS(是的)

使用TNTINMN发布的答案,我修改了我的代码,以使其在运行时隐藏所有选择性属性。

private void ChangeVisibilityBasedOnMode( ref object[] v) {
    if (matchSomeRunTimeCondition) {
        List<string> PropertiesToHide = new List<string> {
            "FormID",
            "jrxml_Id",
        };
        foreach (var vObject in v) {
            var properties = GetProperties(vObject);
            foreach (var p in properties) {
                foreach (string hideProperty in PropertiesToHide ) {
                    if (p.Name.ToLower() == hideProperty.ToLower()) {
                        setBrowsableProperty(hideProperty, false, vObject);
                    }
                }
            }
        }
    }
}
private void setBrowsableProperty(string strPropertyName, bool bIsBrowsable, object vObject) {
    try {
        PropertyDescriptor theDescriptor = TypeDescriptor.GetProperties(vObject.GetType())[strPropertyName];
        BrowsableAttribute theDescriptorBrowsableAttribute = (BrowsableAttribute)theDescriptor.Attributes[typeof(BrowsableAttribute)];
        FieldInfo isBrowsable = theDescriptorBrowsableAttribute.GetType().GetField("Browsable", BindingFlags.IgnoreCase | BindingFlags.NonPublic | BindingFlags.Instance);
        isBrowsable.SetValue(theDescriptorBrowsableAttribute, bIsBrowsable);
    } catch (Exception) { }
}

也感谢Neoikon的出色帖子(有条件的" Browsable"属性),我从中达到了最终解决方案。

这是对我有用的

    private void SetVisibleSearchOptions(Type searchType, bool visible)
    {
        try
        {
            TypeDescriptor.AddAttributes(searchType, new BrowsableAttribute(visible));
        }
        catch (Exception ex)
        {
        }
    }

最新更新