将枚举数据绑定到WPF + MVVM中的ComboBox [英] Databinding an enum to a ComboBox in WPF + MVVM
问题描述
我在这里阅读了这个非常相关的问题,这是非常有帮助的,因为答案中的链接。我现在只是遇到了一个问题,现在要进行额外的步骤,并使其全部适用于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中的组合框。根据文章,我将使用一个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帖子的答案:如何声明具有Itemsource作为枚举值的组合框项目模板WPF?
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!