【问题标题】:Wpf MVVM Josh Smith App programmatically check check box in Customer View ViewmodelWpf MVVM Josh Smith App 以编程方式检查客户视图视图模型中的复选框
【发布时间】: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
    }

【问题讨论】:

    标签: c# wpf mvvm


    【解决方案1】:

    问题是:

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

    【讨论】:

    • 我不明白,MainWindowViewModel 正在引发事件,而 CustomerViewModel 应该正在监听。 CheckCommand 从 MainWindowViewModel 触发一个名为 CheckMenuItemClicked 的事件,但 CustomerViewModel 无法使用此事件
    • 我对一些名字感到困惑。请再看看我编辑的帖子。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-14
    • 2012-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-10
    • 1970-01-01
    相关资源
    最近更新 更多