7

I have a class named MyWindow the derives from Window. I use the MVVM pattern so in code-behind I have the following field:

public MyViewModel ViewModel = new MyViewModel();

ViewModel contains a collection of Person, and all I'd like to do is to bind a ComboBox to this collection, show Person.Name as the header for each Person.
I would also like to have another field in ViewModel that will be data-bound to the selected item.

Please help me.

MasterMastic
  • 20,711
  • 12
  • 68
  • 90
Cartesius00
  • 23,584
  • 43
  • 124
  • 195
  • Have a look at his link http://stackoverflow.com/questions/561166/binding-wpf-combobox-to-a-custom-list/561427#561427 – biju May 19 '11 at 05:39

2 Answers2

5

Well firstly you have to set the datacontext of your window to the viewmdodel in the constructor if you have not already done so:

this.DataContext = MyModelView;

Then you can set the ComboBox as follows:

<ComboBox ItemsSource={Binding Persons} SelectedItem={Binding CurrentPerson,Mode=TwoWay} DisplayMemberPath="Name"/>

Where Persons is the Collection of Persons and Current Person is the Property the selected person will be bound to.

TBohnen.jnr
  • 5,117
  • 1
  • 19
  • 26
2
  1. Assign the modelView to the MyWindow.DataContext property. This makes it available for data binding.
  2. Define the data binding in the combobox xaml like this:

<ComboBox ItemsSource="{Binding PersonCollection}" DisplayMemberPath="Name" SelectedValue="{Binding SelectedPerson}" > </ComboBox>

This assumes that your modelView has a property PersonCollection which is a collection of Person objects, a property Name on the Person object, and a property SelectedPerson on the modelView of type Person.

dthorpe
  • 35,318
  • 5
  • 75
  • 119