conganguo 2019-12-21
WPF 特性之一 附加属性 在本文里实现文本框内容的验证
public class TextBoxHelper:DependencyObject { public static bool GetisOnlyNumber(DependencyObject obj) { return (bool)obj.GetValue(isOnlyNumberProperty); } public static void SetisOnlyNumber(DependencyObject obj, bool value) { obj.SetValue(isOnlyNumberProperty, value); } // Using a DependencyProperty as the backing store for isOnlyNumber. This enables animation, styling, binding, etc... public static readonly DependencyProperty isOnlyNumberProperty = DependencyProperty.RegisterAttached("isOnlyNumber", typeof(bool), typeof(TextBoxHelper), new PropertyMetadata(false,OnIsOnlyNumberChange)); private static void OnIsOnlyNumberChange(DependencyObject d, DependencyPropertyChangedEventArgs e) { var text = d as TextBox; if ((bool)e.NewValue) { text.PreviewTextInput += text_PreviewTextInput; }else{ text.PreviewTextInput -= text_PreviewTextInput; } } static void text_PreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e) { e.Handled = IsNotNumber(e.Text); } private static bool IsNotNumber(string content) { Regex regex = new Regex("[^0-9]"); return regex.IsMatch(content); } }
引用命名空间
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"/>
<!-- Row 0 -->. <TextBlock Text="{Binding Department, ElementName = window}". <!-- Row 1 -->. <TextB
<ListBox Name="sideMenu" SelectedIndex="{Binding MenuSelectedIndex}" ItemsSource="{Binding MenuList}