Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVVM - How do I open a window based on a selected item from a list?

Tags:

mvvm

wpf

I am quite new to the WPF & MVVM world, and have spent the last few days downloading as many tutorials as I could, and reading as much as possible!

I am however struggling to implement with a very basic and common concept with MVVM and am desperate for some help - and perhaps even an example :-)

I've got the basics of M-V-VM, commanding, and even messenging; but how on earch do I open a new window and set that windows ViewModel to the selected item of a listbox?

Let me explain: I have a Model called Client and it has some properties I then have a ViewModel which gets all my Clients and stores them in an ObservableCollection I have a screen where I display the Name & Surname in a listbox and allow the user to filter and search.

All of the above work perfectly.

When a user selects an item though, I would like to open an editable "detailed client view" screen of that particular client. This detailed screen's ViewModel would need to somehow bind to the selected item (if that makes sense); or I need to be able to pass a paramter to the newly opened screen's ViewModel. In fact, if the user could open several detail screens at the same time and edit multiple clints it would be great!

If anyone can give me a nice example, or point me in the right direction I would truly be greatful!

Many thanks, Brendan

like image 260
Brendan Avatar asked Dec 28 '10 19:12

Brendan


2 Answers

I would add an event to the ListBox.SelectionChanged which does the following:

  • Creates a new Dialog and DialogViewModel
  • Binds the DialogViewModel.EditableContentProperty to the ListBox's SelectedItem
  • Dialog.DataContext = DialogViewModel
  • Dialog.ShowDialog()
like image 83
Rachel Avatar answered Nov 01 '22 09:11

Rachel


Simply put:

//Create the Client Detail form
frmClientDetails frm = new frmClientDetails();
frm.Owner = this;
var ViewModel = new ClientDetailViewModel((Client)lstFoundClients.Items.CurrentItem);
frm.DataContext = ViewModel;
frm.Show();
like image 30
Brendan Avatar answered Nov 01 '22 09:11

Brendan