Skip to content

Instantly share code, notes, and snippets.

@PurpleGray
Created August 29, 2018 12:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PurpleGray/981daf56bb6a5002aff8699847cfca77 to your computer and use it in GitHub Desktop.
Save PurpleGray/981daf56bb6a5002aff8699847cfca77 to your computer and use it in GitHub Desktop.
FilteredTextBox
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using System.Reflection;
namespace CosmoPlanner.Infrastructure.Controls
{
public class FilteredTextBox : TextBox
{
public static readonly AvaloniaProperty<string> MaskPatternProperty =
AvaloniaProperty.Register<FilteredTextBox, string>("MaskPattern", string.Empty);
/// <summary>
/// Indicate the type of the filter to apply.
/// </summary>
public string MaskPattern
{
get { return GetValue(MaskPatternProperty); }
set { SetValue(MaskPatternProperty, value); }
}
protected override void OnTextInput(TextInputEventArgs e)
{
if (!e.Handled)
{
base.OnTextInput(e);
e.Handled = true;
if (CaretIndex > MaskPattern.Length)
{
SetText(Text.Remove(Text.Length - e.Text.Length, e.Text.Length));
return;
}
var pattern = MaskPattern[CaretIndex - 1];
if (pattern == '0' && e.Text.Length == 1 && char.IsDigit(e.Text[0]))
{
return;
}
if (e.Text.Length == 1 && e.Text[0] == pattern)
{
return;
}
SetText(Text.Remove(Text.Length - e.Text.Length, e.Text.Length));
return;
}
}
private void SetText(string text)
{
var methodInfo = typeof(TextBox).GetMethod("SetTextInternal",
BindingFlags.NonPublic | BindingFlags.Instance);
methodInfo.Invoke(this, new object[] { text });
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment