Created
August 29, 2018 12:00
-
-
Save PurpleGray/981daf56bb6a5002aff8699847cfca77 to your computer and use it in GitHub Desktop.
FilteredTextBox
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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