Databinding an enum to a ComboBox in WPF + MVVM

非 Y 不嫁゛ 提交于 2019-12-21 12:54:13

问题


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.

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

public enum MyTypes { Type1, Type2, Type3 };

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?


回答1:


Simplest way is to add this line in code:

DataContext = Enum.GetValues(typeof(MyTypes));

Other options is to add markup extension that produce list of values out of enum.




回答2:


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

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>


来源:https://stackoverflow.com/questions/2608300/databinding-an-enum-to-a-combobox-in-wpf-mvvm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!