WPF 高级篇 MVVM 附加属性

原文:WPF 高级篇 MVVM 附加属性

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

WPF 高级篇 MVVM 附加属性


  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"/>
上一篇:单源最短路径Dijkstra算法,多源最短路径Floyd算法


下一篇:最短路径——Dijkstra算法以及二叉堆优化(含证明)