您可以制作AttachedProperty
并使用ChrisF
建议的方法,这样可以轻松添加到TextBoxes
您想要的应用程序中
xml:
<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;
}
}