c# - 有没有办法为类的特定属性隐藏一些枚举值?

标签 c# .net winforms windows-forms-designer propertygrid

我有枚举,例如:

public enum Color
{
  red,
  green,
  blue
}

并且有两个类。具有枚举的属性。

public class ClassA
{
    public Color Color{get;set;}
}

public class ClassB
{
    [InvisibleFlag(Color.red)]  // I want something like that
    public Color Color{get;set;}
}

现在,在 Windows 窗体设计器中,我只想隐藏 ClassB 的 Color 枚举中的红旗。

我知道我可以创建一个单独的枚举。但为什么重复值?我只举了一个简单的例子。

Something I guess might help for superior who can help me at it.

Descriptor API. which I hate. ;(

可能类似于 TypeDescriptor.AddAttributes(object, new BrowsableAttribute(false));

answer在这种情况下将不起作用。我不想将 Browsable 属性应用于枚举标志,因为它在所有类的属性网格中隐藏了该标志。我希望能够仅隐藏特定类的特定枚举值,而不是所有类。

最佳答案

帮助您在 PropertyGrid 中显示枚举值的类是 EnumConverter以及负责在 GetStandardValues 中列出枚举值的方法.

因此,作为一种选择,您可以通过从 EnumConverter 派生并覆盖其 GetStandardValues 以返回基于特定属性的标准值来创建自定义枚举转换器类你有属性(property)。

如何在 TypeConverter 方法中获取属性的属性等上下文信息?

ITypeDescriptorContext 的实例类传递给 TypeConverter 方法的 context 参数。使用该类,您可以访问正在编辑的对象,并且正在编辑的属性的属性描述符具有一些有用的属性。在这里你可以依靠
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;
    }
}

作为用法示例:

public class ClassA
{
    public Color Color { get; set; }
}

public class ClassB
{
    [ExcludeColor(Color.White, Color.Black)]
    public Color Color { get; set; }
}

enter image description here

关于c# - 有没有办法为类的特定属性隐藏一些枚举值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59024032/

相关文章:

c# - 使用 Visual Studio 2010 Express 将 .doc 保存/转换为 .html

c# - Windows窗体背景透明,无法点击

c# - 单击一次部署和解决方案配置

c# - 模态内的多个 View

c# - 为了 DI 的目的,围绕静态类的实例包装器是一种反模式吗?

c# - JWT header 算法 : is "hs256" the same as "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256"

winforms - 当绑定(bind)到组合框 SelectedItem 时,仅在失去焦点时才会通知更改。选择更改时如何通知?

c# - 将记录插入到 SQL Server CE 数据库移动到另一个线程? C# Compact Framework 3.5

c# - C#中是否有一个集中的错误处理过程

.net - 如何从网页确定主机安装的 ASP.NET 版本