【问题标题】:How to get the sender of the InputBinding-Command如何获取 InputBinding-Command 的发送者
【发布时间】:2012-12-24 08:09:02
【问题描述】:
我有这个 xaml 代码:
<Window.InputBindings>
<KeyBinding Command="{Binding Path=KeyEnterCommand}" Key="Enter" />
</Window.InputBindings>
这就是我的 ViewModel 中的代码:
private RelayCommand _keyEnterCommand;
public ICommand KeyEnterCommand
{
get
{
if (_keyEnterCommand == null)
{
_keyEnterCommand = new RelayCommand(param => ExecuteKeyEnterCommand());
}
return _keyEnterCommand;
}
}
public void ExecuteKeyEnterCommand()
{
// Do magic
}
现在是我的问题,我怎样才能得到这个命令的发送者?
【问题讨论】:
标签:
wpf
command
key-bindings
relaycommand
【解决方案1】:
如果“发送者”是指按下键时获得焦点的元素,那么您可以将当前获得焦点的元素作为参数传递给命令,如下所示:
<Window x:Class="MyWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="root">
<Window.InputBindings>
<KeyBinding Command="{Binding Path=KeyEnterCommand}"
CommandParameter="{Binding ElementName=root, Path=(FocusManager.FocusedElement)}"
Key="Escape" />
</Window.InputBindings>
...
private RelayCommand<object> _keyEnterCommand;
public ICommand KeyEnterCommand
{
get
{
if (_keyEnterCommand == null)
{
_keyEnterCommand = new RelayCommand<object>(ExecuteKeyEnterCommand);
}
return _keyEnterCommand;
}
}
public void ExecuteKeyEnterCommand(object sender)
{
// Do magic
}
【解决方案2】:
您还可以使用 CommandTarget 属性。这是一个稍微不同的用法,因为它使用 WPF 附带的预定义命令。但是,我不确定这是否/如何与从 ICommand 继承的类一起使用。
wpf.2000things.com 上的一篇文章说:
路由命令的来源是调用
命令。 Executed 或 CanExecute 处理程序中的 sender 参数
是拥有事件处理程序的对象。设置命令
Button 的参数到特定命令,然后绑定
命令到主窗口的 CommandBindings 中的某些代码,
按钮是源,窗口是发送者。
在设置Command属性的时候,也可以设置CommandTarget
属性,指示应该被视为的不同元素
路由命令的来源。
在下面的示例中,Find 命令现在似乎源自 TextBox。我们可以在 Executed 事件的事件处理程序中看到这一点:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Commands" Width="320" Height="220">
<Window.CommandBindings>
<CommandBinding Command="ApplicationCommands.Find"
CanExecute="Find_CanExecute"
Executed="Find_Executed"/>
</Window.CommandBindings>
<StackPanel>
<TextBox Name="txtSomeText"
Width="140" Height="25" Margin="10"/>
<Button Content="Find"
Command="ApplicationCommands.Find"
CommandTarget="{Binding ElementName=txtSomeText}"
Margin="10" Padding="10,3"
HorizontalAlignment="Center" />
</StackPanel>
</Window>