WPF 拉取枚举说明(如果可用于填充组合框)



我有一个枚举,其中某些项目具有DescriptionAttribute集。

我想在我的 WPF 应用中有一个下拉列表,用户可以在其中从枚举中选择一个项,但我希望下拉列表使用"说明"值(如果可用(。

我编写了代码来获取值列表(如果可用,则提取说明,否则使用 name(,并且我有我尝试用于对象提供程序的 XAML,但它没有填充任何内容。

如果我将 GetValues 与 ObjectType 定义一起使用,则 XAML 有效。

C#

public static string[] GetDescriptions(Enum enumType)
{
List<string> descriptions = new List<string>();
Type t = enumType.GetType();
foreach(string name in Enum.GetNames(t))
{
FieldInfo field = t.GetField(name);
object[] d = field.GetCustomAttributes(typeof(DescriptionAttribute), true);
if (d.Any())
{
descriptions.Add(((DescriptionAttribute)d[0]).Description);
}
else
{
descriptions.Add(name);
}
}
return descriptions.ToArray();
}

XAML:

<ObjectDataProvider x:Key="SkillEnum" MethodName="KwCommon:EnumExtensions.GetDescriptions" >
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="local:SkillLevels"/>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>

我做了类似的事情来将枚举绑定到组合框。 我有几个辅助函数:

public static string GetEnumDescription<TEnum>(this TEnum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes != null && attributes.Length > 0)
{
return attributes[0].Description;
}
else
{
return value.ToString();
}
}

以及将枚举转换为键值对列表的函数:

public static IEnumerable<KeyValuePair<string, Enum>> GetEnumList(this Enum t, bool useDescription = true)
{
return Enum.GetValues(t.GetType()).Cast<Enum>().Select(e => new KeyValuePair<string, Enum>(useDescription == true ? e.GetEnumDescription() : e.ToString(), e)).ToList();
}

我创建了一个转换器(在我的例子中,标记扩展,这是该标记扩展的链接(

public class EnumToListConverter : ConverterMarkupExtension<EnumToListConverter>
{
public override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
bool useDescription = true;
if (parameter is bool p)
{
useDescription = p;
}
if (value is Enum e)
{
return EnumHelper.GetEnumList(e, useDescription);
}
return DependencyProperty.UnsetValue;
}
public override object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return DependencyProperty.UnsetValue;
}
}

然后在我的 xaml 中,我像这样使用它:

<ComboBox Grid.Column="1" Grid.Row="1" ItemsSource="{Binding Applicant.RentOrOwn, Converter={local:EnumToListConverter}, Mode=OneTime}" SelectedValuePath="Value" DisplayMemberPath="Key" SelectedValue="{Binding Applicant.RentOrOwn, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, ValidatesOnExceptions=True, ValidatesOnNotifyDataErrors=True}"></ComboBox>

在这个例子中,我有一个具有RentOrOwn枚举属性的申请人类。 这将显示枚举中所有可用的值,然后在用户单击 MVVM 样式的新选定值时更新 RentOrOwn 属性。

相关内容

最新更新