WPF:如何在 Xaml 中使用枚举填充组合框
我知道有多种方法可以做到这一点,但如果可能的话,我想让它变得更容易,因为我有很多组合框可以通过这种方式绑定。 此处建议使用 ObjectDataProvider。问题是我必须为每个枚举创建一个资源条目,而且数量很多。到目前为止,我一直在使用代码隐藏方式,因为它要短得多:
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)
{
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
}
}
我的 Xaml 资源:
<lib:EnumToArrayConverter x:Key="E2A"/>
以下是如何使用它:
<ComboBox SelectedItem="{Binding MyType}" ItemsSource="{Binding MyTypes, Converter={StaticResource E2A}}"/>
所以,我的问题是如何向转换器指定我的枚举“MyTypes”。我也尝试在前面添加名称空间,但这没有帮助。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您最好使用 MarkupExtension,就像这个。
You would be better off with a MarkupExtension, like this one.
CodeNaked 发布了一个很好的方法,
对于您的工作方法,您可以将转换器更改为
Enum.GetValues(value as Type)
并使用x:Type
语法作为源用于绑定EnumToArrayConverter
CodeNaked posts a great way of doing this
For your approach to work you can change the converter to
Enum.GetValues(value as Type)
and use thex:Type
syntax as Source for the BindingEnumToArrayConverter