WPF: Using RoutedCommand in Modal Windows the MVVM way

I have a WPF application which I am trying to implement in a MVVM pattern (as much as possible). One of my view models opens a child window with code like this:

SomeChildWindow childWin = new SomeChildWindow();
childWin.DataContext = someChildViewModel;
childWin.ShowDialog();

The problem I am having is that a RoutedCommand I am using in SomeChildWindow is not getting received:

<Button Content="Do Work" Command="root:GlobalCommand.DoWork"/>

GlobalCommand is a static class and DoWork is a RoutedUICommand. I have DoWork bound to the my main view model with code like this:

//Method inside the main view model
public void BindGlobalCommands(Window win)
{
    win.CommandBindings.Add( new CommandBinding
        ( GlobalCommand.DoWork, (s, e) => { this.DoSomeWork(); } ) );
}

I did some research and I am quite sure that I am having the same problem as the person who asked this question: WPF Routed Commands and ShowDialog Windows. However, the answer provided to that question requires that the parent view model have direct knowledge of its own view, which mine doesn't

Am I spawning windows in a correct MVVM way?

How can I use RoutedCommand in my child Window?


For dialogs I create separate ViewModels that can be part of the main ViewModel.

The main ViewModel instantiates the dialog's VM, creates the Dialog, sets the DataContext and waits for the dialog to close (if it is Modal)

The Dialog uses the commands on the dialog's ViewModel.

Once the Dialog closes, the main ViewModel looks at the result of the Dialog (Yes, No, Cancel, Ok, ...) which can be a property of the dialog's VM. Based on this result the main VM then uses the content of the dialog to execute some command(s).

This way the dialog is reusable and the main VM stays in control.

链接地址: http://www.djcxy.com/p/9606.html

上一篇: WPF MVVM授权

下一篇: WPF:在Modal Windows中使用RoutedCommand是MVVM的一种方式