你可以做一個AttachedProperty
和使用方法ChrisF
建議,這樣一來它的EAY添加到您想要thoughout應用程序
XAML中TextBoxes
:
<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;
}
}
謝謝,t他的作品非常好。也許我可以通過樣式自動添加附加屬性到我的應用程序中的每個文本框? – ygoe
檢查'e!= null'不是必需的。 –