Databinding ComboBox in Silverlight DataForms
Read the article below if you wish to bind text to a static list on comboboxes.
Read this article if you wish to fill the ComboBox with a list fetched from a database
Say we have a text field for “Gender”, which we want to set to either “Male” or “Female”, the basics of setting up the combobox are as follows:
<ComboBox> <ComboBoxItem Content="Male"></ComboBoxItem> <ComboBoxItem Content="Female"></ComboBoxItem> </ComboBox>
Databinding always catches me out though, there are several fields useful for databinding.
- DisplayMemberPath
- SelectedValuePath
- SelectedValue
The DisplayMemberPath is by default the ToString() function on the ComboBoxItem. We can explicitly set it to Content. This step is optional
<ComboBox
DisplayMemberPath="Content"
>
<ComboBoxItem Content="Male"></ComboBoxItem>
<ComboBoxItem Content="Female"></ComboBoxItem>
</ComboBox>
We can perform a Two-Way binding from a ComboBox’s SelectedValue to a Property on a Model. e.g. Person.Gender.
Since valid values of Person.Gender (“Male” and “Female”) correspond to the ComboBoxItem.Content property, we set the SelectedValuePath to “Content” as well.
<ComboBox
SelectedValuePath="Content"
DisplayMemberPath="Content"
>
<ComboBoxItem Content="Male"></ComboBoxItem>
<ComboBoxItem Content="Female"></ComboBoxItem>
</ComboBox>
The last step is to databind the Gender to the SelectedValue (sssuming the DataContext is a Person)
<ComboBox
SelectedValue="{Binding Path=Gender, Mode=TwoWay}"
SelectedValuePath="Content"
DisplayMemberPath="Content"
>
<ComboBoxItem Content="Male"></ComboBoxItem>
<ComboBoxItem Content="Female"></ComboBoxItem>
</ComboBox>
About this entry
You’re currently reading “ Databinding ComboBox in Silverlight DataForms ,” an entry on Chui's Counterpoint
- Published:
- 7.5.10 / 9pm
- Category:
- .Net, Silverlight
8 Comments
Jump to comment form | comments rss [?]