AvaloniaUI: 全局捕获鼠标按钮的抬起和按下事件

4
有没有可能在AvaloniaUI中全局捕获鼠标按下按钮事件(包括上下)?以便在任何控件之外(或者可能在任何特定视图模型之外)被通知这些事件?
1个回答

4

您可以在MainWindow的代码后台中监听这些事件,并处理已由其他控件处理过的事件,使用 handledEventsToo: true

public class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = new MainWindowViewModel();

        this.AddHandler(PointerPressedEvent, MouseDownHandler, handledEventsToo: true);
        this.AddHandler(PointerReleasedEvent, MouseUpHandler, handledEventsToo: true);

        #if DEBUG
        this.AttachDevTools();
        #endif
    }

    private void MouseUpHandler(object sender, PointerReleasedEventArgs e)
    {
        System.Diagnostics.Debug.WriteLine("Mouse released.");
    }

    private void MouseDownHandler(object sender, PointerPressedEventArgs e)
    {
        System.Diagnostics.Debug.WriteLine("Mouse pressed.");
    }

    private void InitializeComponent()
    {
        AvaloniaXamlLoader.Load(this);
    }
}

请注意,如果您有多个窗口,则此方法(可能)不会在全局范围内起作用。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接