WPF:如何在Xaml中使用枚举填充组合框 [英] WPF: How to populate combobox with enum in Xaml
问题描述
cmb.ItemsSource = Enum.GetValues(typeof (MyTypes));
我想知道是否可以在Xaml中生成等价物。我以为我们可以使用转换器归档这个。我们可以将类型转换为数组,然后将数组绑定到组合框'ItemsSource。但是,我一直坚持如何将转换器的枚举指定给我。这是我的代码:
我的枚举:
public enum MyTypes {Type1,Type2,Type3};
这是我的转换器:
public class EnumToArrayConverter:IValueConverter
{
public object Convert(object value,Type targetType,object parameter,System.Globalization.CultureInfo culture)
{
返回Enum.GetValues(value.GetType());
}
public object ConvertBack(object value,Type targetType,object parameter,System.Globalization.CultureInfo culture)
{
return null; //我不在乎这个
}
}
我的Xaml资源:
< lib:EnumToArrayConverter x:Key =E2A/>
以下是如何使用它:
< ComboBox SelectedItem ={Binding MyType}ItemsSource ={Binding MyTypes,Converter = {StaticResource E2A}}/>
所以,我的问题是如何将我的枚举MyTypes指定给转换器。我也试图预先命名空间,但这并没有帮助。
http:// html = .wordpress.com / 2008/07/08 / enum-getvalues-markup-extension /rel =noreferrer>这个。
I know there are several ways to do it, but I would like to make it even easier if possible because I have a lot of comboboxes to bind in this way. There is a suggestion using ObjectDataProvider here. The problem is that I have to create a resource entry for each enum and that's a lot. So far, I have been using the code-behind way because it's much shorter:
cmb.ItemsSource = Enum.GetValues(typeof(MyTypes));
I'm wondering if an equivalent can be produced in Xaml. I thought we could archive this by using a converter. We could convert the type to an array and then bind the array to combobox' ItemsSource. But I got stuck on how to specify my enum to the converter. Here is my code:
My enum:
public enum MyTypes { Type1, Type2, Type3 };
This is my converter:
public class EnumToArrayConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return Enum.GetValues(value.GetType());
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return null; // I don't care about this
}
}
My Xaml Resource:
<lib:EnumToArrayConverter x:Key="E2A"/>
Here is how to use it:
<ComboBox SelectedItem="{Binding MyType}" ItemsSource="{Binding MyTypes, Converter={StaticResource E2A}}"/>
So, my question is how to specify my enum "MyTypes" to the converter. I also tried to prepend namespace, but it doesn't help.
You would be better off with a MarkupExtension, like this one.
这篇关于WPF:如何在Xaml中使用枚举填充组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!