views:

298

answers:

1

Hi all,

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  A: 

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.

Tim Erickson
I can't believe I looked over that.
Nathan W