The advanced version of WPF MVVM additional properties

Original: WPF MVVM advanced version of additional properties

One of WPF properties to achieve additional properties of the text box contents in this paper verification

 


  
  
  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. }

Namespace references

  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"/>

 
 

 

Guess you like

Origin www.cnblogs.com/lonelyxmas/p/12075813.html