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.
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.
<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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With