Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple WPF + MVVM binding

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.

like image 761
Cartesius00 Avatar asked May 19 '11 04:05

Cartesius00


2 Answers

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.

like image 139
TBohnen.jnr Avatar answered Oct 24 '22 10:10

TBohnen.jnr


  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.

like image 2
dthorpe Avatar answered Oct 24 '22 09:10

dthorpe