您好我正在学习Josh Smith的Wpf应用并尝试了解MVVM模式。您可以从here
下载该应用我的问题很简单,应用程序在MainView上定义了菜单项,这些菜单项绑定到MainWindow视图模型。我需要单击菜单选项以触发CustomerViewModel中的复选框。到目前为止,这就是我所做的,我将menuitem click命令连接到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);
}
}
CustomerViewModel
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
}
答案 0 :(得分:0)
问题是:
MainWindowViewModel vm = new MainWindowViewModel(null);
vm.CheckMenuItemClicked += vm_CheckMenuItemClicked;
您只是附加到MainWindowViewModel
的错误实例。 此事件未触发此事件,因为它与窗口的DataContext不同。
void someFunctionInsideMainWindowViewModel()
{
CustomerViewModel customerVm = new CustomerViewModel(...);
this.OptionsMenuItemClicked += (sender, e)=>
{
//logic to check the check box
//you have access to customerVm from here
};
}