[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
是为之记。
Alva Chien