将 ComboBox 绑定到嵌套在类中的枚举 [英] Binding a ComboBox to an enum nested in a class

查看:29
本文介绍了将 ComboBox 绑定到嵌套在类中的枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经疯狂地将组合框绑定到类的枚举类型属性,其中枚举本身在同一个类中声明.

I have been going crazy with binding a combobox to an enum typed property of a class, where the enum itself is declared in that same class.

我正在尝试按照此处提供的答案(wpf组合框绑定到枚举我做错了什么?) 具体来说,我正在使用建议的 MarkupExtension 代码和匹配的 xaml 代码.

I am trying to follow the answer provided here (wpf combobox binding to enum what i did wrong?) Specifically I am using the suggested MarkupExtension code and the matching xaml code.

我的工作代码是:

在单独的文件中定义枚举.

Defining the Enum in a separate file.

namespace EnumTest
{
    public enum TestEnum {one, two, three, four };
}

使用 Enum 的类(注意,为了简化事情,propertyChanged 代码已被删除):

Class that uses the Enum (Note that the propertyChanged code has been removed to simplify things):

namespace EnumTest
{
    public class Test : INotifyPropertyChanged
    {
        private TestEnum _MyVar;
        public TestEnum MyVar { 
            get { return _MyVar; } 
            set 
            { 
                _MyVar = value;
                OnPropertyChanged("MyVar");
            } 
        }

        public Test()
        {
            _MyVar = TestEnum.three;
        }
    }
}

使用该类的程序文件:

namespace EnumTest
{
    public partial class Window1 : Window
    {
        Test _oTest = new Test();

        public Window1()
        {
            InitializeComponent();
            cmbBox.DataContext = _oTest;
        }
    }
 }

用于显示 Enum 的扩展方法

Extension method for displaying the Enum

namespace EnumTest
{
    [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);
        }
    }
}

以及用于显示数据的xaml代码:

And the xaml code that is used to display the data:

<Window x:Class="EnumTest.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:w="clr-namespace:EnumTest"
    Title="Window1" Height="300" Width="300">
    <Grid>
        <ComboBox Name="cmbBox" 
                  Height="20" 
                  Width="80" 
                  ItemsSource="{Binding Source={w:EnumValues EnumType=w:TestEnum}}" 
                  SelectedItem="{Binding Path=MyVar}"
                  />
    </Grid>
</Window>

以上都是好的和花哨的,但我想在 Test 类中定义 Enum ,并在全局范围内定义 Enum.像这样:

The above is all good and dandy, but I want to define the Enum within the Test class and ditch the Enum from being defined at the global scope. Like so:

namespace EnumTest
{
    public class Test : INotifyPropertyChanged
    {
        // Declare Enum **INSIDE** the class
        public enum TestEnum {one, two, three, four };
        private TestEnum _MyVar;
        public TestEnum MyVar { 
            get { return _MyVar; } 
            set 
            { 
                _MyVar = value;
                OnPropertyChanged("MyVar");
            } 
        }

        public Test()
        {
            _MyVar = TestEnum.three;
        }
    }
}

我提到的 SO 问题暗指匹配的 xaml 语法是:

The SO question I referred to alludes to the matching xaml syntax as being:

        <ComboBox Name="cmbBox" 
                  ...
                  ItemsSource="{Binding Source={w:EnumValues EnumType=w:Test+TestEnum}}" 
                  ...
                  />

但这(有点)对我不起作用.当我进行干净构建时,我在 VS 2008 状态栏上收到构建成功"消息,但我也在 xaml 中报告了一个错误

But this (sort of) does not work for me. When I do a clean build I get a "Build succeeded" message on the VS 2008 status bar, but I also get an error being reported in the xaml

Type 'Test+TestEnum' was not found.  

但代码按预期运行!

然而,这意味着 xaml 设计器不会加载.所以在清除 xaml 错误之前,我有点忙于做更多的 wpf 工作.

However this means that the xaml designer will not load. So I am sort of screwed in doing any more wpf work until I can clear the xaml error.

我现在想知道这是否是 VS 2008 SP1 的问题,而不是我的问题.

I am now wondering if this is a VS 2008 SP1 issue, and not a problem on my part.

编辑

  1. 使我的问题陈述更加明确.
  2. 尝试了 Joel 的第一个解决方案,但我最终得到了运行 2 个 xaml 错误的代码
  3. 尝试了 Joel 的第二个解决方案,而且开箱即用 - 所以我选择了那个!
  1. Made my problem statement more explicit.
  2. Tried Joel's 1st solution, but I ended up with the code running and 2 xaml errors
  3. Tried Joel's 2nd solution and that worked straight out of the box - so I am going with that one!

<小时>

注意事项我从中获得 MarkupExtension 代码的 SO 问题对 xaml 使用了这种语法风格:


Notes The SO question that I got the MarkupExtension code from uses this style of syntax for the xaml:

<ComboBox ItemsSource="{w:EnumValues w:TestEnum}"/>

当我使用它时,我收到一个编译错误,说没有 EnumValues 构造函数需要 1 个参数.我做了一些谷歌搜索,这似乎是 VS 中的一个错误.我正在使用 VS 2008 SP1.我确实看到一些评论暗示它在 VS 2010 测试版中.无论如何,这就是我使用

When I use that I get a compilation error saying that no EnumValues constructor takes 1 parameter. I did some googling and this seems to be an error in VS. I Am using VS 2008 SP1. I did see some comments that alluded to it being in the VS 2010 beta. Anyway, that is why I use the xaml syntax of

<ComboBox ItemsSource="{w:EnumValues EnumType=w:TestEnum}"/>

因为这个语法有效!

推荐答案

另一种获取枚举值以用作数据源的方法:

Another way of getting the enum values for use as a data source:

<Window.Resources>
    <ObjectDataProvider
        MethodName="GetValues"
        ObjectType="{x:Type sys:Enum}"
        x:Key="TestValues">
        <ObjectDataProvider.MethodParameters>
            <w:Type2
                TypeName="w:Test+TestEnum" />
        </ObjectDataProvider.MethodParameters>
    </ObjectDataProvider>
</Window.Resources>

...

ItemsSource="{Binding Source={StaticResource TestValues}}"

请注意,由于 TypeExtension 和嵌套类型的奇怪之处,您仍然需要 Type2Extension.但是您不需要额外的自定义标记扩展.如果您要在多个地方使用该列表,这种方式会更好,因为您可以在 App.xaml 资源中声明它.

Note that you still need the Type2Extension because of weirdness with TypeExtension and nested types. But you wouldn't need the extra custom markup extension. This way is better if you'll be using the list in multiple places, as you can declare it in your App.xaml resources.

这篇关于将 ComboBox 绑定到嵌套在类中的枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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