【问题标题】:How to restrict numeric value paste in WPF textbox如何限制 WPF 文本框中的数值粘贴
【发布时间】:2011-07-11 08:09:19
【问题描述】:

我的 WPF 文本框控件有问题。我只想在其中输入数值。简单的解决方案是在其PreviewKeyDown 事件中调用函数isNumeric(),但问题是如果我将一个数字复制到剪贴板然后将其粘贴到文本框中,则不会调用检查代码。如何处理粘贴的数字?

【问题讨论】:

标签: c# wpf textbox


【解决方案1】:

请参阅DataObject.AddPastingHandler 或参阅this question,了解更通用的问题解决方案。

【讨论】:

    【解决方案2】:

    我使用了一个派生自 TextBox 的自己的类。在构造函数中,我使用 ApplicationCommands.Paste 创建了一个 CommandBinding()。在“CanPaste”方法中,我检查粘贴的文本(无法显示示例代码,因为它来自工作)。

    纸浆

    【讨论】:

      【解决方案3】:

      如果您使用 cinch,只需使用这个出色框架中的附加行为。 但如果不是,你可以从这个链接中得到启发,他(cinch 的作者)正在通过附加行为解决这个问题:http://www.codeproject.com/KB/WPF/CinchII.aspx#NumericAtt

      编辑: 魔法就在这里,他“禁用”粘贴

              TextBox tb = sender as TextBox;
              if (tb == null)
                  return;
      
              tb.PreviewTextInput -= tbb_PreviewTextInput;
              DataObject.RemovePastingHandler(tb, OnClipboardPaste);
      
              bool b = ((e.NewValue != null && e.NewValue.GetType() == typeof(bool))) ?
                  (bool)e.NewValue : false;
              if (b)
              {
                  tb.PreviewTextInput += tbb_PreviewTextInput;
                  DataObject.AddPastingHandler(tb, OnClipboardPaste);
              }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-03-04
        • 1970-01-01
        • 1970-01-01
        • 2017-03-04
        • 1970-01-01
        • 1970-01-01
        • 2015-05-20
        • 1970-01-01
        相关资源
        最近更新 更多