我正在尝试创建一个显示多页图像的UserControl,并允许用户缩放,旋转和浏览图像。我遇到问题的一个部分是正确设置键盘快捷键。我想我需要在托管UserControl的Window类上设置InputBindings。我确实弄清楚如何在后面的代码中创建一个InputBinding,但我期待很多键盘快捷键,我认为在XAML中使用它们会更容易。这是一个我正在测试它的示例项目:
MainWindow.xaml
<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>
MainWindow.Xaml.cs
using System.Windows;
using System.Windows.Input;
namespace CommandTest
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
KeyGesture keyg = new KeyGesture(Key.OemPlus, ModifierKeys.Control);
KeyBinding kb = new KeyBinding((ICommand)UCon.Resources["Commands.ZoomOut"], keyg);
kb.CommandTarget = UCon;
this.InputBindings.Add(kb);
}
}
}
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>
UserControl1.xaml.cs
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");
}
}
}
答案 0 :(得分:0)
不是将键绑定到Window,而是将其绑定到命令本身(如果这是自定义命令,您可以在ZoomCommand的构造函数中执行此操作):
ZoomCommand.InputGestures.Add(new KeyGesture(Key.N));
然后,在UserControl的构造函数中:
Window.GetWindow(this).CommandBindings.Add(new CommandBinding(new ZoomCommand(), ZommCommand_handler));