WPF 高级篇 MVVM 附加属性
Posted lonelyxmas
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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"/>
以上是关于WPF 高级篇 MVVM 附加属性的主要内容,如果未能解决你的问题,请参考以下文章
WPF 利用附加属性创建FreezableCollection集合和反射实现控件参数以MVVM模式传递