[WPF] Binding Enum to ComboBox

 

方法一:在Resources中定义ObjectDataProvider ,如:

<ObjectDataProvider MethodName="GetValues" ObjectType="{x:Type sys:Enum}" x:Key="localEnumTypes">
    <ObjectDataProvider.MethodParameters>
        <x:Type TypeName="local:MyEnumType" />
    </ObjectDataProvider.MethodParameters>
</ObjectDataProvider>

对Combo设定:

<ComboBox ItemsSource="{Binding {StaticResource localEnumTypes}}" />

 

 

方法二:定义一个MarkupExtension

 

[MarkupExtensionReturnType(typeof(object[]))]
public class EnumValuesExtension : MarkupExtension
{
    public EnumValuesExtension() { }
  
    public EnumValuesExtension(Type enumType)  
    {
        this.EnumType = enumType;
     }

    [ConstructorArgument("enumType")]
    public Type EnumType { get; set;}

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        if(this.EnumType == null)
            throw new ArgumentException("The enum type is not set");


        return Enum.GetValues(this.EnumType);
     }
}

对Combo进行Binding:

<ComboBox ItemsSource="{local:EnumValues local:MyEnumType}" />

 

 

方法三。用一个辅助的Class

public enum MyEnumType

{

    One,

    Two,

    Three

}

public class EnumClass :
{
    
static EnumClass()     {

    StringDict = new Dictionary<MyEnumType, String>() {

       {MyEnumType.One, "Pinyin: Yi"},

       {MyEnumType.Two, "Pinyin: Er"},

       {MyEnumType.Three, "Pinyin: San"},

    } ;    

    }

 

     public static Dictionary<MyEnumType, String> StringDict { get; private set; }

}

在Resources中加入:

<ObjectDataProvider ObjectType="{x:Type local:EnumClass}" x:Key="localEnumTypes">
</ObjectDataProvider>

对Combo进行Binding:

  < ComboBox   ItemsSource ="{ Binding   Source ={ StaticResource   localEnumTypes },   Path =StringDict}" SelectedIndex ="0"   DisplayMemberPath ="Value"   SelectedValuePath ="Key"   />

小心的是,这里不能再使用SelectedItem,而是必须使用SelectedValue。如:


三种方法点评:

第一种方法最简单。但其直接显示了Enum中定义的字符串;

第二种方法增加了一点复杂度,但其依旧直接显示字符串,只是在XAML中Binding语法进行了优化。

第三种方法最复杂,但是可以用其自定义显示字符串!这在多语言程序中是必须的。

 

switch (((KeyValuePair <MyEnumType ,  string >)cmbBox.SelectedValue).Key)

            {

                 //your case statements here

                 default :

                     //custom logic

                 break ;

            }

 

By Alva Chien,

2010.04.29

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值