Binding to Silverlight ComboBox and Using SelectedValue, SelectedValuePath and DisplayMemberPath | John Papa

John Papa

Evangelist on the loose

Binding to Silverlight ComboBox and Using SelectedValue, SelectedValuePath and DisplayMemberPath

...

“How do you bind a ComboBox to a collection of objects, and then bind a property from the selected object’s to some other scalar property?” I received this question today from a friend of mine (a variation of this question). I decided to walk through the scenario here in case anyone else runs into it. This is one of those things that can be confusing … it is simple, but it is is much easier shown the explained. This post lays out the scenario using some new features to Silverlight 4 and you can download the sample code at the end.

When we first load the page and open the ComboBox it should look like this, with each state’s full name (State.Name) being displayed in the ComboBox items.

image

And when we select a state it’s state code (State.Code) is bound to the TextBlock. In the screen capture below you can see the state of Washington is selected and its state code of WA is bound to the TextBlock above the ComboBox.

image

This quick demo shows the behavior we want to achieve. Let’s assume we have an object (we’ll assume it is a ViewModel) bound to the Silverlight View (the View being the UserControl).

NOTE: You’ll notice I am using View and ViewModel here and you’ll probably conclude I am using MVVM … and you would be correct. However keep in mind that MVVM is not needed, I just decided to use it to make the example clearer using separation with classes. We could have called them whatever we wanted.

This ViewModel has a property called States which is a ObservableCollection<State>. The State object the properties:

  • string Code (ex: WA)
  • string Name (ex: Washington)

The ViewModel is bound to the View, as its DataContext. A ComboBox in the View is bound to the list of states in the ViewModel’s States property. When the project loads, we expect the list of states to be displayed in the ComboBox.Each state’s full name should appear (from the State.Name property). When a state is selected in the ComboBox, the State.Code property should be grabbed and set to the ViewModel’s SelectedStateCode property. The trick to doing this is to set your XAML for your ComboBox like this:

   1: <ComboBox Height="23" HorizontalAlignment="Left" Margin="12,50,0,0" 

   2:           Name="comboBox1" VerticalAlignment="Top" Width="252" 

   3:           ItemsSource="{Binding Path=States, Mode=OneWay}" 

   4:           SelectedValue="{Binding Path=SelectedStateCode, Mode=TwoWay}" 

   5:           DisplayMemberPath="Name" 

   6:           SelectedValuePath="Code"  />

   7: <TextBlock Height="23" HorizontalAlignment="Left" 

   8:            Margin="187,16,0,0" Name="textBlock1" 

   9:            Text="{Binding Path=SelectedStateCode}" 

  10:            VerticalAlignment="Top" Width="65" />

Notice the following 4 properties are set as follows:

  • ItemsSource is bound to the ViewModel’s States property (a collection of State objects)
  • DisplayMemberPath is set to “Name” (This is the State.Name property)
  • SelectedValuePath is set to “Code” (This is the State.Code property)
  • SelectedValue is bound to the ViewModel’s SelectedStateCode property

The key here are the DisplayMemberPath and SelectedValuePath properties. These apply to the object that each item in the ComboBox is bound to. In other words, these properties are set to the State, not the ObservableCollection<State>. Also, notice these properties are not data bound, they are instead set to the name of the properties respectively. We do not want the values of the properties here, we want the actual name of the properties (which is why it is called DisplayMemberPath and SelectedValuePath).

image

 

 

Download the source code for this sample ComboBox project here.

 

WhitePaper2

 

SelectedValue and SelectedValuePath are new to Silverlight 4. You can find more information on this new feature to Silverlight 4 and many more in the Silverlight 4 whitepaper found here.

 

 

I hope this helps!

UPDATE: I added the XAML for the TextBlock above too. The compelte code can be downloaded from the link above.

tags: Silverlight
  • Anonymous

    Di I miss the code for binding the textblock?

  • Anonymous

    It’s probably worth noting that the SelectedValue and SelectedValuePath property was added to the ComboBox control in Silverlight 4. Previous versions were missing this property, which then required creating a derived custom control in order to be able to bind this.

  • http://www.afanaat.nl Anonymous

    This could also be done (even in SL3) by
    A) exposing a SelectedState property on the ViewModel, or
    B) by binding the TextBlock Text property to the selected item of the ComboBox.
    A)
    – Create a property on the ViewModel of type State and call it SelectedState
    – Bind the SelectedItem property of the ComboBox to the SelectedState property on the ViewModel. Use Mode=TwoWay
    – Bind the Text property of the TextBlock to SelectedState.Code on the ViewModel
    B)
    – Bind the Text property of the TextBlock to SelectedItem.Code and ElementName=comboBox1

  • Anonymous

    And how do we make cascading comboboxes (country, state and city, for example) work with databinding in SL4?

  • http://johnpapa.net JohnPapa

    Jeff Proser – I added the TextBlock code in the post. It is also in the download source too.
    Martin Randall – I did mention that these are new to SL 4 in the end, but I made it a little clearer. Thanks for the suggestion.
    Leonidas – You can bind 1 combobox to another using Element binding (available starting with Silverlight 3). So if you had a list of countries and you wanted to filter states by it, when the value is selected in the country you could then filter the collection that is bound to the states ComboBox by that country. There are a few ways to do this that you can search on. If I get some time I will add it to my blog post queue :)

  • http://www.tamm79.de/?p=108 Anonymous

    Pingback from Markus Tamm » Blog Archive » Links 12.05.2010

  • Anonymous

    John,
    Thanks for your answer, and please do it! I’ve been searching for a easy solution for this situation, and everybody who has done it had to code a lot of stuff to answer something that should be simple.

  • http://www.avrashow.net Anonymous

    I really like these cookbook examples of commonly-needed techniques. Very applicable to general scenarios. Nice to have them in little bite-sized posts instead of just in the context of a larger example.

  • Anonymous

    hi, this is exactly what i’ looking for. Thanks a lot. A question is how to you set the inital value for the combo box. I mean default selected item.

  • http://www.scotttleckie.com Anonymous

    It’s pretty easy once you fugure it out; http://www.scottleckie.com/…/silverlight-dat

  • Anonymous

    Hi John,
    Thanks for clearing this up.
    There is also need to put validation against combobox for blank values.
    I am putting <Required()> attribute in my RIA services MetaData class.
    Apparently, conmbobox validation is fired ONLY after SelectedItemChanged event, instead of LostFocus event for TextBoxes.
    A user may not select any value in combobox(Thereby not invoking SelectedItemChanged event and not invoking server side validation).
    I want validation for combobox to occure at LostFocus.
    How to do this?
    Thanks,
    Mahesh.

  • Anonymous

    Is it required to edit the xaml to do this?

  • Anonymous

    How about extending this example to support null values, i.e, nullable combo box?

  • Anonymous

    Thanks for the example. But I am still stuck.
    I have 2 tables being exposed via the entity framework througha Ria Service.
    Table 1 = Status
    Table 2 = Master
    Master contains 3 fields
    Field 1 = Status1
    Field 2 = Status2
    Field 3 = Status3
    The first combo box I create works like a champ.
    The second and third cause problems.
    It seems like because the second and third are both bound to the same data context as the first, all 3 combo boxes and all 3 status fields change when I select a new value in any of the three combo boxes.
    I’ve solved this by adding 2 more data contexts to my XAML and pointing the other combo boxes at them, but this seems awkward.
    My next project needs a ria service bound combobox as a column in a Datagrid and this first project is not making me look forward to it.

  • http://smehrozalam.wordpress.com/ Anonymous

    Nice post, John. I also once customized the AutoCompleteBox from Silverlight toolkit to include properties like SelectedValue, SelectedValuePath. The resulting AutoCompleteComboBox is MVVM compatible and can be used in Concrete Object-to-Object associations as well as Foreign-Key associations. The full article can be read at: http://www.codeproject.com/…/AutoComplete_Co
    I hope you will enjoy the article.

  • http://www.devsolution.net Anonymous

    Hi JohnPapa, thank you for sample .

  • http://www.devsolution.net Anonymous

    Hi John, thank you for sample.

  • Jeanine

    Thanks for the example.
    I’m currently working on a project that has a simple combobox. When I make a new selection on the combobox, I want the view model property it’s bound to to be changed to the id selected. But when it’s changed, the “set” is never called for the property. Is this normal behaviour for a combobox? Do I have to have a textbox hidden that holds the currently selected ID instead of relying of the model property?

  • http://johnpapa.net johnpapa.net

    Binding to silverlight combobox and using selectedvalue selectedvaluepath and displaymemberpath.. Super :)

  • http://johnpapa.net johnpapa.net

    Binding to silverlight combobox and using selectedvalue selectedvaluepath and displaymemberpath.. Smashing :)

  • Chris Lane

    I was reading through “Binding to Silverlight ComboBox and Using SelectedValue, SelectedValuePath and DisplayMemberPath” and I’m very new to Silverlight. I wonder if you could provide me an example using domain data sets instead of POCO. I hope I’m being clear in what I’m asking. :-) If not let me know and I’ll try to clarify. I’m really stuck here…
    Thank You so much,
    Christopher

  • ssanchezz

    I’m using the combobox with a two-way binding on SelectedValue. But it only works one-way. From view to viewmodel and not from viewmodel to view. I want this to be able to set a default value when it’s a new entity and the previous selected value when existing entity.. Anyone got same problem? Or idea to solve this? Thx in advance!!

  • Hemant

    Hello sir!
    I am Binding ComboBox to List.
    Please suggest me how to set it default selectedIndex to 0 as it is showing blank because its selectedindex is -1

  • Carlton

    I am stuck with displaying the data from a database when the page is loaded! I am OK with populating the Itemsource, displaying the items in the list with DisplayMemberPath, setting which field to use as selected value with SelectedValuePath and sending the selected value with SelectedValue, but which combobox property I should bind to with the MVVM property to show in the combobox when the page is loaded?

  • http://www.freeresumeworld.com logical

    Can you provide a us example without MVVM.
    Do we really need to inherit interface
    INotifyPropertyChanged
    Is ther another way to do this, I dont want do it with MVVM.

  • Nasser

    Hello , i have a question perhaps you have the answer.
    If i have a combobox in datagrid in Lightswitch, and the first column is product, and this column is choice list , if i chose one product , how to get the price and the coli beside . i hope the you get what i mean.
    Thank you

  • Bhushan

    This was really helpful .. Thanks for sharing ..

%d bloggers like this: