UserControl中的ContextMenu中的RoutedCommand

时间:2013-07-05 16:56:26

标签: c# xaml user-controls routed-commands

情况:

我有一个静态RoutedCommand定义如下:

public static class Commands
{
    public static readonly RoutedCommand GrowingOperation = new RoutedCommand("GrowingOperation", typeof(GrowingDisplay));
}

在我的MyUserControl.xaml我定义了这样的命令:

<UserControl.CommandBindings>
    <CommandBinding Command="{x:Static local:Commands.GrowingOperation}"
                    Executed="GrowingOperationExecuted"
                    CanExecute="GrowingOperationCanExecute"/>
</UserControl.CommandBindings>

然后在我ContextMenu的{​​{1}}中使用它:

MyUserControl

问题:

<UserControl.ContextMenu> <ContextMenu x:Name="GrowingContextMenu"> <MenuItem Header="Grow" Command="{x:Static local:Commands.GrowingOperation}" CommandParameter="grow"/> </ContextMenu> </UserControl.ContextMenu> 出现,但ContextMenuGrowingOperationExecuted都未被调用。打开GrowingOperationCanExecute时,我也没有任何异常。

开放式ContextMenu如下所示: enter image description here

它似乎已启用,但绝对没有交互,甚至没有悬停动画。 这里的错误在哪里?

修改

这里执行命令方法:

ContextMenu

编辑2:

private void GrowingOperationExecuted(object sender, ExecutedRoutedEventArgs e) { if (e.Parameter == null) throw new ArgumentException("ExecutedRoutedEventArgs must contain parameter."); var task = e.Parameter.ToString().ToLower(); switch (task) { case "grow": Growing.SpeedUpGrowing(); break; default: throw new ArgumentOutOfRangeException(); } } private void GrowingOperationCanExecute(object sender, CanExecuteRoutedEventArgs e) { if (e.Parameter == null) throw new ArgumentException("ExecutedRoutedEventArgs must contain parameter."); var task = e.Parameter.ToString().ToLower(); switch (task) { case "grow": e.CanExecute = Growing.CanSpeedUpGrowing(); break; default: throw new ArgumentOutOfRangeException(); } } 的构造函数:

MyUserControl

2 个答案:

答案 0 :(得分:0)

我会将RoutedCommand的定义更改为:

private static RoutedUICommand _GrowingOperation;
public static RoutedCommand GrowingOperation
{
    get
    {
        if(_GrowingOperation == null)
        {
            _GrowingOperation = new RoutedUICommand("GrowingOperation", 
                                "GrowingOperation", typeof(WINDOWNAME));
        }
        return _GrowingOperation;
}

然后,您可以通过将Commands类置于:

来清理XAML
xmlns:commands="clr-namespace:NAMESPACE.Commands"

将它放在开始的Window标签中。 (假设这是一个窗口) 然后,当您设置命令时,您可以使用:

<UserControl.CommandBindings>
<CommandBinding Command="commands:Commands.GrowingOperation"
                Executed="GrowingOperationExecuted"
                CanExecute="GrowingOperationCanExecute"/>

我唯一的问题是:您如何实施GrowingOperationExecutedGrowingOperationCanExecute

答案 1 :(得分:0)

这篇文章应该有助于解决您的问题: http://wpftutorial.net/RoutedCommandsInContextMenu.html