using System;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;
public class FilterTextBoxBehavior : Behavior<TextBox>
{
public readonly static DependencyProperty AllowAlphaCharactersProperty = DependencyProperty.Register("AllowAlphaCharacters", typeof(bool), typeof(FilterTextBoxBehavior), new PropertyMetadata(true));
public bool AllowAlphaCharacters
{
get { return (bool)GetValue(AllowAlphaCharactersProperty); }
set { SetValue(AllowAlphaCharactersProperty, value); }
}
public readonly static DependencyProperty AllowNumericCharactersProperty = DependencyProperty.Register("AllowNumericCharacters", typeof(bool), typeof(FilterTextBoxBehavior), new PropertyMetadata(true));
public bool AllowNumericCharacters
{
get { return (bool)GetValue(AllowNumericCharactersProperty); }
set { SetValue(AllowNumericCharactersProperty, value); }
}
public readonly static DependencyProperty AllowSpecialCharactersProperty = DependencyProperty.Register("AllowSpecialCharacters", typeof(bool), typeof(FilterTextBoxBehavior), new PropertyMetadata(true));
public bool AllowSpecialCharacters
{
get { return (bool)GetValue(AllowSpecialCharactersProperty); }
set { SetValue(AllowSpecialCharactersProperty, value); }
}
public readonly static DependencyProperty DoNotFilterProperty = DependencyProperty.Register("DoNotFilter", typeof(string), typeof(FilterTextBoxBehavior), new PropertyMetadata(default(string)));
public string DoNotFilter
{
get { return (string)GetValue(DoNotFilterProperty); }
set { SetValue(DoNotFilterProperty, value); }
}
protected override void OnAttached()
{
base.OnAttached();
if (AssociatedObject == null) { return; }
FilterAssociatedObject();
AssociatedObject.TextChanged += OnTextChanged;
}
protected override void OnDetaching()
{
base.OnDetaching();
if (AssociatedObject == null) { return; }
FilterAssociatedObject();
AssociatedObject.TextChanged -= OnTextChanged;
}
private void OnTextChanged(object sender, TextChangedEventArgs e) { FilterAssociatedObject(); }
private void FilterAssociatedObject()
{
int cursorLocation = AssociatedObject.SelectionStart;
for (int i = AssociatedObject.Text.Length - 1; i >= 0; i--)
{
char c = AssociatedObject.Text[i];
if (ValidChar(c)) { continue; }
AssociatedObject.Text = AssociatedObject.Text.Remove(i, 1);
cursorLocation--;
}
AssociatedObject.SelectionStart = Math.Min(AssociatedObject.Text.Length, Math.Max(0, cursorLocation));
}
private bool ValidChar(char c)
{
if (!string.IsNullOrEmpty(DoNotFilter) && DoNotFilter.Contains(c)) { return true; }
if (!AllowAlphaCharacters && char.IsLetter(c)) { return false; }
if (!AllowNumericCharacters && char.IsNumber(c)) { return false; }
if (!AllowSpecialCharacters && Regex.IsMatch(c.ToString(), @"[\W|_]")) { return false; }
return true;
}
}