WPF 高级篇 MVVM 附加属性
原文:WPF 高级篇 MVVM 附加属性
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"/>
相关推荐
88473166 2020-05-14
89427412 2020-05-06
conganguo 2020-05-06
86523296 2020-04-22
89427412 2020-02-13
conganguo 2020-01-18
檀木雨林 2020-01-10
86523296 2020-01-08
<ListBox Name="sideMenu" SelectedIndex="{Binding MenuSelectedIndex}" ItemsSource="{Binding MenuList}
88473166 2020-01-08
yw00yw 2020-01-03
xcolin 2020-01-03
檀木雨林 2019-12-14
conganguo 2019-12-14
xcolin 2019-12-14
yw00yw 2019-12-14
maokaijiang 2020-06-14
<!-- Row 0 -->. <TextBlock Text="{Binding Department, ElementName = window}". <!-- Row 1 -->. <TextB
Laxcus大数据技术 2020-05-27
wndong 2020-05-20