代码之家  ›  专栏  ›  技术社区  ›  mostlytech

如何从用户控件为页面/窗口创建输入笔势

  •  3
  • mostlytech  · 技术社区  · 16 年前

    我有一个可重用的用户控件,它使用一些命令和相应的键盘手势, (特别是转义和ctrl+1…ctrl+9)

    现在,当我在多个位置使用这个用户控件时,我想在用户控件中定义输入手势,只要焦点在用户控件中,它就可以正常工作。但是,只要焦点在当前页面/窗口中,我就需要它工作。

    我该怎么做呢,或者我真的需要在每个页面上进行命令/输入绑定吗?

    1 回复  |  直到 12 年前
        1
  •  3
  •   brunnerh    14 年前

    你可以处理 Loaded 事件 UserControl 在逻辑树中查找所属的页面/窗口,然后可以在其中添加绑定。

    例如

    public partial class Bogus : UserControl
    {
        public Bogus()
        {
            Loaded += (s, e) => { HookIntoWindow(); };
            InitializeComponent();
        }
    
        private void HookIntoWindow()
        {
            var current = this.Parent;
            while (!(current is Window) && current is FrameworkElement)
            {
                current = ((FrameworkElement)current).Parent;
            }
            if (current != null)
            {
                var window = current as Window;
                // Add input bindings
                var command = new AlertCommand();
                window.InputBindings.Add(new InputBinding(command, new KeyGesture(Key.D1, ModifierKeys.Control)));
            }
        }
    }