【发布时间】:2014-11-26 20:39:39
【问题描述】:
我正在学习 Josh Smith 的 Wpf 应用程序并尝试了解 MVVM 模式。您可以从here下载该应用程序
我的问题很简单,应用程序在 MainView 上定义了菜单项,这些菜单项绑定到 MainWindow 视图模型。我需要单击菜单选项来触发 CustomerViewModel 中的复选框。到目前为止,这就是我所做的,我将 menuitem 单击命令连接到 MainWindowViewModel 中的一个方法,然后该方法引发一个名为 OptionsMenuItemClicked 的事件。然后我在 CustomerViewModel 上实现了一个侦听器,该侦听器将调用一个方法,该方法应该执行我的逻辑来检查复选框。引发事件,但方法未触发。任何人都可以请帮忙。这是我想要实现的屏幕截图:
这是我所做的代码,我希望有人能指出我正确的方向
XAML
<MenuItem Header="Options">
<MenuItem Header="Check"
Command="{Binding Path= CheckCommand}"/>
</MenuItem>
MainWindowViewModel
public event EventHandler CheckMenuItemClicked = delegate { };
private RelayCommand _checkCommand;
public ICommand CheckCommand
{
get
{
if(_checkCommand == null)
{
_checkCommand = new RelayCommand(param=>this.RaiseEventForCustomerViewModel());
}
return _checkCommand;
}
}
private void RaiseEventForCustomerViewModel()
{
EventHandler handler = this.CheckMenuItemClicked;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
客户视图模型
public CustomerViewModel(Customer customer, CustomerRepository customerRepository)
{
if (customer == null)
throw new ArgumentNullException("customer");
if (customerRepository == null)
throw new ArgumentNullException("customerRepository");
_customer = customer;
_customerRepository = customerRepository;
_customerType = Strings.CustomerViewModel_CustomerTypeOption_NotSpecified;
MainWindowViewModel vm = new MainWindowViewModel(null);
vm.CheckMenuItemClicked += vm_CheckMenuItemClicked;
}
void vm_CheckMenuItemClicked(object sender, EventArgs e)
{
//logic to check the check box
}
【问题讨论】: