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.

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
Maciek
  • 19,435
  • 18
  • 63
  • 87
  • 1
    see the accepted answer here: http://stackoverflow.com/questions/1220196/wpf-binding-a-combobox-to-an-enum-nested-in-a-class – Alastair Pitts Dec 16 '09 at 12:41

1 Answers1

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)

Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
  • 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? – newman Mar 04 '14 at 03:57
  • @miliu, you probably have another `IServiceProvider` type in scope; try to specify the full name: `System.IServiceProvider` – Thomas Levesque Mar 04 '14 at 08:33