public static void SetPropertyVisibility(object obj, string propertyName, bool visible)
{
Type type = typeof(BrowsableAttribute);
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(obj);
if (null == props.Find(propertyName, false))
{
return;
}
AttributeCollection attrs = props[propertyName].Attributes;
FieldInfo fld = type.GetField("Browsable", BindingFlags.Public | BindingFlags.Instance);
if (null == fld)
{
return;
}
fld.SetValue(attrs[type], visible);
}
这个函数在.net4中是可以用的,但是.net6中用的话fld 得到的值为null,好像不支持了,那有其它方法吗。
你为什么会有这个需求呢?这个BrowsableAttribute本身就是静态只读的,只能在窗口设计时调整的。能否详细说明一下你的使用场景好判断是否有更好的解决方式。
https://docs.microsoft.com/zh-cn/dotnet/api/system.componentmodel.browsableattribute?redirectedfrom=MSDN&view=net-6.0
应该是支持的
你给类显示的加上[Browsable(true)] 这个标识 试试
https://stackoverflow.com/questions/31321637/changing-browsable-attribute-at-runtime-c
试试这个看看行不行
[TypeConverter(typeof(SheathingOptionsConverter))]
[Browsable(false)] // changes at runtime
public override Sheathing SheathingType { get; set; }
private bool updateWhenChanged;
[RefreshProperties(RefreshProperties.All)]
public bool UpdateWhenChanged
{
get => updateWhenChanged;
set
{
if (updateWhenChanged != value)
{
SetBrowsableAttributeValue(nameof(SheathingType), value);
updateWhenChanged = value;
}
}
}
private void SetBrowsableAttributeValue(string attribute, object value)
{
var descriptor = TypeDescriptor.GetProperties(GetType())[attribute];
var attrib = (BrowsableAttribute)descriptor.Attributes[typeof(BrowsableAttribute)];
var isBrow = attrib.GetType().GetField("browsable", BindingFlags.NonPublic | BindingFlags.Instance);
isBrow.SetValue(attrib, value);
}
public bool Browsable { get; }
可以参考这个地址
https://docs.microsoft.com/zh-cn/dotnet/api/system.componentmodel.browsableattribute.browsable?view=net-6.0
看看我这篇,已确认
适用于产品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6
https://docs.microsoft.com/zh-cn/dotnet/api/system.componentmodel.browsableattribute.browsable?redirectedfrom=MSDN&view=net-6.0#System_ComponentModel_BrowsableAttribute_Browsable
望采纳哦谢谢