首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用依赖项属性的WPF按钮快捷键

使用依赖项属性的WPF按钮快捷键
EN

Stack Overflow用户
提问于 2022-05-14 13:20:26
回答 1查看 139关注 0票数 -1

我正在使用一组标准按钮,在WPF应用程序中重用,并希望向每个按钮添加一个快捷键。

所以我有一个包含命令绑定到标准命令的按钮的ControlTemplate

我试图将一个KeyBinding添加到包含Button的UserControl中,方法是向Button添加依赖项属性,并将父树导航到最近的UserControl。

我可以从模板Button获得DP值来设置键和修饰符,但是无法获得命令(可能是因为它以后才被绑定?)

有什么办法我可以:

  1. 按照这种方法,可以从模板中获取命令或创建命令
  2. 或在解析命令时获取命令,然后设置KeyBinding

PS:我已经在单独的DPs中设置了键和修饰符,但希望有一个KeyBinding的DP,然后在XAML中设置ShortcutBinding.Key和ShortcutBinding.Modifers。有办法在XAML中设置DP类的属性吗?

从按钮组模板中提取XAML:

代码语言:javascript
复制
                <ctrl:ButtonShortcut 
                    x:Name="btnUpdate"
                    Style="{StaticResource EditButtonStyle}"
                    Command="{Binding DataContext.UpdateCommand, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"
                    Content="Update"
                    ShortcutKey="U"
                    ShortcutModifiers="Ctrl"/>

从Button继承的DP类实现了键和修饰符,以便与绑定到Button的相同命令链接:

代码语言:javascript
复制
    public partial class ButtonShortcut : Button
{
    public KeyBinding ShortcutBinding { get; set; }

    public Key ShortcutKey
    {
        get { return (Key)GetValue(ShortcutKeyProperty); }
        set { SetValue(ShortcutKeyProperty, value); }
    }
    public static readonly DependencyProperty ShortcutKeyProperty =
        DependencyProperty.Register("ShortcutKey", typeof(Key), typeof(ButtonShortcut), new PropertyMetadata(Key.None, ShortcutKeyChanged));

    public ModifierKeys ShortcutModifiers
    {
        get { return (ModifierKeys)GetValue(ShortcutModifiersProperty); }
        set { SetValue(ShortcutModifiersProperty, value); }
    }
    public static readonly DependencyProperty ShortcutModifiersProperty =
        DependencyProperty.Register("ShortcutModifiers", typeof(ModifierKeys), typeof(ButtonShortcut), new PropertyMetadata(ModifierKeys.None, ShortcutKeyChanged));

    private static void ShortcutKeyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var btn = d as ButtonShortcut;
        if (btn != null)
        {
            FrameworkElement uc = btn.Parent as FrameworkElement;
            while (uc?.Parent != null && uc is not UserControl)
                uc = uc.Parent as FrameworkElement;

            if (btn.ShortcutBinding == null)
            {
                btn.ShortcutBinding = new KeyBinding();
            }
            var bindings = btn.CommandBindings;
            if (e.NewValue is Key)
                btn.ShortcutBinding.Key = (Key)e.NewValue;
            if (e.NewValue is ModifierKeys)
                btn.ShortcutBinding.Modifiers = (ModifierKeys)e.NewValue;

            //So far, so good, but I cannot find the Command to apply to the KeyBinding
            btn.ShortcutBinding.Command = btn.Command;
            btn.ShortcutBinding.CommandParameter = btn.CommandParameter;
            if (btn.Command == null)
                System.Diagnostics.Debug.Print("not in Commmand");
            if (btn.CommandBindings.Count == 0)
                System.Diagnostics.Debug.Print("not in CommandBindings");
            if (btn.ReadLocalValue(CommandProperty) == DependencyProperty.UnsetValue)
                System.Diagnostics.Debug.Print("not in DP CommandProperty");


            if (btn.ShortcutBinding.Key != Key.None && uc != null)
            {
                if (!uc.InputBindings.Contains(btn.ShortcutBinding))
                    uc.InputBindings.Add(btn.ShortcutBinding);

            }
        }
    }

    public ButtonShortcut()
    {
        InitializeComponent();
    }

}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-05-14 15:53:29

这看起来是个很难闻的设计。子控件不应配置父控件。特别是不要添加孩子假装提供的“功能”:在你的例子中,按钮不能执行关键的手势--它只定义它们。

由于父控件是手势的目标,因此它必须定义执行手势所需的处理程序。这意味着,所有的操作和责任都在父UserControl中,而不是在Button (或子元素)中。类不应该知道其他类的详细信息。按钮不应该知道哪个父程序将执行它的命令,以及如何首先注册该命令。

按钮只是一个被动的源。它本身不处理命令或手势。因此,它永远不会注册CommandBindingInputBinding

通常,将Button.Command绑定到在命令目标上定义的命令。按钮在目标上调用此命令(或引发RoutedCommand),目标执行相应的操作。

在按钮上定义命令或关键手势是没有意义的。按钮不会执行它们。必须在相关职责所在的目标上定义命令、键和鼠标手势。

您可以让父UserControl (我在本例中假设它是命令目标)定义一个RoutedCommand。使用以下命令注册相应的键手势:

解决方案1

MyUserControl.xaml.cs

代码语言:javascript
复制
partial class MyUserControl : UserControl
{
  public static RoutedCommand DoActionCommand { get; }

  static MyUserControl()
  {
    var gestures = new InputGestureCollection
    {
      new KeyGesture(Key.U, ModifierKeys.Control),
    };

    DoActionCommand = new RoutedUICommand(
      "Do something", 
      nameof(DoActionCommand), 
      typeof(CommandTargetUserControl),
      gestures);
  }

  public MyUserControl()
  {
    InitializeComponent();

    this.CommandBindings.Add(new CommandBinding(DoActionCommand, ExecuteDoActionCommand));
  }
}

CommandTargetUserControl.xaml

代码语言:javascript
复制
<MyUserControl>
  <Button Command="{x:Static local:CommandTargetUserControl.DoActionCommand}" />
</MyUserControl>

解决方案2

要允许在不修改源和目标的情况下配置默认键手势,可以实现附加行为。这种行为基本上是将一个由键手势调用的钩式命令委托给注册到特定键手势的实际命令源。命令源和命令目标完全解耦。输入绑定被显式地配置为尊重封装(没有静默和意外的修改)。

使用实例

代码语言:javascript
复制
<Window local:KeyGestureDelegate.IsKeyGestureDelegationEnabled="True">
  <local:KeyGestureDelegate.TargetKeyGestures>
    <InputGestureCollection>
      <KeyGesture>Ctrl+U</KeyGesture>
      <KeyGesture>Ctrl+Shift+M</KeyGesture>
    </InputGestureCollection>
  </local:KeyGestureDelegate.TargetKeyGestures>

  <StackPanel>
    <Button Command="{Binding SomeCommand}" 
            local:KeyGestureDelegate.SourceKeyGesture="Ctrl+U"
            local:KeyGestureDelegate.IsKeyGestureCommandExecutionEnabled="True" />
    <Button Command="{Binding SomeOtherCommand}"
            local:KeyGestureDelegate.SourceKeyGesture="Shift+Ctrl+M"
            local:KeyGestureDelegate.IsKeyGestureCommandExecutionEnabled="True" />
  </StackPanel>
</Window>

实施实例

KeyGestureDelegate.cs

在本例中使用的RelayCommand的一个实现可以在Microsoft Docs:中继命令逻辑上找到。

代码语言:javascript
复制
public class KeyGestureDelegate : DependencyObject
{
  // Custom KeyGesture comparer for the Dictionary
  private class KeyGestureComparer : EqualityComparer<KeyGesture>
  {
    public override bool Equals(KeyGesture? x, KeyGesture? y)
      => (x?.Key, x?.Modifiers).Equals((y?.Key, y?.Modifiers));

    public override int GetHashCode([DisallowNull] KeyGesture obj)
      => HashCode.Combine(obj.Key, obj.Modifiers);
  }

  private static ICommand KeyGestureDelegateCommand { get; } = new RelayCommand(ExecuteKeyGestureDelegateCommand);

  public static bool GetIsKeyGestureDelegationEnabled(DependencyObject attachedElement) => (bool)attachedElement.GetValue(IsKeyGestureDelegationEnabledProperty);
  public static void SetIsKeyGestureDelegationEnabled(DependencyObject attachedElement, bool value) => attachedElement.SetValue(IsKeyGestureDelegationEnabledProperty, value);
  public static readonly DependencyProperty IsKeyGestureDelegationEnabledProperty = DependencyProperty.RegisterAttached(
    "IsKeyGestureDelegationEnabled",
    typeof(bool),
    typeof(KeyGestureDelegate),
    new PropertyMetadata(default(bool), OnIsKeyGestureDelegationEnabled));

  public static bool GetIsKeyGestureCommandExecutionEnabled(DependencyObject attachedElement) => (bool)attachedElement.GetValue(IsKeyGestureCommandExecutionEnabledProperty);
  public static void SetIsKeyGestureCommandExecutionEnabled(DependencyObject attachedElement, bool value) => attachedElement.SetValue(IsKeyGestureCommandExecutionEnabledProperty, value);
  public static readonly DependencyProperty IsKeyGestureCommandExecutionEnabledProperty = DependencyProperty.RegisterAttached(
    "IsKeyGestureCommandExecutionEnabled",
    typeof(bool),
    typeof(KeyGestureDelegate),
    new PropertyMetadata(default(bool), OnIsKeyGestureCommandExecutionEnabled));

  public static InputGestureCollection GetTargetKeyGestures(DependencyObject obj) => (InputGestureCollection)obj.GetValue(TargetKeyGesturesProperty);
  public static void SetTargetKeyGestures(DependencyObject obj, InputGestureCollection value) => obj.SetValue(TargetKeyGesturesProperty, value);

  public static readonly DependencyProperty TargetKeyGesturesProperty = DependencyProperty.RegisterAttached(
    "TargetKeyGestures",
    typeof(InputGestureCollection),
    typeof(KeyGestureDelegate),
    new PropertyMetadata(default(InputGestureCollection), OnTargetKeyGesturesChanged));

  public static KeyGesture GetSourceKeyGesture(DependencyObject attachedElement) => (KeyGesture)attachedElement.GetValue(SourceKeyGestureProperty);
  public static void SetSourceKeyGesture(DependencyObject attachedElement, KeyGesture value) => attachedElement.SetValue(SourceKeyGestureProperty, value);
  public static readonly DependencyProperty SourceKeyGestureProperty = DependencyProperty.RegisterAttached(
    "SourceKeyGesture",
    typeof(KeyGesture),
    typeof(KeyGestureDelegate),
    new PropertyMetadata(default(KeyGesture), OnSourceKeyGestureChanged));

  // Remember added InputBindings to enable later removal
  private static Dictionary<UIElement, IList<InputBinding>> InputBindingTargetMap { get; } = new Dictionary<UIElement, IList<InputBinding>>();

  // Lookup command sources that map to a particular gesture
  private static Dictionary<KeyGesture, IList<ICommandSource>> InputBindingSourceMap { get; } = new Dictionary<KeyGesture, IList<ICommandSource>>(new KeyGestureComparer());

  private static void OnIsKeyGestureDelegationEnabled(DependencyObject attachedElement, DependencyPropertyChangedEventArgs e)
  {
    if (attachedElement is not UIElement keyGestureHandler)
    {
      throw new ArgumentException($"Attached element must be of type {typeof(UIElement)}.");
    }

    InputGestureCollection gestures = GetTargetKeyGestures(keyGestureHandler);
    if ((bool)e.NewValue)
    {
      RegisterKeyBinding(keyGestureHandler, gestures);
    }
    else
    {
      UnregisterKeyBinding(keyGestureHandler);
    }
  }

  private static void OnIsKeyGestureCommandExecutionEnabled(DependencyObject attachedElement, DependencyPropertyChangedEventArgs e)
  {
    if (attachedElement is not ICommandSource commandSource)
    {
      throw new ArgumentException($"Attached element must be of type {typeof(ICommandSource)}.");
    }

    KeyGesture keyGesture = GetSourceKeyGesture(attachedElement);
    if ((bool)e.NewValue)
    {
      RegisterCommandBinding(commandSource, keyGesture);
    }
    else
    {
      UnregisterCommandBinding(commandSource, keyGesture);
    }
  }

  private static void OnTargetKeyGesturesChanged(DependencyObject attachedElement, DependencyPropertyChangedEventArgs e)
  {
    if (attachedElement is not UIElement keyGestureHandler)
    {
      throw new ArgumentException($"Attached element must be of type {typeof(UIElement)}.");
    }

    if (e.OldValue is InputBindingCollection)
    {
      UnregisterKeyBinding(keyGestureHandler);
    }

    if (!GetIsKeyGestureDelegationEnabled(keyGestureHandler))
    {
      return;
    }
    RegisterKeyBinding(keyGestureHandler, e.NewValue as InputGestureCollection);
  }

  private static void OnSourceKeyGestureChanged(DependencyObject attachedElement, DependencyPropertyChangedEventArgs e)
  {
    if (attachedElement is not ICommandSource commandSource)
    {
      throw new ArgumentException($"Attached element must be of type {typeof(ICommandSource)}.");
    }

    UnregisterCommandBinding(commandSource, e.OldValue as KeyGesture);

    if (!GetIsKeyGestureCommandExecutionEnabled(attachedElement))
    {
        return;
    }
    RegisterCommandBinding(commandSource, e.NewValue as KeyGesture);
  }

  private static void ExecuteKeyGestureDelegateCommand(object commandParameter)
  {
    if (InputBindingSourceMap.TryGetValue(commandParameter as KeyGesture, out IList<ICommandSource> commandSources))
    {
      foreach (ICommandSource commandSource in commandSources)
      {
        ExecuteCommandSource(commandSource);
      }
    }
  }

  private static void ExecuteCommandSource(ICommandSource commandSource)
  {
    if (commandSource.Command is RoutedCommand routedCommand)
    {
      IInputElement commandTarget = commandSource.CommandTarget ?? commandSource as IInputElement;
      if (routedCommand.CanExecute(commandSource.CommandParameter, commandTarget))
      {
        routedCommand.Execute(commandSource.CommandParameter, commandTarget);
      }
    }
    else if (commandSource.Command?.CanExecute(parameter: commandSource.CommandParameter) ?? false)
    {
      commandSource.Command.Execute(commandSource.CommandParameter);
    }
  }

  private static void RegisterKeyBinding(UIElement keyGestureHandler, InputGestureCollection inputGestureCollection)
  {
    if (inputGestureCollection == null)
    {
      return;
    }

    IList<InputBinding>? inputBindings = new List<InputBinding>();
    InputBindingTargetMap.Add(keyGestureHandler, inputBindings);
    foreach (KeyGesture gesture in inputGestureCollection.OfType<KeyGesture>())
    {
      var inputBinding = new KeyBinding(KeyGestureDelegateCommand, gesture) { CommandParameter = gesture };
      keyGestureHandler.InputBindings.Add(inputBinding);
      inputBindings.Add(inputBinding);
    }
  }

  private static void UnregisterKeyBinding(UIElement keyGestureHandler)
  {
    if (InputBindingTargetMap.TryGetValue(keyGestureHandler, out IList<InputBinding>? inputBindings))
    {
      foreach (InputBinding inputBinding in inputBindings)
      {
        keyGestureHandler.InputBindings.Remove(inputBinding);
      }
      InputBindingTargetMap.Remove(keyGestureHandler);
    }
  }

  private static void RegisterCommandBinding(ICommandSource commandSource, KeyGesture keyGesture)
  {
    if (keyGesture == null)
    {
      return;
    }

    if (!InputBindingSourceMap.TryGetValue(keyGesture, out IList<ICommandSource>? commandSources))
    {
      commandSources = new List<ICommandSource>();
      InputBindingSourceMap.Add(keyGesture, commandSources);
    }
    commandSources.Add(commandSource);
  }

  private static void UnregisterCommandBinding(ICommandSource commandSource, KeyGesture keyGesture)
  {
    if (keyGesture == null)
    {
      return;
    }

    if (InputBindingSourceMap.TryGetValue(keyGesture, out IList<ICommandSource>? commandSources))
    {
      commandSources.Remove(commandSource);
      if (!commandSources.Any())
      {
        InputBindingSourceMap.Remove(keyGesture);
      }
    }
  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72240608

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档