MVVM中将枚举数据绑定到ComboBox

MVVM中将枚举数据绑定到ComboBox

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

问题描述

我在这里阅读了,这是非常有帮助的,因为在答案中的链接。我现在只是有一个问题现在进行额外的步骤,并使它所有的工作与MVVM模式。

I've read this very related question here on SO, and it was extremely helpful because of the link in the answer. I'm just having a problem now going the extra step and making it all work with the MVVM pattern.

让我们说我有我的ViewModel,它(甚至模型)可以具有定义的枚举:

Let's say I have my ViewModel, and it (or even the Model) could have an enum defined:

public enum MyTypes { Type1, Type2, Type3 };

我想将这个数据绑定到我的GUI中的ComboBox。根据文章,我将使用ObjectDataProvider来调用MyTypes上的Enum.GetValues()方法。所以我必须传递MyTypes作为MethodParameter。但你怎么传递类型?我尝试了各种方法,例如在XAML中添加对命名空间的引用:

I want to databind this to a ComboBox in my GUI. According to the article, I would use an ObjectDataProvider to invoke the Enum.GetValues() method on MyTypes. So I have to pass MyTypes as a MethodParameter. But how do you pass the type? I've tried various methods, like adding the reference to the namespace in XAML:

    <Window.Resources>
        <ObjectDataProvider MethodName="GetValues" ObjectType="{x:Type sys:Enum}" x:Key="TipHandlingValues">
            <ObjectDataProvider.MethodParameters>
                <!-- what goes here?  it's totally wrong. -->
                <my:MyTypes />
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
    </Window.Resources>

几乎没有什么我放在那里甚至会编译。

Pretty much nothing I put there will even compile. Does anyone know how to get past this little hurdle?

推荐答案

请参阅我的回答这个SO post:

See my answer on this SO post: How to declare combobox itemTemplate that has Itemsource as Enum Values in WPF?

简而言之,在ObjectDataProvider.MethodParameters中应该引用您的Enum的类型名称作为命名空间引用,即

In short, in the ObjectDataProvider.MethodParameters should refer to your Enum's type name as referenced in a namespace, i.e.,

<ObjectDataProvider.MethodParameters>
  <x:Type TypeName="my:MyTypes"/>
</ObjectDataProvider.MethodParameters>

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

08-15 09:00