1

I am trying to bind values of an enum to a combo box but the combo box remain empty with no options to choose.

This is the combo box xaml defintion:

<ComboBox Grid.Row="2" Grid.Column="1" ItemsSource="{Binding Path=SkillItemSource}" SelectedItem="{Binding Path=neededSkill, Mode=TwoWay}" SelectedIndex="0" Margin="5" MinWidth="100"></ComboBox>

And this is the items source and selected item which are defined in the window's cs:

public Skill neededSkill = Skill.FirstSkill;

public string[] SkillItemSource
    {
        get
        {
            return Enum.GetNames(typeof(Skill));
        }
    }

What is missing for the values to appear in the combobox?

CodeMonkey
  • 11,196
  • 30
  • 112
  • 203
  • [This](https://stackoverflow.com/questions/6145888/how-to-bind-an-enum-to-a-combobox-control-in-wpf) might be what you're looking for. – dotNET May 22 '19 at 12:53
  • You cannot set SelectedItem to type Skill while the ItemsSource of Combobox is type string[]. – Mathivanan KP May 22 '19 at 12:55

1 Answers1

1

What is missing for the values to appear in the combobox?

You need to set the DataContext of the ComboBox, or a parent element, to an instance of the class where the SkillItemSource property is defined. If the property is defined in the code-behind, you could just set the DataContext to the view itself: this.DataContext = this;

Also, you can't mix types. If the ItemsSource is bound to an IEnumerable<string>, the SelectedItem property should be bound to a string property.

Also note that neededSkill must be defined as a public property for you to be able to bind to it.

Try this:

public Skill neededSkill { get; set; } = Skill.FirstSkill;

public IEnumerable<Skill> SkillItemSource { get; } = Enum.GetValues(typeof(Skill)).Cast<Skill>();
CodeMonkey
  • 11,196
  • 30
  • 112
  • 203
mm8
  • 163,881
  • 10
  • 57
  • 88
  • Do I need to set the DataContext even if it's defined in the xaml.cs of that same window? – CodeMonkey May 22 '19 at 13:16
  • 1
    Yes. If the property is defined in the code-behind, you could just set the DataContext to the view itself: `this.DataContext = this;` – mm8 May 22 '19 at 13:17