Answer the question
In order to leave comments, you need to log in
How to create a new window using the MVVM pattern using an existing ViewModel?
There is a PersonsList form, where each list item is an object of the PersonViewModel class. Actually, the question is, how to cause the creation of a new form and, as a DataContext, pass to it an already existing object of the PersonViewModel class within the framework of the MVVM pattern?
Answer the question
In order to leave comments, you need to log in
> PersonsList I
advise you to name the form PersonsListWindow.
Then you need to create another viewmodel - PersonsListViewModel, which will be the viewmodel for the ENTIRE FORM as a whole, and which will have a Persons/PersonViewModels property of type IObservableCollection. In this collection you will have all the viewmodels for each person. Then you will have to assign PersonsListViewModel as DataContext to your PersonsListWindow form, and bind your list control (ListView for example, or DataGrid, depending on what you have) to the Persons/PersonViewModels property. It will be what is called, "by pattern". Total:
1) personsListWindow.DataContext = new PersonsListViewModel();
2) in the XAML control list (its ItemsSource property), bind to the PersonViewModels property
3) each element of the list is automatically mapped to the viewmodel from the ObservableCollection.
If you then add more controls to the form, then you can add more data for display/modification to the viewmodel for the form (PersonsListViewModel). For example, if you want to select the person responsible for the work in this list, then you can make the Leader property of the PersonViewModel type in the PersonsListViewModel. Or if you have Create / Delete buttons there, then you can set the corresponding ICommand objects.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question