WPF / XAML: Binding ComboBox directly to enum values

This is a note to remind me how to bind a xaml combo box directly to an enum property defined in the ViewModel. This is handy if the ComboBox values for display match exactly those defined in the backing enum.

So imaging that we have an enum defined as follows:

public enum UserType
{
    Tester,
    Engineer
}

Now imagine that we want to include a ComboBox in our view that allows the selection of these enum values and whose SelectedValue property binds with a property of our view model, in xaml terms:


So we need to add a property to our ViewModel called UserTypes that will enumerate our enum’s values so that they can be displayed in the combo box. We also need a property called UserType that will bind to the ComboBox’s selected value like this:

//
public IList UserTypes
{
    get
    {
        // Will result in a list like {"Tester", "Engineer"}
        return Enum.GetValues(typeof(UserType)).Cast().ToList();
    }
}
public UserType UserType
{
	get;
	set;
}
//

And that should do it…. But knowing WPF and XAML you will probably end up fighting with it for a good few hours! ;-)

2 replies
  1. Abdelwaheb
    Abdelwaheb says:

    i want to ask the author of this code what can do this instruction:
    return Enum.GetValues(typeof(UserType)).Cast().ToList();

    ?

Comments are closed.