RelayCommand未在MenuItem上触发,单击WPF MVVM [英] RelayCommand not firing on MenuItem click WPF MVVM

查看:64
本文介绍了RelayCommand未在MenuItem上触发,单击WPF MVVM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在WPF表单上有一个运行导入例程的菜单项,我已经将命令属性绑定到了视图模型中的ICommand属性,但是由于某种原因该方法无法触发.

I have menu item on my WPF form that runs a import routine, I have bound the command property to a ICommand property in my view model but for some reason the method won't fire.

这是xaml:

<Menu Height="21"
              Margin="0,-2,0,0"
              VerticalAlignment="Top"
              Grid.ColumnSpan="2">
            <MenuItem Header="File" Command="{Binding ImportFileCommand}">Import</MenuItem>
</Menu>

这是我的视图模型:

        private ICommand importfilecommand;
        public ICommand ImportFileCommand
        {
            get
            {
                if (this.importfilecommand == null)
                {
                    this.importfilecommand =  new RelayCommand(parm => ImportFile());
                }
                return this.importfilecommand;
            }
        }

        private void ImportFile()
        {

            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "Tab Files (*.tab)|*.tab*";

            if (dialog.ShowDialog() == true)
            {
            //    MessageBox.Show(dialog.FileName);
            }
        }

这是我用于表单上所有按钮的模式,但是菜单项无法使用.我是否缺少某些东西,或者菜单项是否必须以其他方式处理?

This is the pattern that I have used for all my buttons on the form but the menu item just won't work. Am I missing something or does menu items have to be done differently?

谢谢.

推荐答案

将XAML更改为

<Menu Height="21" Margin="0,-2,0,0" VerticalAlignment="Top" Grid.ColumnSpan="2">
    <MenuItem Header="File">
        <MenuItem Header="Import" Command="{Binding ImportFileCommand}" />
    </MenuItem>
</Menu>

在您的示例中,MenuItem元素的导入"内容隐式创建了父文件MenuItem的子MenuItem.此子MenuItem没有定义Command属性,因此无法执行.显然,子菜单扩展功能会覆盖在父MenuItem上定义的Command的可执行性.

In your example, the "Import" content of the MenuItem element implicitly creates a child MenuItem of the parent File MenuItem. This child MenuItem has no Command property defined and so is unable to be executed. Apparently the executability of the Command defined on the parent MenuItem is overridden by the sub-menu expansion functionality.

这篇关于RelayCommand未在MenuItem上触发,单击WPF MVVM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆