Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind UWP ComboBox ItemsSource to Enum

It's possible to use the ObjectDataProvider in a WPF application to bind an enum's string values to a ComboBox's ItemsSource, as evidenced in this question.

However, when using a similar snippet in a UWP application, the ff. error message is displayed:

"ObjectDataProvider is not supported in a Windows Universal project."

Is there a simple alternative to do this in UWP?

like image 462
miguelarcilla Avatar asked Aug 29 '16 15:08

miguelarcilla


1 Answers

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" />
like image 85
Lance Avatar answered Sep 19 '22 12:09

Lance