Bind UWP ComboBox ItemsSource to Enum

Below is a working example from one of my prototypes.

ENUM

public enum GetDetails
{
    test1,
    test2,
    test3,
    test4,
    test5
}

ItemsSource

var _enumval = Enum.GetValues(typeof(GetDetails)).Cast<GetDetails>();
cmbData.ItemsSource = _enumval.ToList();

This will bind combobox to Enum Values.


If you try to set your SelectedItem via xaml and Bindings, make sure that you set the ItemsSource first!

Example:

<ComboBox ItemsSource="{Binding ...}" SelectedItem="{Binding ...}"/>

Trust me, ComboBox and enum in UWP is a bad idea. Save yourself some time, don't use enum on a combobox in UWP. Spent hours trying to make it work. You can try the solutions mentioned in other answers but the problem you're going to get is that the propertychange won't fire when SelectedValue is bound to an enum. So I just convert it to int.

You can create a property in the VM and cast the enum GetDetails to int.

public int Details
{
  get { return (int)Model.Details; }
  set { Model.Details = (GetDetails)value; OnPropertyChanged();}
}

Then you can just work on a list of a class with int and string, not sure if you can use a KeyValuePair

public class DetailItem
{
  public int Value {get;set;}
  public string Text {get;set;}
}

public IEnumerable<DetailItem> Items
{
  get { return GetItems(); }
}

public IEnumerable<DetailItem> GetItems()
{
   yield return new DetailItem() { Text = "Test #1", Value = (int)GetDetails.test1 }; 
   yield return new DetailItem() { Text = "Test #2", Value = (int)GetDetails.test2 }; 
   yield return new DetailItem() { Text = "Test #3", Value = (int)GetDetails.test3 }; 
   // ..something like that
}

Then on the Xaml

<Combobox ItemsSource="{Binding Items, UpdateSourceTrigger=PropertyChanged}"
 SelectedValue="{Binding Details, UpdateSourceTriggerPropertyChanged, Mode=TwoWay}"
 SelectedValuePath="Value" 
 DisplayMemberPath="Text" />