首页 > Windows开发 > 详细

WPF 高级篇 MVVM 附加属性

时间:2019-12-21 10:07:10      阅读:117      评论:0      收藏:0      [点我收藏+]
原文:WPF 高级篇 MVVM 附加属性

WPF 特性之一 附加属性 在本文里实现文本框内容的验证

技术分享图片

 

  1. public class TextBoxHelper:DependencyObject
  2. {
  3. public static bool GetisOnlyNumber(DependencyObject obj)
  4. {
  5. return (bool)obj.GetValue(isOnlyNumberProperty);
  6. }
  7. public static void SetisOnlyNumber(DependencyObject obj, bool value)
  8. {
  9. obj.SetValue(isOnlyNumberProperty, value);
  10. }
  11. // Using a DependencyProperty as the backing store for isOnlyNumber. This enables animation, styling, binding, etc...
  12. public static readonly DependencyProperty isOnlyNumberProperty =
  13. DependencyProperty.RegisterAttached("isOnlyNumber", typeof(bool), typeof(TextBoxHelper), new PropertyMetadata(false,OnIsOnlyNumberChange));
  14. private static void OnIsOnlyNumberChange(DependencyObject d, DependencyPropertyChangedEventArgs e)
  15. {
  16. var text = d as TextBox;
  17. if ((bool)e.NewValue)
  18. {
  19. text.PreviewTextInput += text_PreviewTextInput;
  20. }else{
  21. text.PreviewTextInput -= text_PreviewTextInput;
  22. }
  23. }
  24. static void text_PreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
  25. {
  26. e.Handled = IsNotNumber(e.Text);
  27. }
  28. private static bool IsNotNumber(string content)
  29. {
  30. Regex regex = new Regex("[^0-9]");
  31. return regex.IsMatch(content);
  32. }
  33. }

引用命名空间

  xmlns:bhx ="clr-namespace:WPF.Behaviors"
        <TextBox bhx:TextBoxHelper.isOnlyNumber="True" HorizontalAlignment="Left" Height="23" Margin="10,131,0,0" TextWrapping="Wrap" Text="{Binding CurrentBook.Pages}" VerticalAlignment="Top" Width="120"/>

 

WPF 高级篇 MVVM 附加属性

原文:https://www.cnblogs.com/lonelyxmas/p/12075813.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!