Disable overwrite mode in WPF TextBox (when pressing the Insert key)

overwrite, textbox, wpf

Solution

You could make an `AttachedProperty` and use the method `ChrisF` suggested, this way its eay to add to the `TextBoxes` you want thoughout your application

Xaml:

   <TextBox Name="textbox1" local:Extensions.DisableInsert="True" />

AttachedProperty:

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;
        }
    }

Problem

When the user presses the Insert key in a WPF TextBox, the control toggles between insert and overwrite mode. Usually, this is visualised by using a different cursor (line vs. block) but that's not the case here. Since there is absolutely no way for the user to know that overwrite mode is active, I'd simply like to disable it completely. When the user presses the Insert key (or however that mode could possibly be activated, intentionally or accidently), the TextBox should simply stay in insert mode. I could add some key press event handler and ignore all such events, pressing the Insert key with no modifiers. Would that be enough? Do you know a better alternative? There's a number of TextBox controls throughout my views, and I don't want to add event handlers everywhere...

Original source