Bind text to selected item in combobox

c#, combobox, data-binding, wpf, xaml

Solution

The Wpf `ComboBox` has three selection properties and one display property:

- `SelectedItem`

- `SelectedValue`

- `SelectedValuePath`

- `DisplayMemberPath`

When using `SelectedValue` you should also set the `SelectedValuePath` (almost always). Understand that the `Items` in your case contains a sequence (`ItemCollection`) of `ComboBoxItem` objects, and just like any other object you must specify the `SelectedValuePath` (read property) that you want to bind to; In this case, you want to access the `ComboBoxItem.Content` property (http://msdn.microsoft.com/en-us/library/system.windows.controls.contentcontrol.content(v=vs.110).aspx).

<ComboBox SelectedValue="{Binding Path=MyProperty}" SelectedValuePath="Content">
  <ComboBoxItem>A</ComboBoxItem>
  <ComboBoxItem>B</ComboBoxItem>
  <ComboBoxItem>C</ComboBoxItem>
</ComboBox>

Now you are binding the `SelctedValue` to the `MyProperty` property using the selected item's `Content` property, which happens to be the strings you are looking for.

Problem

I have a text field on the database, but now I don't want it to be a free open field, I want to restrict it to: let's say A, B and C. For this I want to use a Combobox. Question: How do I bind the selected item to the string property, given that the Items of the combobox are defined in XAML? XAML: ``` <ComboBox SelectedValue="{Binding Path=MyProperty}"> <!-- Not working--> <ComboBoxItem>A</ComboBoxItem> <ComboBoxItem>B</ComboBoxItem> <ComboBoxItem>C</ComboBoxItem> </ComboBox> ``` Class: ``` public Class MyClass:INotifyPropertyChanged { private string myProperty; public string MyProperty { get{return myProperty;} set{ myProperty=value; OnPropertyChanged("MyProperty"); } } } ``` So, the user will change the selected item, and the new value will be updated on the databound object. EDIT: Thanks to the comments and answers I partially solved the problem, the only issue was that the combobox selection was empty when the program started. I solved it like this: ``` <ComboBox SelectedValuePath="Content"> <ComboBoxItem>A</ComboBoxItem> <ComboBoxItem>B</ComboBoxItem> <ComboBoxItem>C</ComboBoxItem> <ComboBox.SelectedValue> <Binding Path="MyProperty" Mode="TwoWay"/> </ComboBox.SelectedValue> </ComboBox> ``` I moved the selected value part out of the attributes of the Combobox, and used property element sintax, this ensures that the collection is defined before it is used.

Original source