RelayCommand not firing on MenuItem click WPF MVVM

柔情痞子 提交于 2019-12-14 03:42:38

问题


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.

This is the xaml:

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

And this is in my view model:

        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?

Thanks.


回答1:


Change your XAML to

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

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.



来源:https://stackoverflow.com/questions/1943081/relaycommand-not-firing-on-menuitem-click-wpf-mvvm

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!