【发布时间】:2013-07-05 16:56:26
【问题描述】:
情况:
我有一个静态的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 我的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();
}
【问题讨论】:
标签: c# xaml user-controls routed-commands