Gerald Gonzales
Gerald Gonzales

Reputation: 533

Silverlight combobox selectedvalue string property binding

I have a combobox with items like below:

{[1, US]}
{[2, UK]}

My combobox will display it with the Value. My problem is I can't set the SelectedValue property of my combobox.

<ComboBox Name="cbSource" Grid.Row="1" Grid.Column="3"
ItemsSource="{Binding Datas.Countries, Mode=OneWay}" 
SelectedValue="{Binding CurrentObject.Country, Mode=TwoWay}"     
DisplayMemberPath="Value" SelectedValuePath="Key"></ComboBox>

Now my CurrentObject.Country is a string property with a value of UK. I also tried this one below but no luck.

DisplayMemberPath="Value" SelectedValuePath="Value"

What can I do here?

Upvotes: 0

Views: 513

Answers (1)

ViVi
ViVi

Reputation: 4464

It is not possible to achieve your behavior using a key value pair. See the example below. Just create a class having 2 properties one for key and one for value. Then bind a collection of this class as the itemssource and bind the selectedvalue to a string property. Ie Datas.Countries is the collection of the class.

<ComboBox Name="cbSource" Grid.Row="1" Grid.Column="3"
ItemsSource="{Binding Datas.Countries, Mode=OneWay}" 
SelectedValue="{Binding SomePropertyToHoldKeyValue, Mode=TwoWay}"     
DisplayMemberPath="Value" SelectedValuePath="Key"></ComboBox>

I think we can understand the difference between SelectedItem, SelectedValue, DisplayMemberPath and SelectedValuePath better with an example. See this class:

public class Employee
{
   public int Id;
   public string Name;
}

and the following xaml:

<ComboBox ItemsSource="{Binding Source={StaticResource Employees}}"
          DisplayMemberPath="Name"
          SelectedValuePath="Id"/>

DisplayMemberPath points to the Name property, so the value displayed in the ComboBox and the Employee entries contained in the drop down list, will be the Name property of the Employee object.

To understand the other two, you should first understand SelectedItem. SelectedItem will return the currently selected Employee object from the ComboBox. You can also assign SelectedItem with an Employee object to set the current selection in the ComboBox.

SelectedValuePath points to Id, which means you can get the Id of currently selected Employee by using SelectedValue. You can also set the currently selected Employee in the ComboBox by setting the SelectedValue to an Id (which we assume will be present in the Employees list).

Upvotes: 1

Related Questions