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

发布于 2024-07-25 16:12:35 字数 204 浏览 2 评论 0原文

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

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

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

I have a reusable usercontrol that uses a few commands and corresponding keyboard gestures,
(specifically Escape and Ctrl+1...Ctrl+9)

Now as I use this usercontrol in multiple locations I'd like to define the input gestures in the usercontrol, which works fine as long as the focus is within the usercontrol. However, I'd need it to work as long as focus is within the current page/window.

How can I do it, or do I really have to do command/input bindings on every page?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

甜嗑 2024-08-01 16:12:35

您可以处理 UserControlLoaded 事件,并沿着逻辑树向上查找所属页面/窗口,然后您可以在其中添加绑定。

例如

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)));
        }
    }
}

You could handle the Loaded event of the UserControl and walk up the logical tree to find the owning page/window, then you can add the bindings there.

e.g.

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)));
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文