首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

一个过滤Textbox输入的WPF Behavior

Posted on 2014-03-10 10:15  Alex Geng  阅读(522)  评论(0)    收藏  举报
 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     }

用法:

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>

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