WPF:如何在Xaml中使用枚举填充组合框 [英] WPF: How to populate combobox with enum in Xaml

查看:150
本文介绍了WPF:如何在Xaml中使用枚举填充组合框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有几种方法可以做到这一点,但是如果可能的话我想让它更容易,因为我有很多组合框以这种方式绑定。有一个使用ObjectDataProvider here 的建议。问题是我必须为每个枚举创建一个资源条目,这很多。到目前为止,我一直在使用代码隐藏方式,因为它更短:

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆