指定组合框的转换器

本文关键字:转换器 组合 | 更新日期: 2024-10-21 15:45:50

我有以下用于组合框的(工作)XAML:

<ComboBox SelectedValue="{Binding SelectedItem}" ItemsSource="{Binding Items}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Converter={StaticResource MyEnumToStringConverter}}"/>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

我不喜欢这段代码:为了改变枚举作为字符串的表示方式,我还必须指定ComboBoxItemTemplate的外观。如果我想全局更改所有组合框的外观,该怎么办?

另一个解决方案是在ItemSource绑定上指定转换器:

<ComboBox
    SelectedValue="{Binding SelectedItem}"
    ItemsSource="{Binding Items, Converter={StaticResource MyEnumToStringConverter}}" />

我也不喜欢这样,因为我希望ComboBox存储我的真实类型,而不是它的字符串表示

我还有什么其他选择?

指定组合框的转换器

不需要设置每个组合框的ItemTemplate,无论是否为Style。

相反,您可以简单地通过设置枚举类型的DataType属性为其创建一个默认的DataTemplate

<Window.Resources>
    <local:MyEnumStringConverter x:Key="MyEnumStringConverter"/>
    <DataTemplate DataType="{x:Type local:MyEnum}">
        <TextBlock Text="{Binding Converter={StaticResource MyEnumStringConverter}}"/>
    </DataTemplate>
    ...
</Window.Resources>

您可以创建一个新的基于MyEnumText字符串的属性,该属性返回枚举值的Description属性值,并将您的TextBlock.Text属性绑定到它,如下所示:

<ComboBox SelectedValue="{Binding SelectedItem}" ItemsSource="{Binding Items}">
<ComboBox.ItemTemplate>
    <DataTemplate>
        <TextBlock Text="{Binding MyEnumText}"/> <!--Bound to new Text property-->
    </DataTemplate>
</ComboBox.ItemTemplate>

DescriptionAtrribute属性添加到您的枚举值:

public enum MyEnum
{
    [System.ComponentModel.Description("Value One")]
    MyValue1 = 1,
    [System.ComponentModel.Description("Value Two")]
    MyValue2 = 2,
    [System.ComponentModel.Description("Value Three")]
    MyValue3 = 3
}

Enum类创建一个扩展方法

public static class EnumHelper
{
    public static string GetDescription(this Enum value)
    {
        Type type = value.GetType();
        string name = Enum.GetName(type, value);
        if (name != null)
        {
            System.Reflection.FieldInfo field = type.GetField(name);
            if (field != null)
            {
                System.ComponentModel.DescriptionAttribute attr =
                       Attribute.GetCustomAttribute(field,
                         typeof(System.ComponentModel.DescriptionAttribute)) as System.ComponentModel.DescriptionAttribute;
                if (attr != null)
                {
                    return attr.Description;
                }
            }
        }
        return null;
    }
}

将返回字符串的新属性MyEnumText添加到ViewModel:

public MyEnum MyEnumProperty { get; set; }
public string MyEnumText    //New Property
{
    get
    {
        return MyEnumProperty.GetDescription();
    }
}

OP此处。我在这里重新表述了这个问题,得到了同样适用于这个问题的答案。