Wpf 从父窗口绑定到UserControl RoutedCommand
我正在尝试创建一个UserControl,它显示多页图像,并允许用户缩放、旋转和浏览图像。我遇到的一个问题是正确设置键盘快捷键。我发现我需要在承载UserControl的窗口类上设置InputBindings。我确实知道如何在代码背后创建InputBinding,但我希望有很多键盘快捷键,我认为在XAML中使用它们会更容易。下面是我正在测试的一个示例项目: MainWindow.xamlWpf 从父窗口绑定到UserControl RoutedCommand,wpf,user-controls,commandbinding,inputbinding,Wpf,User Controls,Commandbinding,Inputbinding,我正在尝试创建一个UserControl,它显示多页图像,并允许用户缩放、旋转和浏览图像。我遇到的一个问题是正确设置键盘快捷键。我发现我需要在承载UserControl的窗口类上设置InputBindings。我确实知道如何在代码背后创建InputBinding,但我希望有很多键盘快捷键,我认为在XAML中使用它们会更容易。下面是我正在测试的一个示例项目: MainWindow.xaml <Window x:Class="CommandTest.Window1" xmlns="http
<Window x:Class="CommandTest.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:CommandTest"
Title="Window1" Height="300" Width="344">
<Window.InputBindings>
<KeyBinding
Key="N"
CommandTarget="x:UCon"
/>
</Window.InputBindings>
<StackPanel>
<local:NestedControl x:Name="UCon">
</local:NestedControl>
</StackPanel>
</Window>
UserControl1.xaml
<UserControl x:Class="CommandTest.NestedControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<UserControl.Resources>
<!-- UI commands. -->
<RoutedCommand x:Key="Commands.ZoomOut" />
</UserControl.Resources>
<UserControl.CommandBindings>
<CommandBinding x:Name="ZoomCommand" Command="{StaticResource Commands.ZoomOut}" CanExecute="ZoomCommand_CanExecute" Executed="ZoomCommand_Executed"/>
</UserControl.CommandBindings>
<Button Command="{StaticResource Commands.ZoomOut}">Zoom</Button>
</UserControl>
与其将键绑定到窗口,不如将其绑定到命令本身(如果这是自定义命令,则可以在ZoomCommand的构造函数中执行此操作): 然后,在UserControl的构造函数中:
Window.GetWindow(this).CommandBindings.Add(new CommandBinding(new ZoomCommand(), ZommCommand_handler));
在代码中创建命令比在XAML中创建命令更好吗?这是否意味着您不能在XAML中将InputBinding添加到UserControl的主机?而且,这个解决方案不起作用。UserControl1没有键盘焦点,因此InputBinding不会触发。如果您单击按钮,然后使用按键手势,消息框将显示您是否使用代码或XAML来创建命令,这实际上取决于您自己——两者都不是“更好”。我选择这里的代码是因为它需要更少的行,所以可能更容易理解。我编辑了我的答案,将命令绑定到窗口。
using System.Windows.Controls;
using System.Windows.Input;
namespace CommandTest
{
public partial class NestedControl : UserControl
{
public NestedControl()
{
InitializeComponent();
}
private void ZoomCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private void ZoomCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
System.Windows.MessageBox.Show("Zoom", "Zoom");
}
}
}
ZoomCommand.InputGestures.Add(new KeyGesture(Key.N));
Window.GetWindow(this).CommandBindings.Add(new CommandBinding(new ZoomCommand(), ZommCommand_handler));