简体   繁体   中英

Using Commands declared in “Parent” ViewModel (MVVM)

(Note: I chose to not use the Navigation Framework)

I have a WizardViewModel which is linked to WizardView.
The WizardViewModel declares and instantiates a command "Next".
It also contains a Property "ActiveSpell" of Type SpellViewModel.

The SpellViewModel contains several PageViewModels, each having a View counterpart.
The ActivePage Property (on SpellViewModel) tells the ui which view to take.

Now I have the following problem:
When I click a button to switch to the next page,
I need access to the "Next" command defined in the WizardViewModel,
but I only have access to a PageViewModel there.

I could just add a Parent property to each child ViewModel,
but I'm not sure if that is a good idea.
Or maybe there is another nicer/common way to do that.

您可以使用Event Aggregator调整ViewModel之间的交互。

You don't need Parent property. Your view model structure is good, just look at the picture, to understand how you should bind your view model onto the view:

在此输入图像描述

Next command should be implemented something like that:

public void NextExecute()
{
    ActualSpell.MoveToNextPage();
}

UPDATE: According to your comment, Arokh, I've updated the post. I think, in this case you should implement ActivateCreatePersonSpell command in WizardViewModel.This command should:

  • save actual spell state
  • open CreatePerson spell
  • once person is created set saved spell with result of creation person

The last what you need to do is to bind ActivateCreatePersonSpell command to button on the page. I propose to use ViewModelLocator for these purposes.Look at this post for example.

I had to implement a wizard once and I liked and mimicked the way Josh Smith and Karl Shifflett set up their WizardViewModel and wizard page view models in this example project (source code available with the article):

http://www.codeproject.com/KB/WPF/InternationalizedWizard.aspx

They kept the Next command as part of their WizardViewModel, but created a WizardPageViewModelBase that all of the wizard pages derive from. That allowed the WizardViewModel to control which page is the current page, and it allowed the WizardViewModel to query the current page view model to see if the Next command can execute, thus enabling or disabling the Next button on the wizard. (That is, the wizard view model knew about the page view models, but the page view models didn't need to know anything about the "parent" wizard view model.)

As for adding links to parent view models, it's an approach that works, and I've done it before when I started working with MVVM, but after time I found the approach to result in some difficult to maintain code as every view model becomes interdependent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM