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...
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;
}
}
To avoid adding handlers everywhere you could subclass the TextBox
and add a PreviewKeyDown
event handler which 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 does mean that you will need to replace all usages of TextBox
with MyTextBox
in your XAML, so unfortunately you are going to have to edit all your views anyway.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With