21

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 Answers 3

29
<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.

Sign up to request clarification or add additional context in comments.

Comments

4

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" />

Comments

3

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

3 Comments

I recommend reading the documentation on ComboBox.SelectedValue instead of just guessing about it.
This worked for me, i was missing: UpdateSourceTrigger=PropertyChanged

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.