c# - 将具有可变自定义数据的自定义属性附加到 PropertyGrid 中的类属性
问题描述
我从线程中获取了以下代码: TypeConverter reuse in PropertyGrid .NET winforms
代码示例来自 Simon Mourier 对上述线程的回复
public class Animals
{
// both properties have the same TypeConverter, but they use different custom attributes
[TypeConverter(typeof(ListTypeConverter))]
[ListTypeConverter(new [] { "cat", "dog" })]
public string Pets { get; set; }
[TypeConverter(typeof(ListTypeConverter))]
[ListTypeConverter(new [] { "cow", "sheep" })]
public string Others { get; set; }
}
// this is your custom attribute
// Note attribute can only use constants (as they are added at compile time), so you can't add a List object here
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class ListTypeConverterAttribute : Attribute
{
public ListTypeConverterAttribute(string[] list)
{
List = list;
}
public string[] List { get; set; }
}
// this is the type converter that knows how to use the ListTypeConverterAttribute attribute
public class ListTypeConverter : TypeConverter
{
public override bool GetStandardValuesSupported(ITypeDescriptorContext context) => true;
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
var list = new List<string>();
// the context contains the property descriptor
// the property descriptor has all custom attributes defined on the property
// just get it (with proper null handling)
var choices = context.PropertyDescriptor.Attributes.OfType<ListTypeConverterAttribute>().FirstOrDefault()?.List;
if (choices != null)
{
list.AddRange(choices);
}
return new StandardValuesCollection(list);
}
}
这种方法似乎是可能的,因为我在以下两个线程中也看到了它:http: //geekswithblogs.net/abhijeetp/archive/2009/01/10/dynamic-attributes-in-c.aspx StringConverter GetStandardValueCollection
我可以在 Animal 类中找到具有 ListTypeConverter 自定义属性的属性,并遍历它们
var props = context.Instance.GetType().GetProperties().Where(
prop => Attribute.IsDefined(prop, typeof(ListTypeConverterAttribute))).ToList();
我遇到的问题是 Simon 和其他人提供的代码需要 context.PropertyDescriptor,就我而言
context.PropertyDescriptor == null
如何找到调用 ListTypeConverter 的 Animal 类属性,以便在
return new StandardValuesCollection(list);
解决方案
推荐阅读
- ios - 当视图在 SwiftUI 中消失时如何隐藏 NavigationBar?
- javascript - 渲染从父组件传递到模态子组件的数据反应
- xamarin.forms - 如何删除xamarin表单ios中的视觉材料条目下划线
- java - Java不能显示JPanel,但是能显示JLabel?
- react-native - 如何在 react-native 中实现三角形的内角半径
- c - 为什么我不能在 C 中用 %7.d 或其他 %xd 打印 0
- php - PHP,致命错误:从另一个类调用未定义的方法调用函数
- java - JPA 存储库删除操作是否同步?
- c++ - 使用 SIMD 有效地评估大型多项式
- sql - 您好我想要一个 SQL 递归查询,以便查询的结果需要应用回同一个查询,直到查询结果变为零