[英]RoutedCommand in ContextMenu in UserControl
情況:
我有一個靜態的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>
然后在MyUserControl
ContextMenu
中像這樣使用它:
<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();
}
我將您的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"
將其放在打開的窗口標簽中。 (假設這是一個窗口)然后在設置命令時可以使用:
<UserControl.CommandBindings>
<CommandBinding Command="commands:Commands.GrowingOperation"
Executed="GrowingOperationExecuted"
CanExecute="GrowingOperationCanExecute"/>
我唯一的問題是:您如何實現GrowingOperationExecuted
和GrowingOperationCanExecute
?
這篇文章應該有助於解決您的問題: http : //wpftutorial.net/RoutedCommandsInContextMenu.html 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.