TextBox自定义Mac输入框类

时间:2023-03-08 18:42:45
using System.Windows.Controls;

namespace test
{
public class MacTextBox : TextBox
{
private string _lastText = "";
protected override void OnTextChanged(TextChangedEventArgs e)
{
string text = Text;
if (PrepareText(ref text))
{
Text = text;
_lastText = Text;
}
else
{
Text = _lastText;
} if (Text.Length > )
CaretIndex = Text[Text.Length - ] == '-' ? Text.Length - : Text.Length;
e.Handled = true;
base.OnTextChanged(e);
} private bool PrepareText(ref string text)
{
if (text.Length > )
return false; text = text.ToUpper();
string t = ""; foreach (char c in text)
{
if ((c >= && c <= ) ||
(c >= && c <= ))
{
t += c;
if (t.Length == ||
t.Length == ||
t.Length == ||
t.Length == ||
t.Length == )
{
t += "-";
}
}
else if (c != ':' && c != '-')
{
return false;
}
} if (t.EndsWith("-"))
t = t.Remove(t.Length - ); if (t.Length > )
return false;
text = t;
return true;
}
}
}