我是wpf和mvvm概念的新手.这里有一个我正在研究的教程,但我无法理解这一部分; 在图7中:
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.
EventHandler handler = null;
handler = delegate
{
viewModel.RequestClose -= handler;
window.Close();
};
viewModel.RequestClose += handler;
// 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)
做什么viewModel.RequestClose -= handler;和viewModel.RequestClose += handler;做什么?
viewModel.RequestClose += handler;添加EventHandler到RequestClose事件.-=删除它.
请注意,删除它是作为清理完成的,因为看起来在处理程序中完成的下一步操作是关闭窗口.
MainWindowViewModel是一个发布一个名为的事件的对象RequestClose.您的代码正在订阅该活动.您的代码想要在触发该事件时进行处理.您可以通过使用向事件添加处理程序来实现+=.当您这样做,并且MainWindowViewModel实例触发事件时,您的处理程序将运行.事件允许对象之间的一种解耦形式的通信.看起来您的处理程序也将关闭窗口,因此需要通过从事件中删除处理程序来进行进一步的清理操作-=.
请参阅MSDN文档以了解事件.
事件使类或对象在发生感兴趣的事件时通知其他类或对象.发送(或引发)事件的类称为发布者,接收(或处理)事件的类称为订阅者.