MaskedTextBox.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Globalization;
  5. using System.Linq;
  6. using Avalonia.Input;
  7. using Avalonia.Input.Platform;
  8. using Avalonia.Interactivity;
  9. using Avalonia.Styling;
  10. namespace Avalonia.Controls
  11. {
  12. public class MaskedTextBox : TextBox, IStyleable
  13. {
  14. public static readonly StyledProperty<bool> AsciiOnlyProperty =
  15. AvaloniaProperty.Register<MaskedTextBox, bool>(nameof(AsciiOnly));
  16. public static readonly StyledProperty<CultureInfo?> CultureProperty =
  17. AvaloniaProperty.Register<MaskedTextBox, CultureInfo?>(nameof(Culture), CultureInfo.CurrentCulture);
  18. public static readonly StyledProperty<bool> HidePromptOnLeaveProperty =
  19. AvaloniaProperty.Register<MaskedTextBox, bool>(nameof(HidePromptOnLeave));
  20. public static readonly DirectProperty<MaskedTextBox, bool?> MaskCompletedProperty =
  21. AvaloniaProperty.RegisterDirect<MaskedTextBox, bool?>(nameof(MaskCompleted), o => o.MaskCompleted);
  22. public static readonly DirectProperty<MaskedTextBox, bool?> MaskFullProperty =
  23. AvaloniaProperty.RegisterDirect<MaskedTextBox, bool?>(nameof(MaskFull), o => o.MaskFull);
  24. public static readonly StyledProperty<string?> MaskProperty =
  25. AvaloniaProperty.Register<MaskedTextBox, string?>(nameof(Mask), string.Empty);
  26. public static readonly StyledProperty<char> PromptCharProperty =
  27. AvaloniaProperty.Register<MaskedTextBox, char>(nameof(PromptChar), '_', coerce: CoercePromptChar);
  28. public static readonly StyledProperty<bool> ResetOnPromptProperty =
  29. AvaloniaProperty.Register<MaskedTextBox, bool>(nameof(ResetOnPrompt), true);
  30. public static readonly StyledProperty<bool> ResetOnSpaceProperty =
  31. AvaloniaProperty.Register<MaskedTextBox, bool>(nameof(ResetOnSpace), true);
  32. private bool _ignoreTextChanges;
  33. static MaskedTextBox()
  34. {
  35. PasswordCharProperty.OverrideMetadata<MaskedTextBox>(new('\0', coerce: CoercePasswordChar));
  36. }
  37. private static char CoercePasswordChar(AvaloniaObject sender, char baseValue)
  38. {
  39. if (!MaskedTextProvider.IsValidPasswordChar(baseValue))
  40. {
  41. throw new ArgumentException($"'{baseValue}' is not a valid value for PasswordChar.");
  42. }
  43. var textbox = (MaskedTextBox)sender;
  44. if (textbox.MaskProvider is { } maskProvider && baseValue == maskProvider.PromptChar)
  45. {
  46. // Prompt and password chars must be different.
  47. throw new InvalidOperationException("PasswordChar and PromptChar values cannot be the same.");
  48. }
  49. return baseValue;
  50. }
  51. private static char CoercePromptChar(AvaloniaObject sender, char baseValue)
  52. {
  53. if (!MaskedTextProvider.IsValidInputChar(baseValue))
  54. {
  55. throw new ArgumentException($"'{baseValue}' is not a valid value for PromptChar.");
  56. }
  57. if (baseValue == sender.GetValue(PasswordCharProperty))
  58. {
  59. throw new InvalidOperationException("PasswordChar and PromptChar values cannot be the same.");
  60. }
  61. return baseValue;
  62. }
  63. public MaskedTextBox() { }
  64. /// <summary>
  65. /// Constructs the MaskedTextBox with the specified MaskedTextProvider object.
  66. /// </summary>
  67. [System.Diagnostics.CodeAnalysis.SuppressMessage("AvaloniaProperty",
  68. "AVP1012:An AvaloniaObject should use SetCurrentValue when assigning its own StyledProperty or AttachedProperty values",
  69. Justification = "These values are being explicitly provided by a constructor parameter.")]
  70. public MaskedTextBox(MaskedTextProvider maskedTextProvider)
  71. {
  72. if (maskedTextProvider == null)
  73. {
  74. throw new ArgumentNullException(nameof(maskedTextProvider));
  75. }
  76. AsciiOnly = maskedTextProvider.AsciiOnly;
  77. Culture = maskedTextProvider.Culture;
  78. Mask = maskedTextProvider.Mask;
  79. PasswordChar = maskedTextProvider.PasswordChar;
  80. PromptChar = maskedTextProvider.PromptChar;
  81. }
  82. /// <summary>
  83. /// Gets or sets a value indicating if the masked text box is restricted to accept only ASCII characters.
  84. /// Default value is false.
  85. /// </summary>
  86. public bool AsciiOnly
  87. {
  88. get => GetValue(AsciiOnlyProperty);
  89. set => SetValue(AsciiOnlyProperty, value);
  90. }
  91. /// <summary>
  92. /// Gets or sets the culture information associated with the masked text box.
  93. /// </summary>
  94. public CultureInfo? Culture
  95. {
  96. get => GetValue(CultureProperty);
  97. set => SetValue(CultureProperty, value);
  98. }
  99. /// <summary>
  100. /// Gets or sets a value indicating if the prompt character is hidden when the masked text box loses focus.
  101. /// </summary>
  102. public bool HidePromptOnLeave
  103. {
  104. get => GetValue(HidePromptOnLeaveProperty);
  105. set => SetValue(HidePromptOnLeaveProperty, value);
  106. }
  107. /// <summary>
  108. /// Gets or sets the mask to apply to the TextBox.
  109. /// </summary>
  110. public string? Mask
  111. {
  112. get => GetValue(MaskProperty);
  113. set => SetValue(MaskProperty, value);
  114. }
  115. /// <summary>
  116. /// Specifies whether the test string required input positions, as specified by the mask, have
  117. /// all been assigned.
  118. /// </summary>
  119. public bool? MaskCompleted
  120. {
  121. get => MaskProvider?.MaskCompleted;
  122. }
  123. /// <summary>
  124. /// Specifies whether all inputs (required and optional) have been provided into the mask successfully.
  125. /// </summary>
  126. public bool? MaskFull
  127. {
  128. get => MaskProvider?.MaskFull;
  129. }
  130. /// <summary>
  131. /// Gets the MaskTextProvider for the specified Mask.
  132. /// </summary>
  133. public MaskedTextProvider? MaskProvider { get; private set; }
  134. /// <summary>
  135. /// Gets or sets the character used to represent the absence of user input in MaskedTextBox.
  136. /// </summary>
  137. public char PromptChar
  138. {
  139. get => GetValue(PromptCharProperty);
  140. set => SetValue(PromptCharProperty, value);
  141. }
  142. /// <summary>
  143. /// Gets or sets a value indicating if selected characters should be reset when the prompt character is pressed.
  144. /// </summary>
  145. public bool ResetOnPrompt
  146. {
  147. get => GetValue(ResetOnPromptProperty);
  148. set => SetValue(ResetOnPromptProperty, value);
  149. }
  150. /// <summary>
  151. /// Gets or sets a value indicating if selected characters should be reset when the space character is pressed.
  152. /// </summary>
  153. public bool ResetOnSpace
  154. {
  155. get => GetValue(ResetOnSpaceProperty);
  156. set => SetValue(ResetOnSpaceProperty, value);
  157. }
  158. Type IStyleable.StyleKey => typeof(TextBox);
  159. /// <inheritdoc />
  160. protected override void OnGotFocus(GotFocusEventArgs e)
  161. {
  162. if (HidePromptOnLeave == true && MaskProvider != null)
  163. {
  164. SetCurrentValue(TextProperty, MaskProvider.ToDisplayString());
  165. }
  166. base.OnGotFocus(e);
  167. }
  168. /// <inheritdoc />
  169. protected override async void OnKeyDown(KeyEventArgs e)
  170. {
  171. if (MaskProvider == null)
  172. {
  173. base.OnKeyDown(e);
  174. return;
  175. }
  176. var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>();
  177. bool Match(List<KeyGesture> gestures) => gestures.Any(g => g.Matches(e));
  178. if (keymap is not null && Match(keymap.Paste))
  179. {
  180. var clipboard = TopLevel.GetTopLevel(this)?.Clipboard;
  181. if (clipboard is null)
  182. return;
  183. var text = await clipboard.GetTextAsync();
  184. if (text == null)
  185. return;
  186. foreach (var item in text)
  187. {
  188. var index = GetNextCharacterPosition(CaretIndex);
  189. if (MaskProvider.InsertAt(item, index))
  190. {
  191. SetCurrentValue(CaretIndexProperty, ++index);
  192. }
  193. }
  194. SetCurrentValue(TextProperty, MaskProvider.ToDisplayString());
  195. e.Handled = true;
  196. return;
  197. }
  198. if (e.Key != Key.Back)
  199. {
  200. base.OnKeyDown(e);
  201. }
  202. switch (e.Key)
  203. {
  204. case Key.Delete:
  205. if (CaretIndex < Text?.Length)
  206. {
  207. if (MaskProvider.RemoveAt(CaretIndex))
  208. {
  209. RefreshText(MaskProvider, CaretIndex);
  210. }
  211. e.Handled = true;
  212. }
  213. break;
  214. case Key.Space:
  215. if (!MaskProvider.ResetOnSpace || string.IsNullOrEmpty(SelectedText))
  216. {
  217. if (MaskProvider.InsertAt(" ", CaretIndex))
  218. {
  219. RefreshText(MaskProvider, CaretIndex);
  220. }
  221. }
  222. e.Handled = true;
  223. break;
  224. case Key.Back:
  225. if (CaretIndex > 0)
  226. {
  227. MaskProvider.RemoveAt(CaretIndex - 1);
  228. }
  229. RefreshText(MaskProvider, CaretIndex - 1);
  230. e.Handled = true;
  231. break;
  232. }
  233. }
  234. /// <inheritdoc />
  235. protected override void OnLostFocus(RoutedEventArgs e)
  236. {
  237. if (HidePromptOnLeave && MaskProvider != null)
  238. {
  239. SetCurrentValue(TextProperty, MaskProvider.ToString(!HidePromptOnLeave, true));
  240. }
  241. base.OnLostFocus(e);
  242. }
  243. /// <inheritdoc />
  244. protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
  245. {
  246. void UpdateMaskProvider()
  247. {
  248. MaskProvider = new MaskedTextProvider(Mask!, Culture, true, PromptChar, PasswordChar, AsciiOnly) { ResetOnSpace = ResetOnSpace, ResetOnPrompt = ResetOnPrompt };
  249. if (Text != null)
  250. {
  251. MaskProvider.Set(Text);
  252. }
  253. RefreshText(MaskProvider, 0);
  254. }
  255. if (change.Property == TextProperty && MaskProvider != null && _ignoreTextChanges == false)
  256. {
  257. if (string.IsNullOrEmpty(Text))
  258. {
  259. MaskProvider.Clear();
  260. RefreshText(MaskProvider, CaretIndex);
  261. base.OnPropertyChanged(change);
  262. return;
  263. }
  264. MaskProvider.Set(Text);
  265. RefreshText(MaskProvider, CaretIndex);
  266. }
  267. else if (change.Property == MaskProperty)
  268. {
  269. UpdateMaskProvider();
  270. if (!string.IsNullOrEmpty(Mask))
  271. {
  272. foreach (var c in Mask!)
  273. {
  274. if (!MaskedTextProvider.IsValidMaskChar(c))
  275. {
  276. throw new ArgumentException("Specified mask contains characters that are not valid.");
  277. }
  278. }
  279. }
  280. }
  281. else if (change.Property == PasswordCharProperty)
  282. {
  283. if (MaskProvider != null && MaskProvider.PasswordChar != PasswordChar)
  284. {
  285. UpdateMaskProvider();
  286. }
  287. }
  288. else if (change.Property == PromptCharProperty)
  289. {
  290. if (MaskProvider != null && MaskProvider.PromptChar != PromptChar)
  291. {
  292. UpdateMaskProvider();
  293. }
  294. }
  295. else if (change.Property == ResetOnPromptProperty)
  296. {
  297. if (MaskProvider != null && change.GetNewValue<bool>() is { } newValue)
  298. {
  299. MaskProvider.ResetOnPrompt = newValue;
  300. }
  301. }
  302. else if (change.Property == ResetOnSpaceProperty)
  303. {
  304. if (MaskProvider != null && change.GetNewValue<bool>() is { } newValue)
  305. {
  306. MaskProvider.ResetOnSpace = newValue;
  307. }
  308. }
  309. else if (change.Property == AsciiOnlyProperty && MaskProvider != null && MaskProvider.AsciiOnly != AsciiOnly
  310. || change.Property == CultureProperty && MaskProvider != null && !MaskProvider.Culture.Equals(Culture))
  311. {
  312. UpdateMaskProvider();
  313. }
  314. base.OnPropertyChanged(change);
  315. }
  316. /// <inheritdoc />
  317. protected override void OnTextInput(TextInputEventArgs e)
  318. {
  319. _ignoreTextChanges = true;
  320. try
  321. {
  322. if (IsReadOnly)
  323. {
  324. e.Handled = true;
  325. base.OnTextInput(e);
  326. return;
  327. }
  328. if (MaskProvider == null)
  329. {
  330. base.OnTextInput(e);
  331. return;
  332. }
  333. if ((MaskProvider.ResetOnSpace && e.Text == " " || MaskProvider.ResetOnPrompt && e.Text == MaskProvider.PromptChar.ToString()) && !string.IsNullOrEmpty(SelectedText))
  334. {
  335. if (SelectionStart > SelectionEnd ? MaskProvider.RemoveAt(SelectionEnd, SelectionStart - 1) : MaskProvider.RemoveAt(SelectionStart, SelectionEnd - 1))
  336. {
  337. SelectedText = string.Empty;
  338. }
  339. }
  340. if (CaretIndex < Text?.Length)
  341. {
  342. SetCurrentValue(CaretIndexProperty, GetNextCharacterPosition(CaretIndex));
  343. if (MaskProvider.InsertAt(e.Text!, CaretIndex))
  344. {
  345. CaretIndex++;
  346. }
  347. var nextPos = GetNextCharacterPosition(CaretIndex);
  348. if (nextPos != 0 && CaretIndex != Text.Length)
  349. {
  350. SetCurrentValue(CaretIndexProperty, nextPos);
  351. }
  352. }
  353. RefreshText(MaskProvider, CaretIndex);
  354. e.Handled = true;
  355. base.OnTextInput(e);
  356. }
  357. finally
  358. {
  359. _ignoreTextChanges = false;
  360. }
  361. }
  362. private int GetNextCharacterPosition(int startPosition)
  363. {
  364. if (MaskProvider != null)
  365. {
  366. var position = MaskProvider.FindEditPositionFrom(startPosition, true);
  367. if (CaretIndex != -1)
  368. {
  369. return position;
  370. }
  371. }
  372. return startPosition;
  373. }
  374. private void RefreshText(MaskedTextProvider? provider, int position)
  375. {
  376. if (provider != null)
  377. {
  378. SetCurrentValue(TextProperty, provider.ToDisplayString());
  379. SetCurrentValue(CaretIndexProperty, position);
  380. }
  381. }
  382. }
  383. }