当用户在 WPF 文本框中按下 Insert 键时,控件会在插入和覆盖模式之间切换。通常,这是通过使用不同的光标(行与块)来可视化的,但这里的情况并非如此。由于用户绝对无法知道覆盖模式处于事件状态,因此我只想完全禁用它。当用户按下 Insert 键时(或者该模式可能被有意或无意地激活),TextBox 应该只是保持插入模式。
我可以添加一些按键事件处理程序并忽略所有此类事件,按下不带修饰符的 Insert 键。这样就够了吗?你知道更好的选择吗?在我的 View 中有许多 TextBox 控件,我不想在任何地方添加事件处理程序......
最佳答案
你可以做一个 AttachedProperty
并使用方法 ChrisF
建议,这样很容易添加到 TextBoxes
你想在你的申请中
Xaml:
<TextBox Name="textbox1" local:Extensions.DisableInsert="True" />
附属属性(property):
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;
}
}
关于wpf - 在 WPF TextBox 中禁用覆盖模式(按下 Insert 键时),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18344723/