WPF 将 ListBox 绑定到枚举,显示描述属性 [英] WPF Binding a ListBox to an enum, displaying the Description Attribute

查看:41
本文介绍了WPF 将 ListBox 绑定到枚举,显示描述属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用 ObjectDataProvider 方法将 ListBox 绑定到枚举,并以某种方式为其设置样式以显示 Description 属性?如果是这样,人们将如何做这件事......?

Is it possible to use the ObjectDataProvider method to bind a ListBox to an enum, and style it somehow to display the Description attriibute? If so how would one go about doing this...?

推荐答案

是的,这是可能的.这将做到.假设我们有枚举

Yes, it is possible. This will do it. Say we have the enum

public enum MyEnum
{
    [Description("MyEnum1 Description")]
    MyEnum1,
    [Description("MyEnum2 Description")]
    MyEnum2,
    [Description("MyEnum3 Description")]
    MyEnum3
}

然后我们可以使用 ObjectDataProvider 作为

Then we can use the ObjectDataProvider as

xmlns:MyEnumerations="clr-namespace:MyEnumerations"

<ObjectDataProvider MethodName="GetValues"
                ObjectType="{x:Type sys:Enum}"
                x:Key="MyEnumValues">
    <ObjectDataProvider.MethodParameters>
        <x:Type TypeName="MyEnumerations:MyEnum" />
    </ObjectDataProvider.MethodParameters>
</ObjectDataProvider>

对于 ListBox,我们将 ItemsSource 设置为 MyEnumValues 并应用带有转换器的 ItemTemplate.

And for the ListBox we set the ItemsSource to MyEnumValues and apply an ItemTemplate with a Converter.

<ListBox Name="c_myListBox" SelectedIndex="0" Margin="8"
        ItemsSource="{Binding Source={StaticResource MyEnumValues}}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Converter={StaticResource EnumDescriptionConverter}}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

在转换器中我们得到描述并返回它

And in the converter we get the description and return it

public class EnumDescriptionConverter : IValueConverter
{
    private string GetEnumDescription(Enum enumObj)
    {
        FieldInfo fieldInfo = enumObj.GetType().GetField(enumObj.ToString());

        object[] attribArray = fieldInfo.GetCustomAttributes(false);

        if (attribArray.Length == 0)
        {
            return enumObj.ToString();
        }
        else
        {
            DescriptionAttribute attrib = attribArray[0] as DescriptionAttribute;
            return attrib.Description;
        }
    }

    object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        Enum myEnum = (Enum)value;
        string description = GetEnumDescription(myEnum);
        return description;
    }

    object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return string.Empty;
    }
}

GetEnumDescription 方法可能应该去别的地方,但你明白了:)

The GetEnumDescription method should probably go somewhere else but you get the idea :)

检查GetEnumDescription 作为扩展方法.

这篇关于WPF 将 ListBox 绑定到枚举,显示描述属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆