【发布时间】:2014-10-19 15:28:38
【问题描述】:
我被 wpf 命令和“非平凡的”热键困住了。我想将“+”键映射到某个命令。在我希望它继续与任何文本框一起工作。下面是示例
Commands.cs
public static class Commands
{
private static readonly ICommand _someCommand;
static Commands()
{
_someCommand = new RoutedCommand("cmd", typeof(Commands), new InputGestureCollection { new KeyGesture(Key.OemPlus), new KeyGesture(Key.Add) });
}
public static ICommand SomeCommand
{
get { return _someCommand; }
}
}
MainWindow.xaml
<Window x:Class="WpfHotkeysTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:wpfHotkeysTest="clr-namespace:WpfHotkeysTest"
Title="MainWindow" Height="350" Width="525">
<Window.CommandBindings>
<CommandBinding Command="wpfHotkeysTest:Commands.SomeCommand" Executed="CommandBinding_OnExecuted"></CommandBinding>
</Window.CommandBindings>
<TextBox></TextBox>
</Window>
MainWindow.xaml.cs
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void CommandBinding_OnExecuted(object sender, ExecutedRoutedEventArgs e)
{
Debug.WriteLine("COMMAND! " + e.Source);
}
}
问题是当我专注于文本框时,它在执行命令之前无法处理按下的“+”键。 我希望显示我的密钥,但如何以最好的方式实现呢?
UPD 如果密钥由文本框处理,我不想执行命令。
我知道有属性 CanExecuteRoutingEventArgs.ContinueRouting。但它同时执行命令和文本框处理
【问题讨论】:
-
您可以为该命令实现
CanExecuteRoutingEventHandler,或者在执行命令之前手动检查是否有任何TextBox被聚焦。如果有任何TextBox被关注,请不要执行该命令。 -
是的,到目前为止,我最终得到了这个解决方案。谢谢!
-
您应该重新考虑您的用例。你真的想要只有“+”作为命令触发器,而不是与例如组合“控制”?少按一个按钮有什么好处?真的值得吗?
-
我同意 ctrl++ 会更好,但这个问题是关于可用性的,客户希望它是那样的。