Avalonia 事件转 Command Behav

处理类


# 继承自 AvaloniaObject (实际其它类也可以)
# 使用 RegisterAttached 注册应用于 Interactive (发出单击事件的对象) 的 command 属性,
# 当 command 属性变更时,注册对应 Interactive 属性的单击事件 
# 在单击事件处理函数中调用 command 

using System.Windows.Input;
using Avalonia;
using Avalonia.Input;
using Avalonia.Interactivity;

/// <summary>
///     单击调用事件
/// </summary>
public class TappedBehav : AvaloniaObject
{
    // 1. 注册 2 个扩展属性 CommandProperty CommandParameterProperty
    public static readonly AttachedProperty<ICommand> CommandProperty = AvaloniaProperty.RegisterAttached<TappedBehav, Interactive, ICommand>(
        "Command");

    // 1. 注册 2 个扩展属性 CommandProperty CommandParameterProperty
    public static readonly AttachedProperty<object> CommandParameterProperty = AvaloniaProperty.RegisterAttached<TappedBehav, Interactive, object>(
        "CommandParameter");

    static TappedBehav()
    {
        // 3. 监听 CommandProperty 值改变事件 
        CommandProperty.Changed.AddClassHandler<Interactive>(HandleCommandChanged);
    }

    public static ICommand GetCommand(AvaloniaObject element)
    {
        return element.GetValue(CommandProperty);
    }

    public static object GetCommandParameter(AvaloniaObject element)
    {
        return element.GetValue(CommandParameterProperty);
    }

    public static void SetCommand(AvaloniaObject element, ICommand commandValue)
    {
        element.SetValue(CommandProperty, commandValue);
    }

    public static void SetCommandParameter(AvaloniaObject element, object parameter)
    {
        element.SetValue(CommandParameterProperty, parameter);
    }

    // 4. 当元素绑定了 command 后,对应的元素单击事件执行处理函数
    private static void HandleCommandChanged(Interactive interactElem, AvaloniaPropertyChangedEventArgs args)
    {
        interactElem.RemoveHandler(InputElement.TappedEvent, TappedEventHandler);

        if (args.NewValue is ICommand commandValue)
        {
            interactElem.AddHandler(InputElement.TappedEvent, TappedEventHandler);
        }
    }

    // 5. 处理元素的单击处理事件
    private static void TappedEventHandler(object? s, RoutedEventArgs e)
    {
        if (s is not Interactive interactElem)
        {
            return;
        }

        // 这是如何从GUI元素中获取参数的方法。
        var commandParameter = interactElem.GetValue(CommandParameterProperty);
        var commandValue = interactElem.GetValue(CommandProperty);
        if (commandValue?.CanExecute(commandParameter) == true)
        {
            commandValue.Execute(commandParameter);
        }
    }
}

调用

<!-- #ChannelConfigurationPopup 根据名称找到元素  -->
  <Border TappedBehav.Command="{Binding #ChannelConfigurationPopup.StartCloseCommand}"
  TappedBehav.CommandParameter=""
                Background="Transparent"
                IsVisible="{Binding #ChannelConfigurationPopup.IsOpen}"
                ZIndex="1" />
上一篇
下一篇