简体   繁体   English

WPF:ComboBox F4键未在KeyDown事件中触发

[英]WPF: ComboBox F4 key is not firing in KeyDown Event

I need to stop F4's default functionality for ComboBox. 我需要停止F4的ComboBox默认功能。 While googling for it, I came across in various solutions with previewkeydown of combobox. 在谷歌搜索时,我遇到了各种解决方案,使用了combobox的预览。 But for my requirement i cant restrict the previewkeydown event. 但是根据我的要求,我无法限制previewkeydown事件。 Any other way to handle this case?. 还有其他办法处理这种情况吗? If it is a bug in combobox, any other workaround to get the keydown event for F4 key. 如果它是组合框中的错误,任何其他解决方法来获取F4键的keydown事件。

If you want to disable for all ComboBox in your application, then you can do this. 如果要在应用程序中禁用所有ComboBox,则可以执行此操作。 Register your KeyDown for ComboBox application wide. 在ComboBox应用程序范围内注册KeyDown。 You can add this statement in your application start (App.xaml.cs or AppBootStrapper if you are using MVVM) 您可以在应用程序启动时添加此语句(如果您使用的是MVVM,则为App.xaml.cs或AppBootStrapper)

EventManager.RegisterClassHandler(typeof(ComboBox) ,UIElement.KeyDownEvent ,new KeyEventHandler((sender ,e) =>
{
    var cb = sender as ComboBox;
    if ( cb != null && e.Key == Key.F4 )
        e.Handled = true;   
}));

Be aware, this is not tested. 请注意,这未经过测试。 I used similar approach for TextBox move focus on enter. 我使用类似的方法将TextBox移动重点放在enter上。

Although i know this question is old, but i write my tricky solution (as i not found it across web) for someone engaging this problem: 虽然我知道这个问题已经过时了,但是我写了一个棘手的解决方案(因为我没有在网上找到它)来解决这个问题:

I must say that this behavior is not a bug, It is a common action over all standard drop-down (ComboBox) controls across Windows. 我必须说这种行为不是一个错误,它是Windows上所有标准下拉(ComboBox)控件的常见操作。

And you can override it simply in WPF by using CommandBinding . 您可以使用CommandBinding在WPF中简单地覆盖它。

public class MyWindow
{
   private static readonly RoutedCommand DummyEmptyCommand = new RoutedCommand("DummyEmptyCommand", typeof(MyWindow), new InputGestureCollection() { new KeyGesture(Key.F4) });

   public MyWindow()
   {
      MyComboBox.CommandBindings.Add(new CommandBinding(DummyEmptyCommand, (o, e) => 
      { 
         // Do your work here or simply leave it blank to disable F4 common behavior;
      }));
   }
}

In this way, You can implement your own alternative work or just disable the standard common windows behavior. 通过这种方式,您可以实现自己的替代工作,或者只是禁用标准的常见窗口行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM