3

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

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

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

4

1 回答 1

3

您可以处理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)));
        }
    }
}
于 2011-06-13T23:26:33.527 回答