[.NET] 在WPF中实现TextBox只能输入数字

2021-09-29 23:13

阅读:1067

标签:如题,实现此功能的方法有很多,如果使用的是MVVM的开发模式,该如何实现此功能? 很简单,为TextBox新建一个附加属性,就可以完美的解决此问题。 新建一个附件属性 IsOnlyAcceptFigure ,并为其添加属性回调函数即可。 代码如下: namespace WPF.Validation { public class TextBoxOnlyAcceptFigureBehavior { public static readonly DependencyProperty IsOnlyAcceptFigureProperty = DependencyProperty.RegisterAttached("IsOnlyAcceptFigure", typeof (bool), typeof (TextBoxOnlyAcceptFigureBehavior), new UIPropertyMetadata(false, OnBindedPasswordChanged)); public static bool GetIsOnlyAcceptFigure(DependencyObject obj) { return (bool) obj.GetValue(IsOnlyAcceptFigureProperty); } public static void SetIsOnlyAcceptFigure(DependencyObject obj, bool value) { obj.SetValue(IsOnlyAcceptFigureProperty, value); } private static void OnBindedPasswordChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e) { var textBox = obj as TextBox; if (textBox == null) return; if ((bool) e.NewValue) { textBox.PreviewTextInput += textBox_PreviewTextInput; textBox.PreviewKeyDown += textBox_PreviewKeyDown; DataObject.AddPastingHandler(textBox, textBox_Pasting); } else { textBox.PreviewTextInput -= textBox_PreviewTextInput; textBox.PreviewKeyDown -= textBox_PreviewKeyDown; DataObject.RemovePastingHandler(textBox, textBox_Pasting); } } private static void textBox_Pasting(object sender, DataObjectPastingEventArgs e) { if (e.DataObject.GetDataPresent(typeof (string))) { var text = (string) e.DataObject.GetData(typeof (string)); if (!IsNumberic(text)) { e.CancelCommand(); } } else { e.CancelCommand(); } } private static void textBox_PreviewKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Space) e.Handled = true; } private static void textBox_PreviewTextInput(object sender, TextCompositionEventArgs e) { e.Handled = !IsNumberic(e.Text); } public static bool IsNumberic(string _string) { if (string.IsNullOrEmpty(_string)) return false; return _string.All(char.IsDigit); } } } 如何调用: PS:验证输入的代码来自于网络,再次谢谢网友的分享。 祝大家生活愉快!  [.NET] 在WPF中实现TextBox只能输入数字标签:原文地址:http://www.cnblogs.com/sela/p/4777506.html


评论


亲,登录后才可以留言!