情况:
我有一个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>
然后在 my ContextMenu
of my中像这样使用它MyUserControl
:
<UserControl.ContextMenu>
<ContextMenu x:Name="GrowingContextMenu">
<MenuItem Header="Grow"
Command="{x:Static local:Commands.GrowingOperation}"
CommandParameter="grow"/>
</ContextMenu>
</UserControl.ContextMenu>
问题:
出现ContextMenu
,但既GrowingOperationExecuted
没有被调用,也没有GrowingOperationCanExecute
被调用。打开ContextMenu
.
打开ContextMenu
看起来像这样:
它似乎已启用,但绝对没有交互,甚至没有悬停动画。这里的错误在哪里?
编辑:
这里执行命令方法:
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();
}
}
编辑2:
我的构造函数MyUserControl
:
public GrowingDisplay()
{
InitializeComponent();
HeightProperty.AddOwner(typeof (GrowingDisplay),
new FrameworkPropertyMetadata(OnHeightPropertyChanged));
WidthProperty.AddOwner(typeof (GrowingDisplay),
new FrameworkPropertyMetadata(OnWidthPropertyChanged));
CommandManager.InvalidateRequerySuggested();
}