【问题标题】:Disable overwrite mode in WPF TextBox (when pressing the Insert key)在 WPF 文本框中禁用覆盖模式(按下插入键时)
【发布时间】:2013-08-23 01:48:15
【问题描述】:

当用户在 WPF 文本框中按下 Insert 键时,控件会在插入和覆盖模式之间切换。通常,这是通过使用不同的光标(行与块)来可视化的,但这里不是这种情况。由于用户绝对无法知道覆盖模式处于活动状态,因此我只想完全禁用它。当用户按下 Insert 键时(或者可能有意或无意地激活了该模式),TextBox 应该保持在插入模式。

我可以添加一些按键事件处理程序并忽略所有此类事件,按下不带修饰符的插入键。这样就够了吗?你知道更好的选择吗?我的视图中有许多 TextBox 控件,我不想到处添加事件处理程序...

【问题讨论】:

    标签: wpf textbox overwrite


    【解决方案1】:

    为避免在任何地方添加处理程序,您可以将TextBox 子类化并添加一个PreviewKeyDown 事件处理程序,按照您的建议操作。

    在构造函数中:

    public MyTextBox()
    {
        this.KeyDown += PreviewKeyDownHandler;
    }
    
    
    private void PreviewKeyDownHandler(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Insert)
        {
            e.Handled = true;
        }
    }
    

    但是,这确实意味着您需要在 XAML 中将 TextBox 的所有用法替换为 MyTextBox,因此很遗憾,无论如何您都必须编辑所有视图。

    【讨论】:

      【解决方案2】:

      您可以创建一个AttachedProperty 并使用建议的ChrisF 方法,这样可以很容易地添加到您在应用程序中想要的TextBoxes

      Xaml:

         <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;
              }
          }
      

      【讨论】:

      • 谢谢,这很好用。也许我可以通过样式自动将附加属性添加到我的应用程序中的每个文本框?
      • 不需要检查e != null
      猜你喜欢
      • 2021-04-19
      • 1970-01-01
      • 1970-01-01
      • 2023-04-11
      • 2017-03-11
      • 2015-05-13
      • 2015-10-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多