Associate WPF Combobox with a <string> List

I have two properties, one of which is a list of strings, and the other is 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 Combobox defined in XAML as such

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

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

When the user selects one or the other, I want to set SimpleStringProperty with this value. However, the "value" im returning from combobox via a two-way binding is not a select, but a List<String> . How can I do it right? I am new to wpf, so please excuse my amateurism.

+12
c # wpf
source share
3 answers
 <Combobox ItemsSource="{Binding Property}" SelectedItem="{Binding SimpleStringProperty, Mode=TwoWay}" Text="Select Option" /> 

This is untested, but it should be at least close to what you need.

+20
source share

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

 <Combobox ItemsSource="{Binding Property}" SelectedItem="{Binding SimpleStringProperty}" IsSynchronizedWithCurrentItem="True" Text="Select Option" /> 
+3
source share

What helped me:

  1. Using SelectedItem
  2. Adding UpdateSourceTrigger = PropertyChanged
  3. IsSynchronizedWithCurrentItem = "True" to ensure that the selected item is always in sync with the actual value
  4. Mode = TwoWay, if you need to update both from the source and from the GUI

So in the end the best way is if the source

 List<string> 

Example:

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

Additional Information

+1
source share

All Articles