如何使 C# WPF 中的其他文件通用键盘事件?

How to make keyboardevent common to other files in C# WPF?

我的代码中有一个 PreviewKeyDown 事件,如下所示:

    private void Box_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Space)
        {
            e.Handled = true;
        }
        if ((e.Key == Key.V) && (e.KeyboardDevice.Modifiers & ModifierKeys.Control) != 0)
        {
            e.Handled = true;
        }
        else
        {
            base.OnKeyDown(e);
        }
    }

此代码在 wpf 中的 TextBox 或 PasswordBox 控件中阻止 Ctrl+V 和 space 键运行。

我想做的是让这段代码变得通用 在另一个文件的 PasswordBox 中调用此代码。

有什么解决办法吗?我知道我可以为每个控件分配 PreviewKeyDown 事件,但它是重复的,所以我想避免重复。

一个选择是将功能包装在可重用的附加行为中:

public static class Behavior
{
    public static bool GetHandlePreviewKeyDown(UIElement element) =>
        (bool)element.GetValue(HandlePreviewKeyDownProperty);

    public static void SetHandlePreviewKeyDown(UIElement element, bool value) =>
        element.SetValue(HandlePreviewKeyDownProperty, value);

    public static readonly DependencyProperty HandlePreviewKeyDownProperty =
        DependencyProperty.RegisterAttached(
        "HandlePreviewKeyDown",
        typeof(bool),
        typeof(Behavior),
        new UIPropertyMetadata(false, OnChanged));

    private static void OnChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        UIElement element = (UIElement)d;
        bool value = (bool)e.NewValue;
        if (value)
            element.PreviewKeyDown += Element_PreviewKeyDown;
        else
            element.PreviewKeyDown -= Element_PreviewKeyDown;
    }

    private static void Element_PreviewKeyDown(object sender, KeyEventArgs e) =>
        e.Handled = (e.Key == Key.Space) || ((e.Key == Key.V) && (e.KeyboardDevice.Modifiers & ModifierKeys.Control) != 0);
}

用法:

<TextBox local:Behavior.HandlePreviewKeyDown="true" />