在回调方法中,我想知道如何触发命令绑定。最重要的是我必须找出键盘快捷键是否触发了命令,而不是使用的按钮或菜单项。
这是我的回调方法:
private void AddObjectCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
yap.AddObject(false);
}
我假设我可以使用object参数,但它始终是传递的视图(窗口),而不是按钮或菜单项。
我需要这个,因为命令应该在我的屏幕上添加一个新对象。如果使用键盘快捷键,我想在鼠标位置添加对象。如果单击菜单快捷方式,这(显然)不是一个好主意。该对象应添加到屏幕中间。
我可以创建两个不同的命令,但只使用一个命令,菜单中也会显示快捷方式,这是首选。
答案 0 :(得分:1)
您可以在命令参数中传递一些值来识别调用者,并使用 ExecutedRoutedEventArgs e来获取该值。
public static class Commands
{
public static readonly RoutedCommand testcommand = new RoutedCommand();
}
private void MyCmd_Executed(object sender, ExecutedRoutedEventArgs e)
{
string parameter = (string)e.Parameter;
MessageBox.Show(parameter);
}
XAML
<Window.CommandBindings>
<CommandBinding
Command="{x:Static local:Commands.testcommand}"
Executed="MyCmd_Executed"
/>
</Window.CommandBindings>
<Window.InputBindings>
<KeyBinding Command="{x:Static local:Commands.testcommand}"
CommandParameter="From key Binding"
Key="H" Modifiers="Alt"/>
</Window.InputBindings>
<Grid>
<Menu>
<MenuItem Header="My Command"
Command="{x:Static local:Commands.testcommand}"
CommandParameter="From bmenuitem"/>
</Menu>
答案 1 :(得分:0)
在回调方法中,我想知道命令绑定是如何被触发的
我担心此信息不会传递给事件处理程序。如果要区分键盘快捷键和其他类型的调用,实际上应该使用两个不同的命令。
他们可能会做同样的事情,例如调用相同的方法。但是没有办法告诉命令是如何在Executed
事件处理程序中执行的。