0
votes

I am learning Josh Smith's Wpf app and trying to understand the MVVM pattern. You can download the app from here

My question is very simple, the app has Menu Items defined on the MainView which are bound to the MainWindow view model. I need to click the menu options to trigger a check box in the CustomerViewModel. So far this is what I have done, I wired the menuitem click command to a method in the MainWindowViewModel, this method then raises an event Called OptionsMenuItemClicked. I then implemented a listener on the CustomerViewModel, this listener would call a method which should do my logic for doing check on the check box. The event is raised but the method is not firing. Can anyone please help. Here is screen shot of what I am trying to achieve:

enter image description here

Here is my code of what I have done, I am hoping someone can point me to the right direction

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
    }
1

1 Answers

0
votes

The problem is:

   MainWindowViewModel vm = new MainWindowViewModel(null);
   vm.CheckMenuItemClicked += vm_CheckMenuItemClicked;

You simply attach to a wrong instance of MainWindowViewModel. the event is not fired from this instance because it isn't the same as DataContext of the window.

void someFunctionInsideMainWindowViewModel()
{
    CustomerViewModel customerVm = new CustomerViewModel(...);
    this.OptionsMenuItemClicked += (sender, e)=>
    {
        //logic to check the check box
        //you have access to customerVm from here
    };
}