asd*_*000 4 .net c# enums windows-forms-designer winforms
我有枚举可以说例如:
public enum Color
{
red,
green,
blue
}
Run Code Online (Sandbox Code Playgroud)
并有两个班。具有枚举的属性。
public class ClassA
{
public Color Color{get;set;}
}
public class ClassB
{
[InvisibleFlag(Color.red)] // I want something like that
public Color Color{get;set;}
}
Run Code Online (Sandbox Code Playgroud)
现在在Windows Forms Designer中,我只想仅从ClassB的Color枚举中隐藏红色标记。
我知道我可以创建一个单独的枚举。但是为什么要重复值呢?我只举了一个简单的例子。
我猜可能会对上级可以帮助我的事情有所帮助。
描述符API。我讨厌 ;(
也许像 TypeDescriptor.AddAttributes(object, new BrowsableAttribute(false));
在这种情况下,此答案将无效。我不想将Browsable属性应用于枚举标志,因为它在所有类的属性网格中都隐藏了该标志。我希望仅对特定类而不对所有类隐藏特定的枚举值。
可以帮助您在中显示枚举值的类PropertyGrid是,EnumConverter并可以在中列出枚举值的方法GetStandardValues。
因此,作为一种选择,您可以通过派生自定义的枚举转换器类EnumConverter并对其GetStandardValues进行重写以基于该属性具有的特定属性来返回标准值,从而创建自定义枚举转换器类。
如何在TypeConverter方法中上下文信息(如属性的属性)?
ITypeDescriptorContext类的实例传递给方法的context参数TypeConverter。使用该类,您可以访问正在编辑的对象,并且正在编辑的属性的属性描述符具有一些有用的属性。在这里,您可以依赖
PropertyDescriptor上下文的属性并获取Attributes和检查是否已为属性设置了我们感兴趣的特定属性。
例
[TypeConverter(typeof(ExcludeColorTypeConverter))]
public enum Color
{
Red,
Green,
Blue,
White,
Black,
}
public class ExcludeColorAttribute : Attribute
{
public Color[] Exclude { get; private set; }
public ExcludeColorAttribute(params Color[] exclude)
{
Exclude = exclude;
}
}
public class ExcludeColorTypeConverter : EnumConverter
{
public ExcludeColorTypeConverter() : base(typeof(Color))
{
}
public override StandardValuesCollection GetStandardValues(
ITypeDescriptorContext context)
{
var original = base.GetStandardValues(context);
var exclude = context.PropertyDescriptor.Attributes
.OfType<ExcludeColorAttribute>().FirstOrDefault()?.Exclude
?? new Color[0];
var excluded = new StandardValuesCollection(
original.Cast<Color>().Except(exclude).ToList());
Values = excluded;
return excluded;
}
}
Run Code Online (Sandbox Code Playgroud)
作为用法示例:
public class ClassA
{
public Color Color { get; set; }
}
public class ClassB
{
[ExcludeColor(Color.White, Color.Black)]
public Color Color { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
97 次 |
| 最近记录: |