自定义Command,默认继承于ICommand,之后的扩展会继承IRelayCommand,这样可以使用属性。[NotifyCanExecuteChangedFor(nameof(XXXX))]

CustomCommand.axaml代码

<Window xmlns="https://github.com/avaloniaui"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:local="using:AvaloniaUI"
        Height="300" Width="300"
        x:Class="AvaloniaUI.CustomCommand"
        Title="CustomCommand">
    <Grid>
        <Button Margin="5" HorizontalAlignment="Center" Command="{x:Static local:DataCommands.Requery}">点我</Button>
    </Grid>
</Window>

CustomCommand.axaml.cs代码

using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Markup.Xaml;
using System;
using System.Windows.Input;

namespace AvaloniaUI;

public class DataCommands : ICommand
{
    public class ExecutedRoutedEventArgs : EventArgs
    {
        public object? Parameter { get; }
        public ExecutedRoutedEventArgs(object? parameter) => Parameter = parameter;
    }
    public string Name { get; }
    public KeyGesture? Gesture { get; }

    public event EventHandler? CanExecuteChanged;
    public event EventHandler<ExecutedRoutedEventArgs>? Executed;

    public DataCommands(string name, KeyGesture? gesture = null)
    {
        Name = name;
        Gesture = gesture;
    }

    public bool CanExecute(object? parameter) => true;

    public void Execute(object? parameter) =>
        Executed?.Invoke(this, new ExecutedRoutedEventArgs(parameter));

    public void RaiseCanExecuteChanged() =>
        CanExecuteChanged?.Invoke(this, EventArgs.Empty);

    public static readonly DataCommands Requery =
        new DataCommands("Requery", new KeyGesture(Key.R, Avalonia.Input.KeyModifiers.Control));
}

public partial class CustomCommand : Window
{ 
    public CustomCommand()
    {
        InitializeComponent();
        this.KeyDown += OnKeyDown;
        DataCommands.Requery.Executed += (_, e) =>
        {
            var dlg = new Window
            {
                Title = "提示",
                Width = 250,
                Height = 200,
                Content = new TextBlock
                {
                    Text = "Requery被执行了",
                    VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center,
                    HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center
                }
            };
            dlg.ShowDialog(this);
        };
    }
    private void OnKeyDown(object? sender, KeyEventArgs e)
    {
        // 判断 Ctrl+R
        if (e.Key == Key.R && e.KeyModifiers.HasFlag(Avalonia.Input.KeyModifiers.Control))
        {
            DataCommands.Requery.Execute(null);
            e.Handled = true;
        }
    }
}

运行效果(按下Ctrl + R)

image

 

posted on 2025-08-08 10:44  dalgleish  阅读(20)  评论(0)    收藏  举报