2

I have a menu item on my WPF form that runs an 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 do menu items have to be done differently?

Thanks.

codersl
  • 2,222
  • 4
  • 30
  • 33
Nathan W
  • 54,475
  • 27
  • 99
  • 146
  • Do you have the proper DataContext coming to the Menu? That part is not clear from the question. Otherwise it looks good. – Jobi Joy Dec 21 '09 at 22:50
  • Yeah if I set a break point on the ImportFileCommand the RelayCommand is getting newed up but it just doesn't want to fire. – Nathan W Dec 21 '09 at 22:53

1 Answers1

4

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
  • 2,323
  • 2
  • 22
  • 27