在运行时更改可浏览属性(C#)

Nic*_*ert 6 c# treeview propertygrid attributes

我试图在运行时更改我的一个类中的变量的Browsable属性.包含该属性的类如下所示:

public class DisplayWallType : WallType
    {
        [TypeConverter(typeof(SheathingOptionsConverter))]
        [Browsable(false)]
        public override Sheathing SheathingType { get; set; }

        public DisplayWallType(string passedName, string passedType, bool passedMirrorable, Distance passedHeight, string passedStudPattern, Distance passedStudSpacing, VaporBarrier passedBarrier)
            : base(passedName, passedType, passedMirrorable, passedHeight, passedStudPattern, passedStudSpacing, passedBarrier)
        {

        }

        /// <summary>
        /// Empty constructor for XML serialization
        /// </summary>
        public DisplayWallType()
        {

        }
    }
Run Code Online (Sandbox Code Playgroud)

我最初为SheathingType将其设置为false,因为我不希望该属性以我的应用程序的第一种形式显示.但是,我确实希望它在我的第二种形式中可见,所以我有这种方法来改变它

private void _makeSheathingVisible(DisplayWallType wallTypeToMakeSheathingVisible)
        {
            PropertyDescriptor descriptor = TypeDescriptor.GetProperties(wallTypeToMakeSheathingVisible.GetType())["SheathingType"];
            BrowsableAttribute attrib = (BrowsableAttribute)descriptor.Attributes[typeof(BrowsableAttribute)];
            FieldInfo isBrow = attrib.GetType().GetField("browsable", BindingFlags.NonPublic | BindingFlags.Instance);
            isBrow.SetValue(attrib, true);
        }
Run Code Online (Sandbox Code Playgroud)

上面的方法采用DisplayWallType对象并确保将Browsable设置为true.我的第二种形式是树形视图和属性网格.树视图使用DisplayWallType实例填充,当选择一个时,将其传递给该方法,以便SheathingType在PropertiesGrid中显示父类的其余属性.

在此输入图像描述

但是,SheathingType仍然没有显示为属性,所以我的方法有问题,但我不知道是什么

小智 1

除非您有明确的声明,否则您无法获取Browsable一个确切属性的属性TypeDescriptor。在您的情况下,GetField("browsable")将返回FieldInfo所有属性并将它们切换为可见 true。如果您有一些属性并将一个可浏览设置为 false,也会出现同样的情况 - 它将隐藏所有属性。

为所需属性提供自定义 TypeDescriptor 或使用一些解决方案,例如https://www.codeproject.com/articles/7852/propertygrid-utilities