简体   繁体   中英

Organizing Commands and ViewModels in MVVM

Currently I have 2 ViewModels in my project. MainViewModel is currently bound to my WPF window, so I have a command in my other ViewModel (AdventurerViewModel) that doesn't fire anymore. Is there a way to have that command fire without the ViewModel being bound or do all of my commands need to be in MainViewModel? And is there a good way to organize commands that might help me avoid this situation in the future? Any advice would be greatly appreciated.

EDIT: A bit of code

From my XAML

Button Grid.Column="3" Grid.Row="1" Content="IncreaseLevel" Command="{Binding IncreaseLevel}"

AdventurerViewModel.cs

public ICommand IncreaseLevel { get { return new RelayCommand(IncreaseLevelExecute, CanIncreaseLevelExecute); } }

    private bool CanIncreaseLevelExecute()
    {
        return true;
    }

    private void IncreaseLevelExecute()
    {
        Level++;
    }

First make sure you split the ViewModels correctly and have the commands in the correct ViewModels.

After that it might still be possible that you want to notify other ViewModels of changes in a current ViewModel. In that case you could have a look at a messaging system between ViewModels so a ViewModel can subscribe to a specific event and respond to it.

Use one ViewModel per View. If you use a Window then you should use one ViewModel. Right now in my project a have a Window which has 2 user controls in it, and each UserControl has its own ViewModel plus the ViewModel for the Window. I could put everything in one ViewModel but it is cleaner this way, but for your example I recomend you put everything in one ViewModel. It realy depends on situations or project requirements.

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