3

In the namespace X, I've got a public enum definition :

namespace X { public enum MyEnum { val0=0, val1, val2, val3, val4 } } 

In the namespace Y I've got a class which has a property of the X.MyEnum type

using namespace X; namespace Y { class Container { public MyEnum MYEnum { get { return m_myenum; } set { m_myenum = value; } } private MyEnum m_myenum; } } 

I've created an user control which contains a ComboBox. I'd very much like to databind it (TwoWay) to the MYEnum field of the "Container". The usercontrol resides in the window.

How do I achieve that? I've seen some examples with ObjectDataProvider, however I'm lost.

1

1 Answer 1

6

You can define the ItemsSource of the ComboBox by using a custom markup extension that returns all values of the enum (this achieves the same result as using an ObjectDataProvider, but it is simpler to use) :

[MarkupExtensionReturnType(typeof(Array))] 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) { return Enum.GetValues(EnumType); } } 

And bind the SelectedItem to your MYEnum property :

<ComboBox ItemsSource="{local:EnumValues local:MyEnum}" SelectedItem="{Binding MYEnum, Mode=TwoWay}" /> 

(the local XML namespace must be mapped to your C# namespace)

Sign up to request clarification or add additional context in comments.

2 Comments

I like this idea very much, but for some reasons I get a compiler error "Inconsistent accessibility: parameter type 'IServiceProvider' is less accessible than method 'UtilityLib.EnumValuesExtension.ProvideValue(IServiceProvider)'". You copied your code exactly as it is. Any idea?
@miliu, you probably have another IServiceProvider type in scope; try to specify the full name: System.IServiceProvider

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.