wpf - 在 WPF TextBox 中禁用覆盖模式(按下 Insert 键时)

标签 wpf textbox overwrite

当用户在 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/

相关文章:

wpf - 当我提供默认值时,为什么依赖属性实现会使我的应用程序崩溃?

wpf - 动态改变 FocusManager.FocusedElement

javascript - 只需单击一个按钮即可启用必填字段验证

tar - 创建 tar 存档时如何避免破坏文件

wpf - WPF 中的命令绑定(bind)内存泄漏

c# - MVVM Light Toolkit 的文档/示例?

java - 文本框类在 Java 中只接受整数

c# - 在 DWM 玻璃下使用 TextBox 进行测试

php - 使用 PHP 制作点击计数器

batch-file - 如何批量覆盖已有文件?