我正在编写我的第一个
WPF应用程序,并试图让我的自定义命令工作.
public static RoutedUICommand Header1 { get; private set; } . . . gestures = new InputGestureCollection(); gestures.Add(new KeyGesture(Key.D1,ModifierKeys.Control,"Ctrl+1")); Header1 = new RoutedUICommand("Header 1","Header1",typeof(EditCommands),gestures);
然后我在我的窗口的XAML中添加了一个CommandBindings部分.
<!-- local refers to my application's namespace --> <Window.CommandBindings> <CommandBinding Command="local:EditCommands.Header1" Executed="CommandBinding_Executed" CanExecute="CommandBinding_CanExecute"></CommandBinding> </Window.CommandBindings>
最后,在关联的Ribbon控件中添加了一个命令条目.
<RibbonButton Label="Header 1" Command="local:EditCommands.Header1" SmallImageSource="Images\small.png" ToolTipTitle="Header 1" ToolTipDescription="" ToolTipImageSource="Images\small.png"></RibbonButton>
解决方法
还有其他事情必须继续.是否有一些元素在使用包含命令的命令绑定到达元素之前处理键输入?
Snooop是一个很有用的工具来搞清楚这样的事情.
每按一次Ctrl 1,就会调用HandleHeader1下面的代码.
public static class MyCommands { public static RoutedUICommand Header1 { get; } = new RoutedUICommand("Header 1",typeof(MyCommands),new InputGestureCollection { new KeyGesture(Key.D1,"Ctrl+1") }); } public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void HandleHeader1(object sender,ExecutedRoutedEventArgs e) { } } <Window x:Class="WpfApplication2.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfApplication2" mc:Ignorable="d" Title="MainWindow" Height="350" Width="525"> <Window.CommandBindings> <CommandBinding Command="local:MyCommands.Header1" Executed="HandleHeader1"/> </Window.CommandBindings> <StackPanel> <TextBox/> </StackPanel> </Window>