如何使用MVVM Light Toolkit关闭带有取消按钮的ChildWindow

Jér*_*oul 7 silverlight mvvm childwindow icommand mvvm-light

我是MVVM的新手,并试图找出如何使用MVVM Light Toolkit使用传统的Cancel按钮关闭ChildWindow.

在我的ChildWindow(StoreDetail.xaml)中,我有:

<Button x:Name="CancelButton" Content="Cancel" Command="{Binding CancelCommand}" />
Run Code Online (Sandbox Code Playgroud)

在我的ViewModel(ViewModelStoreDetail.cs)中,我有:

public ICommand CancelCommand { get; private set; }

public ViewModelStoreDetail()
{
    CancelCommand = new RelayCommand(CancelEval);
}

private void CancelEval()
{
    //Not sure if Messenger is the way to go here...
    //Messenger.Default.Send<string>("ClosePostEventChildWindow", "ClosePostEventChildWindow");
}
Run Code Online (Sandbox Code Playgroud)

aqw*_*ert 0

看看MSDN 上的这篇文章。大约一半的地方有一个关于如何做到这一点的方法。基本上它要么使用一个,WorkspaceViewModel要么你实现一个公开事件的接口RequestClose

然后,您可以在窗口的 DataContext 内部(如果您将 ViewModel 设置为它)附加到该事件。

这是文章的摘录(图 7)。您可以调整它以满足您的需要。

// In App.xaml.cs
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);

MainWindow window = new MainWindow();

// Create the ViewModel to which 
// the main window binds.
string path = "Data/customers.xml";
var viewModel = new MainWindowViewModel(path);

// When the ViewModel asks to be closed, 
// close the window.
viewModel.RequestClose += delegate 
{ 
    window.Close(); 
};

// Allow all controls in the window to 
// bind to the ViewModel by setting the 
// DataContext, which propagates down 
// the element tree.
window.DataContext = viewModel;

window.Show();
}
Run Code Online (Sandbox Code Playgroud)