一个用于多个MenuItem的Commandhandler

时间:2013-02-28 12:00:32

标签: c# wpf mvvm

在我的xaml代码中,我有一个包含如下项目的菜单:

<Menu x:Name="menu" Grid.Row="0" Background="Transparent" HorizontalAlignment="Right">
        <MenuItem Header="Root">
            <MenuItem Header="Sub1" Command="{Binding Command}" CommandParameter="{Binding ???}"></MenuItem>
            <MenuItem Header="Sub2" Command="{Binding Command}" CommandParameter="{Binding ???}"></MenuItem>
            <MenuItem Header="Sub3" Command="{Binding Command}" CommandParameter="{Binding ???}"></MenuItem>
            <MenuItem Header="Sub4" Command="{Binding Command}" CommandParameter="{Binding ???}"></MenuItem>
            <MenuItem Header="Sub5" Command="{Binding Command}" CommandParameter="{Binding ???}"></MenuItem>
            <MenuItem Header="Sub6" Command="{Binding Command}" CommandParameter="{Binding ???}"></MenuItem>
        </MenuItem>
</Menu>

Command是ICommand类型的属性。实施是

 public class RelayCommand : ICommand
{
    private readonly Action<object> execute;
    private readonly Predicate<object> canExecute;

    public RelayCommand(Action<object> execute, Predicate<object> canExecute = null)
    {
        if (execute == null)
            throw new ArgumentNullException("execute");
        this.execute = execute;
        this.canExecute = canExecute;
    }

    public void Execute(object parameter)
    {
        this.execute(parameter);
    }

    public bool CanExecute(object parameter)
    {
        return this.canExecute == null || this.canExecute(parameter);
    }

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }
}

在我的viewmodel的构造函数中,我有一行:

this.Command = new RelayCommand(OnMenuItemExecute);

OnMenuItemExecute的方法是:

private void OnMenuItemExecute(object parameter)
{
   // Here i want to know which menuitem executed the command
}

我只是不知道我作为命令参数传递了什么

1 个答案:

答案 0 :(得分:1)

如果您想要对菜单项的引用,您可以使用相对的自我来源。

<MenuItem Header="Sub1" Command="{Binding Command}" CommandParameter="{Binding RelativeSource={RelativeSource Self}}"></MenuItem>