在 WPF 文本框中禁用覆盖模式(按下插入键时)

5
当用户在WPF文本框中按下Insert键时,控件会在插入和覆盖模式之间切换。通常,这通过使用不同的光标(线条 vs. 块)来可视化,但这里并非如此。由于用户绝对无法知道覆盖模式是否处于活动状态,因此我希望完全禁用它。当用户按下Insert键(或者以任何方式激活该模式,有意或无意),文本框应该保持在插入模式。
我可以添加一些按键事件处理程序并忽略所有这样的事件,只需按下没有修饰符的Insert键即可。那就足够了吗?你知道更好的替代方案吗?我的视图中有许多文本框控件,我不想在每个地方都添加事件处理程序...
2个回答

7
你可以创建一个AttachedProperty,并使用ChrisF建议的方法,这样你就可以很容易地在整个应用程序中添加想要的TextBoxesXaml:
   <TextBox Name="textbox1" local:Extensions.DisableInsert="True" />

附加属性:

public static class Extensions
{
    public static bool GetDisableInsert(DependencyObject obj)
    {
        return (bool)obj.GetValue(DisableInsertProperty);
    }

    public static void SetDisableInsert(DependencyObject obj, bool value)
    {
        obj.SetValue(DisableInsertProperty, value);
    }

    // Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty DisableInsertProperty =
        DependencyProperty.RegisterAttached("DisableInsert", typeof(bool), typeof(Extensions), new PropertyMetadata(false, OnDisableInsertChanged));

    private static void OnDisableInsertChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is TextBox && e != null)
        {
            if ((bool)e.NewValue)
            {
                (d as TextBox).PreviewKeyDown += TextBox_PreviewKeyDown;
            }
            else
            {
                (d as TextBox).PreviewKeyDown -= TextBox_PreviewKeyDown;
            }
        }
    }

    static void TextBox_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Insert && e.KeyboardDevice.Modifiers == ModifierKeys.None)
        {
            e.Handled = true;
        }
    }

谢谢,这个很好用。也许我可以通过样式自动将附加属性添加到应用程序中的每个文本框? - ygoe
检查 e != null 是不必要的。 - Dmitri Nesteruk

4
为了避免在各个地方添加处理程序,您可以继承TextBox并添加PreviewKeyDown事件处理程序,该处理程序按照您的建议执行操作。
在构造函数中:
public MyTextBox()
{
    this.KeyDown += PreviewKeyDownHandler;
}


private void PreviewKeyDownHandler(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Insert)
    {
        e.Handled = true;
    }
}

然而,这意味着您需要将所有使用 TextBox 的地方替换为 MyTextBox,所以不幸的是,您仍然需要编辑所有视图。

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