【问题标题】:Issue with UserControl and KeyBinding (WPF)UserControl 和 KeyBinding (WPF) 的问题
【发布时间】:2015-08-21 04:18:13
【问题描述】:

我有一个带有 ContentControl 的窗口,我在其中显示我的用户控件。每个用户控件都有其 KeyBindings。问题是当用户控件失去焦点时,键绑定不起作用。如果我单击用户控件之外的窗口中的任何位置,我将无法访问键绑定。我可以使用全局键绑定,但每个都是特定的用户控件?我找到了一些解决方案,但不为我服务。谢谢!

【问题讨论】:

  • 您希望它如何工作?如果有多个用户控件具有不同的键绑定,当用户控件没有焦点时会发生什么?应该激活哪些键绑定?
  • 每个用户控件都有一个或多个 KeyBinding 但没有一个不重复。理想情况下,它只会激活我正在显示的用户控件的相应键绑定。我需要虽然用户控件没有焦点,但键绑定工作。

标签: c# wpf


【解决方案1】:

你能做什么:

  1. 创建包含命令的新类。每个命令都代表您想要在用户控件中执行的操作

    public static class CustomCommands
    {
        public static readonly RoutedUICommand SettingsCommand = new RoutedUICommand
            (
                    "SettingsCommand",
                    "SettingsCommand",
                    typeof(CustomCommands),
                    new InputGestureCollection()
                            {
    
                            }
            );
    }
    
  2. 在您的用户控件中订阅此命令:

在 XAML 中:

<UserControl.CommandBindings>
    <CommandBinding Command="local:CustomCommands.SettingsCommand" Executed="OnSettingsExecuted"></CommandBinding>
</UserControl.CommandBindings>

或者在代码隐藏中:

CustomCommands.SettingsCommand.Executed += (s, e) => { };
  1. 在您的窗口中将键绑定到命令:

    <Window.InputBindings>
        <KeyBinding Key="S" Modifiers="Control" Command="local:CustomCommands.SettingsCommand" />
    </Window.InputBindings>
    

因此,您将拥有在窗口处于活动状态时将被接受的窗口比例键绑定。

希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多