【问题标题】:KeyBinding on KeyUp OR propagate KeyUp to WindowKeyUp 上的 KeyBinding 或将 KeyUp 传播到 Window
【发布时间】:2015-04-16 20:54:54
【问题描述】:

所以我有以下 KeyBindings:

<Page.InputBindings>
    <KeyBinding Key="Space" Command="{Binding AcceptCommand}" />
    <KeyBinding Key="Esc" Command="{Binding CancelCommand}"/>
</Page.InputBindings>

我还使用附加行为将 InputBindings 传播到祖先窗口,因为如果我没有焦点问题,并且命令并不总是在我想要的时候被调用。 Here's a link 方便的方法。

我的问题是 KeyBindings 发生在 KeyDown 上,我希望它们发生在 KeyUp 上。根据我的阅读,这是不可能的,您必须处理 KeyUp 事件并从代码隐藏中执行所有操作。虽然这并不理想,但如果必须,我会这样做,但是我不知道如何将 KeyUp 从页面传播到窗口。

我尝试进行类似于输入绑定的附加行为,但事件的本质是我无法分离事件,也无法检查事件是否为空,除非我在拥有事件的实际类中(在这种情况下,Page)。

有人对如何做到这一点有任何想法吗?

【问题讨论】:

    标签: c# wpf xaml


    【解决方案1】:

    我从 InputBinding 中制作了以下 KeyUpBinding,以防您需要添加更多依赖属性作为 CommandParameter 只需添加为对象:

     public class KeyUpBinding : InputBinding
    {
        public Key Key
        {
            get { return (Key)GetValue(KeyProperty); }
            set { SetValue(KeyProperty, value); }
        }
    
        public static readonly DependencyProperty KeyProperty =
            DependencyProperty.Register("Key", typeof(Key), typeof(KeyUpBinding), new PropertyMetadata(Key.A, KeyChanged));
    
        private static void KeyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var keybinding = (d as KeyUpBinding);
    
            Keyboard.AddKeyUpHandler(App.Current.MainWindow, (s, ku) =>
            {
                if(keybinding.Command!=null && ku.Key == keybinding.Key && ku.IsUp)
                {
                    keybinding.Command.Execute(null);
                }
            });
        }
    
    
        public ICommand Command
        {
            get { return (ICommand)GetValue(CommandProperty); }
            set { SetValue(CommandProperty, value); }
        }
    
        public static readonly DependencyProperty CommandProperty =
            DependencyProperty.Register("Command", typeof(ICommand), typeof(KeyUpBinding), new PropertyMetadata(null));
    
    
    }
    

    【讨论】:

    • 这看起来很有希望......难道它不会从 InputBinding 继承 Command、CommandParameter 等属性,从而无需添加它们吗?此外,我尝试使用与上面的 KeyBindings 基本相同的方式,但使用 KeyUpBindings,并且永远不会调用 KeyChanged 函数。我的使用略有不同,因为我的 WPF 项目是一个 DLL,并且我正在实例化一个 NavigationWindow 来使用而不是 App.Current.MainWindow,但我怀疑这就是原因,因为它无论如何都没有达到这一点。
    • 你的意思是继承键绑定,它没有激活事件处理程序的选项(可能是你找到了一种方法)然后它会调用两次一次向下,以防你可以一次向上
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-10
    • 1970-01-01
    • 2020-12-14
    • 2011-12-07
    • 2016-03-09
    相关资源
    最近更新 更多