如何将ContextMenu的单击处理程序绑定到函数

时间:2014-04-03 07:04:44

标签: c# wpf wpf-controls

我有一些XAML如下:

<UserControl x:Class="Foo">
  <UserControl.Resources>
    <ContextMenu x:Key="ContextMenu1">
      <MenuItem Header="Command 1a"/>
      <MenuItem Header="Command 1b"/>
    </ContextMenu>
    <ContextMenu x:Key="ContextMenu2">
      <MenuItem Header="Command 2a"/>
      <MenuItem Header="Command 2b"/>
    </ContextMenu>
  </UserControl.Resources>

  <DockPanel>
    <TreeView>
      <TreeView.Resources>
        <DataTemplate DataType="{x:Type Type1}">
          <StackPanel ContextMenu="{StaticResource ContextMenu1"}/>
        </DataTemplate>

        <DataTemplate DataType="{x:Type Type2}">
          <StackPanel ContextMenu="{StaticResource ContextMenu2"}/>
        </DataTemplate>
      </TreeView.Resources>
    </TreeView>
  </DockPanel>
</UserControl>

和类似于以下内容的代码:

public class Type1 {
  public void OnCommand1a() {}
  public void OnCommand1b() {}
}

public class Type2 {
  public void OnCommand2a() {}
  public void OnCommand2b() {}
}

单击菜单上的相应项目,我需要做什么才能调用相应的功能?

如果我添加:

Command="{Binding Path=OnCommand1a}" CommandTarget="{Binding Path=PlacementTarget}"

等然后在运行时我得到有关OnCommand1a不是属性的错误。一些搜索表明这与RoutedUIEvent有关,但我真的不明白那是什么。

如果我使用

Click="OnCommand1a" 

然后它在UserControl上查找OnCommand1a()而不是绑定到DataTemplate的类型。

处理此问题的标准方法是什么?

1 个答案:

答案 0 :(得分:2)

首先,您需要一个扩展ICommand的类。 你可以用这个:

public class DelegateCommand : ICommand
{
    private readonly Action<object> executeMethod = null;
    private readonly Func<object, bool> canExecuteMethod = null;

    public event EventHandler CanExecuteChanged
    {
        add { return; }
        remove { return; } 
    }

    public DelegateCommand(Action<object> executeMethod, Func<object, bool> canExecuteMethod)
    {
        this.executeMethod = executeMethod;
        this.canExecuteMethod = canExecuteMethod;
    }

    public bool CanExecute(object parameter)
    {
        if (canExecuteMethod == null) return true;
        return this.canExecuteMethod(parameter);
    }

    public void Execute(object parameter)
    {
        if (executeMethod == null) return;
        this.executeMethod(parameter);
    }
}

然后,在您的类Type1中,您必须声明:

public DelegateCommand OnCommand1a {get; private set;}

并以这种方式在Type1构造函数中设置它:

OnCommand1a = new DelegateCommand(c => Cmd1a(), null);

其中Cmd1a是:

private void Cmd1a()
{
     //your code here
}

最后,在你的xaml中:

Command="{Binding Path=OnCommand1a}"