码迷,mamicode.com
首页 > Windows程序 > 详细

WPF 高级篇 MVVM 附加属性

时间:2019-12-21 10:19:17      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:content   vertica   space   属性   keyword   textinput   实现   code   height   

原文: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 附加属性

标签:content   vertica   space   属性   keyword   textinput   实现   code   height   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!