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

When the user presses the Insert key in the WPF text box, the control switches between the insert and overwrite mode. This is usually rendered using a different cursor (line against block), but it is not. Since the user is completely unaware that the rewrite mode is active, I just would like to completely disable it. When the user presses the Insert key (or, however, this mode can be activated, intentionally or accidentally), the TextBox should simply remain in insert mode.

I could add some keypress event handler and ignore all such events by pressing the Insert key without modifiers. It would be enough? Do you know a better alternative? There are several TextBox controls in my view, and I don't want to add event handlers everywhere ...

+4
source share
2 answers

You can make AttachedProperty and use the proposed ChrisF method, so its eay to add to the TextBoxes you want, although 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; } } 
+6
source

To avoid adding handlers everywhere, you can subclass the TextBox and add a PreviewKeyDown event handler that does as you suggest.

In the constructor:

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

However, this means that you will need to replace all TextBox usages with MyTextBox in your XAML, so unfortunately you still have to edit all your views.

+3
source

Source: https://habr.com/ru/post/1498078/


All Articles