首页 > 其他 > 详细

一个过滤Textbox输入的WPF Behavior

时间:2014-03-11 07:21:28      阅读:734      评论:0      收藏:0      [点我收藏+]
bubuko.com,布布扣
 1 public class TextBoxFilterBehavior : Behavior<TextBox>
 2     {
 3         public static readonly DependencyProperty LegalCharsProperty = DependencyProperty.RegisterAttached(
 4     "LegalChars", typeof(string), typeof(TextBoxFilterBehavior), new PropertyMetadata("1234567890abcdefghijklmnopqrstuvwxyz"));
 5 
 6         public static void SetLegalChars(DependencyObject element, string value)
 7         {
 8             element.SetValue(LegalCharsProperty, value);
 9         }
10 
11         public static string GetLegalChars(DependencyObject element)
12         {
13             return (string)element.GetValue(LegalCharsProperty);
14         }
15 
16         protected override void OnAttached()
17         {
18             base.OnAttached();
19             AssociatedObject.TextChanged += TextBoxTextChanged;
20         }
21 
22         protected override void OnDetaching()
23         {
24             base.OnDetaching();
25             AssociatedObject.TextChanged -= TextBoxTextChanged;
26         }
27 
28         private void FilterLegalChars()
29         {
30             var cursorLocation = AssociatedObject.SelectionStart;
31 
32             for (var i = AssociatedObject.Text.Length - 1; i >= 0; i--)
33             {
34                 var c = AssociatedObject.Text[i];
35                 var legalChars = GetLegalChars(this);
36                 if(legalChars.ToCharArray().ToList().Contains(c))
37                     continue;
38                 AssociatedObject.Text = AssociatedObject.Text.Remove(i, 1);
39                 cursorLocation--;
40             }
41 
42             AssociatedObject.SelectionStart = Math.Min(AssociatedObject.Text.Length, Math.Max(0, cursorLocation));
43         }
44 
45 
46         void TextBoxTextChanged(object sender, TextChangedEventArgs e)
47         {
48             FilterLegalChars();
49         }
50     }
bubuko.com,布布扣

用法:

bubuko.com,布布扣
1             <TextBox x:Name="txtPartNumber" HorizontalAlignment="Left" Height="25">
2                 <i:Interaction.Behaviors>
3                     <Helper:TextBoxFilterBehavior Helper:TextBoxFilterBehavior.LegalChars="1234567890-jJkKsS"/>
4                 </i:Interaction.Behaviors>
5             </TextBox>
bubuko.com,布布扣

只需要在LegalChars的属性里指定所有合法的字符即可.

一个过滤Textbox输入的WPF Behavior,布布扣,bubuko.com

一个过滤Textbox输入的WPF Behavior

原文:http://www.cnblogs.com/isharegallery/p/3591229.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!