In my app I have 2 views. List(GridView) and Form. I am changing views as proposed in this thread: WPF MVVM switch usercontrols
Now I have a problem how to pass id of selected item after click edit to show new View with the edit form.
Simple application to list all items, add new, delete and edit. How can I do this in MVVWM?
UPDATE
I just want to create a simple application, that has menu on the left with:
- List
- Add new.
When click List, it shows UC with list and 3 buttons: Add, Edit, Delete. After click add, edit it shows UC with Form with specific values (while editing). How can I achieve this??
As far as I understand, you want something like this:
So that when you click
Add
, it shows this:Right?
So you need the following behaviour:
I will assume that you are working with some repository.
I propose the following MVVM structure:
MainViewModel
: The DataContext for the main screen.BaseViewModel RightViewModel
: The container for viewmodels shown on the right part of the screen.ICommand ViewListCommand
: Shows the list by creating a new instance ofListViewModel
and assigning it to theBaseViewModel
property.ICommand AddNewCommand
: Shows the addnew screen by creating a new isntance ofAddViewModel
and assigning it to theBaseViewModel
property.Then:
ListViewModel
: The DataContext for the right part of the screen when List is clicked.List<Items> Items
: Provides the items to be shown.Item SelectedItem
: The property that will be binded to the SelectedItem on the UI.ICommand EditCommand
: The command that will get the selected item and notify the MainViewModel that has to be edited.So at some point, a viewmodel will receive a notification from a child viewmodel (i.e. list will tell main to edit somethin). I recommend to do this by using events as:
The xaml binding is not necessary since it will be quite forward.
This is a very basic example about how I think this kind of stuff can be handled. The important thing here is to properly unhook the events, otherwise you can run into problems.
For this kind of stuff you can also have a look at Reactive UI.
If you have a common parent of the view models, then you can use that parent to pass parameter values for you. Simply set up one or more
delegate
s in the relevant view models:In the view model with the relevant parameter to update... let's call it
ParameterViewModel
:In the parent:
Back in
ParameterViewModel
when the parameter changes:Now in the parent view model:
You can find out more about using
delegate
objects from the Delegates (C# Programming Guide) page on MSDN.