18
votes

I have two properties, one which is a list of string and the other just a string.

private List<String> _property;
public List<String> Property
get
{
return new List<string>(){"string1", "string2"};
}
set{_property = value
}

public String SimpleStringProperty{get;set;}

I also have a Combobox defined in XAML as such

<Combobox ItemsSource="{Binding Property , Mode="TwoWay"}" Text="Select Option" />    

Now the combobox correctly displays two options :"string1" and "string2"

When the user selects one or the other, I want to set SimpleStringProperty with that value. However, the 'value' im getting back from the combobox through the two way binding is not the selectedItem, but the List<String>. How can I do this right? I'm fairly new to wpf, so please excuse the amateurism.

3

3 Answers

26
votes
<Combobox ItemsSource="{Binding Property}" SelectedItem="{Binding SimpleStringProperty, Mode=TwoWay}" Text="Select Option" />

That's untested, but it should at least be pretty close to what you need.

3
votes

You need to bind to the String property using the SelectedItem property of the combobox.

<Combobox ItemsSource="{Binding Property}" 
          SelectedItem="{Binding SimpleStringProperty}" 
          IsSynchronizedWithCurrentItem="True" 
          Text="Select Option" />
2
votes

What helped me:

  1. Using SelectedItem
  2. Adding UpdateSourceTrigger=PropertyChanged
  3. IsSynchronizedWithCurrentItem="True" to be sure Selected item always synchronized with actual value
  4. Mode=TwoWay if you need to update as from source as from GUI

So at the end best way, if source is

List<string>

Example:

 <ComboBox 
    IsSynchronizedWithCurrentItem="True"
    ItemsSource="{Binding SomeBindingPropertyList}"
    SelectedItem="{Binding SomeBindingPropertySelectedCurrently, 
                    Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />

Additional Info