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

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

问题描述

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

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));

我想知道是否可以在 Xaml 中生成等效项.我想我们可以通过使用转换器来存档.我们可以将类型转换为数组,然后将数组绑定到组合框的 ItemsSource.但是我被困在如何将我的枚举指定给转换器的问题上.这是我的代码:

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:

我的枚举:

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 资源:

My Xaml Resource:

<lib:EnumToArrayConverter x:Key="E2A"/>

使用方法如下:

<ComboBox SelectedItem="{Binding MyType}" ItemsSource="{Binding MyTypes, Converter={StaticResource E2A}}"/>

所以,我的问题是如何为转换器指定我的枚举MyTypes".我也尝试添加命名空间,但没有帮助.

So, my question is how to specify my enum "MyTypes" to the converter. I also tried to prepend namespace, but it doesn't help.

推荐答案

最好使用 MarkupExtension,例如 这个.

这篇关于WPF:如何在 Xaml 中使用枚举填充组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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