MaskedTextBoxTests.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047
  1. using System;
  2. using System.Globalization;
  3. using System.Reactive.Linq;
  4. using System.Threading.Tasks;
  5. using Avalonia.Controls.Presenters;
  6. using Avalonia.Controls.Primitives;
  7. using Avalonia.Controls.Templates;
  8. using Avalonia.Data;
  9. using Avalonia.Headless;
  10. using Avalonia.Input;
  11. using Avalonia.Input.Platform;
  12. using Avalonia.Layout;
  13. using Avalonia.Media;
  14. using Avalonia.Platform;
  15. using Avalonia.UnitTests;
  16. using Moq;
  17. using Xunit;
  18. namespace Avalonia.Controls.UnitTests
  19. {
  20. public class MaskedTextBoxTests : ScopedTestBase
  21. {
  22. [Fact]
  23. public void Opening_Context_Menu_Does_not_Lose_Selection()
  24. {
  25. using (Start(FocusServices))
  26. {
  27. var target1 = new MaskedTextBox
  28. {
  29. Template = CreateTemplate(),
  30. Text = "1234",
  31. ContextMenu = new TestContextMenu()
  32. };
  33. var target2 = new MaskedTextBox
  34. {
  35. Template = CreateTemplate(),
  36. Text = "5678"
  37. };
  38. var sp = new StackPanel();
  39. sp.Children.Add(target1);
  40. sp.Children.Add(target2);
  41. target1.ApplyTemplate();
  42. target2.ApplyTemplate();
  43. var root = new TestRoot() { Child = sp };
  44. target1.SelectionStart = 0;
  45. target1.SelectionEnd = 3;
  46. target1.Focus();
  47. Assert.False(target2.IsFocused);
  48. Assert.True(target1.IsFocused);
  49. target2.Focus();
  50. Assert.Equal("123", target1.SelectedText);
  51. }
  52. }
  53. [Fact]
  54. public void Opening_Context_Flyout_Does_not_Lose_Selection()
  55. {
  56. using (Start(FocusServices))
  57. {
  58. var target1 = new MaskedTextBox
  59. {
  60. Template = CreateTemplate(),
  61. Text = "1234",
  62. ContextFlyout = new MenuFlyout
  63. {
  64. Items =
  65. {
  66. new MenuItem { Header = "Item 1" },
  67. new MenuItem {Header = "Item 2" },
  68. new MenuItem {Header = "Item 3" }
  69. }
  70. }
  71. };
  72. target1.ApplyTemplate();
  73. var root = new TestRoot() { Child = target1 };
  74. target1.SelectionStart = 0;
  75. target1.SelectionEnd = 3;
  76. target1.Focus();
  77. Assert.True(target1.IsFocused);
  78. target1.ContextFlyout.ShowAt(target1);
  79. Assert.Equal("123", target1.SelectedText);
  80. }
  81. }
  82. [Fact]
  83. public void DefaultBindingMode_Should_Be_TwoWay()
  84. {
  85. Assert.Equal(
  86. BindingMode.TwoWay,
  87. TextBox.TextProperty.GetMetadata(typeof(MaskedTextBox)).DefaultBindingMode);
  88. }
  89. [Fact]
  90. public void CaretIndex_Can_Moved_To_Position_After_The_End_Of_Text_With_Arrow_Key()
  91. {
  92. using (Start())
  93. {
  94. var target = new MaskedTextBox
  95. {
  96. Template = CreateTemplate(),
  97. Text = "1234"
  98. };
  99. target.ApplyTemplate();
  100. target.CaretIndex = 3;
  101. target.Measure(Size.Infinity);
  102. RaiseKeyEvent(target, Key.Right, 0);
  103. Assert.Equal(4, target.CaretIndex);
  104. }
  105. }
  106. [Fact]
  107. public void Press_Ctrl_A_Select_All_Text()
  108. {
  109. using (Start())
  110. {
  111. var target = new MaskedTextBox
  112. {
  113. Template = CreateTemplate(),
  114. Text = "1234"
  115. };
  116. target.ApplyTemplate();
  117. RaiseKeyEvent(target, Key.A, KeyModifiers.Control);
  118. Assert.Equal(0, target.SelectionStart);
  119. Assert.Equal(4, target.SelectionEnd);
  120. }
  121. }
  122. [Fact]
  123. public void Press_Ctrl_A_Select_All_Null_Text()
  124. {
  125. using (Start())
  126. {
  127. var target = new MaskedTextBox
  128. {
  129. Template = CreateTemplate()
  130. };
  131. RaiseKeyEvent(target, Key.A, KeyModifiers.Control);
  132. Assert.Equal(0, target.SelectionStart);
  133. Assert.Equal(0, target.SelectionEnd);
  134. }
  135. }
  136. [Fact]
  137. public void Press_Ctrl_Z_Will_Not_Modify_Text()
  138. {
  139. using (Start())
  140. {
  141. var target = new MaskedTextBox
  142. {
  143. Template = CreateTemplate(),
  144. Text = "1234"
  145. };
  146. RaiseKeyEvent(target, Key.Z, KeyModifiers.Control);
  147. Assert.Equal("1234", target.Text);
  148. }
  149. }
  150. [Fact]
  151. public void Control_Backspace_Should_Remove_The_Word_Before_The_Caret_If_There_Is_No_Selection()
  152. {
  153. using (Start())
  154. {
  155. MaskedTextBox textBox = new MaskedTextBox
  156. {
  157. Template = CreateTemplate(),
  158. Text = "First Second Third Fourth",
  159. CaretIndex = 5
  160. };
  161. textBox.ApplyTemplate();
  162. // (First| Second Third Fourth)
  163. RaiseKeyEvent(textBox, Key.Back, KeyModifiers.Control);
  164. Assert.Equal(" Second Third Fourth", textBox.Text);
  165. // ( Second |Third Fourth)
  166. textBox.CaretIndex = 8;
  167. RaiseKeyEvent(textBox, Key.Back, KeyModifiers.Control);
  168. Assert.Equal(" Third Fourth", textBox.Text);
  169. // ( Thi|rd Fourth)
  170. textBox.CaretIndex = 4;
  171. RaiseKeyEvent(textBox, Key.Back, KeyModifiers.Control);
  172. Assert.Equal(" rd Fourth", textBox.Text);
  173. // ( rd F[ou]rth)
  174. textBox.SelectionStart = 5;
  175. textBox.SelectionEnd = 7;
  176. RaiseKeyEvent(textBox, Key.Back, KeyModifiers.Control);
  177. Assert.Equal(" rd Frth", textBox.Text);
  178. // ( |rd Frth)
  179. textBox.CaretIndex = 1;
  180. RaiseKeyEvent(textBox, Key.Back, KeyModifiers.Control);
  181. Assert.Equal("rd Frth", textBox.Text);
  182. }
  183. }
  184. [Fact]
  185. public void Control_Delete_Should_Remove_The_Word_After_The_Caret_If_There_Is_No_Selection()
  186. {
  187. using (Start())
  188. {
  189. var textBox = new MaskedTextBox
  190. {
  191. Template = CreateTemplate(),
  192. Text = "First Second Third Fourth",
  193. CaretIndex = 19
  194. };
  195. textBox.ApplyTemplate();
  196. // (First Second Third |Fourth)
  197. RaiseKeyEvent(textBox, Key.Delete, KeyModifiers.Control);
  198. Assert.Equal("First Second Third ", textBox.Text);
  199. // (First Second |Third )
  200. textBox.CaretIndex = 13;
  201. RaiseKeyEvent(textBox, Key.Delete, KeyModifiers.Control);
  202. Assert.Equal("First Second ", textBox.Text);
  203. // (First Sec|ond )
  204. textBox.CaretIndex = 9;
  205. RaiseKeyEvent(textBox, Key.Delete, KeyModifiers.Control);
  206. Assert.Equal("First Sec", textBox.Text);
  207. // (Fi[rs]t Sec )
  208. textBox.SelectionStart = 2;
  209. textBox.SelectionEnd = 4;
  210. RaiseKeyEvent(textBox, Key.Delete, KeyModifiers.Control);
  211. Assert.Equal("Fit Sec", textBox.Text);
  212. // (Fit Sec| )
  213. textBox.Text += " ";
  214. textBox.CaretIndex = 7;
  215. RaiseKeyEvent(textBox, Key.Delete, KeyModifiers.Control);
  216. Assert.Equal("Fit Sec", textBox.Text);
  217. }
  218. }
  219. [Fact]
  220. public void Setting_SelectionStart_To_SelectionEnd_Sets_CaretPosition_To_SelectionStart()
  221. {
  222. using (Start())
  223. {
  224. var textBox = new MaskedTextBox
  225. {
  226. Text = "0123456789"
  227. };
  228. textBox.SelectionStart = 2;
  229. textBox.SelectionEnd = 2;
  230. Assert.Equal(2, textBox.CaretIndex);
  231. }
  232. }
  233. [Fact]
  234. public void Setting_Text_Updates_CaretPosition()
  235. {
  236. using (Start())
  237. {
  238. var target = new MaskedTextBox
  239. {
  240. Text = "Initial Text",
  241. CaretIndex = 11
  242. };
  243. var invoked = false;
  244. target.GetObservable(TextBox.TextProperty).Skip(1).Subscribe(_ =>
  245. {
  246. // Caret index should be set before Text changed notification, as we don't want
  247. // to notify with an invalid CaretIndex.
  248. Assert.Equal(7, target.CaretIndex);
  249. invoked = true;
  250. });
  251. target.Text = "Changed";
  252. Assert.True(invoked);
  253. }
  254. }
  255. [Fact]
  256. public void Press_Enter_Does_Not_Accept_Return()
  257. {
  258. using (Start())
  259. {
  260. var target = new MaskedTextBox
  261. {
  262. Template = CreateTemplate(),
  263. AcceptsReturn = false,
  264. Text = "1234"
  265. };
  266. RaiseKeyEvent(target, Key.Enter, 0);
  267. Assert.Equal("1234", target.Text);
  268. }
  269. }
  270. [Fact]
  271. public void Press_Enter_Add_Default_Newline()
  272. {
  273. using (Start())
  274. {
  275. var target = new MaskedTextBox
  276. {
  277. Template = CreateTemplate(),
  278. AcceptsReturn = true
  279. };
  280. target.ApplyTemplate();
  281. RaiseKeyEvent(target, Key.Enter, 0);
  282. Assert.Equal(Environment.NewLine, target.Text);
  283. }
  284. }
  285. [Theory]
  286. [InlineData("00/00/0000", "12102000", "12/10/2000")]
  287. [InlineData("LLLL", "дбs", "____")]
  288. [InlineData("AA", "Ü1", "__")]
  289. public void AsciiOnly_Should_Not_Accept_Non_Ascii(string mask, string textEventArg, string expected)
  290. {
  291. using (Start())
  292. {
  293. var target = new MaskedTextBox
  294. {
  295. Template = CreateTemplate(),
  296. Mask = mask,
  297. AsciiOnly = true
  298. };
  299. RaiseTextEvent(target, textEventArg);
  300. Assert.Equal(expected, target.Text);
  301. }
  302. }
  303. [Fact]
  304. public void Programmatically_Set_Text_Should_Not_Be_Removed_On_Key_Press()
  305. {
  306. using (Start())
  307. {
  308. var target = new MaskedTextBox
  309. {
  310. Template = CreateTemplate(),
  311. Mask = "00:00:00.000",
  312. Text = "12:34:56.000"
  313. };
  314. target.CaretIndex = target.Text.Length;
  315. RaiseKeyEvent(target, Key.Back, 0);
  316. Assert.Equal("12:34:56.00_", target.Text);
  317. }
  318. }
  319. [Fact]
  320. public void Invalid_Programmatically_Set_Text_Should_Be_Rejected()
  321. {
  322. using (Start())
  323. {
  324. var target = new MaskedTextBox
  325. {
  326. Template = CreateTemplate(),
  327. Mask = "00:00:00.000",
  328. Text = "12:34:560000"
  329. };
  330. Assert.Equal("__:__:__.___", target.Text);
  331. }
  332. }
  333. [Theory]
  334. [InlineData("00/00/0000", "12102000", "**/**/****")]
  335. [InlineData("LLLL", "дбs", "***_")]
  336. [InlineData("AA#00", "S2 33", "**_**")]
  337. public void PasswordChar_Should_Hide_User_Input(string mask, string textEventArg, string expected)
  338. {
  339. using (Start())
  340. {
  341. var target = new MaskedTextBox
  342. {
  343. Template = CreateTemplate(),
  344. Mask = mask,
  345. PasswordChar = '*'
  346. };
  347. RaiseTextEvent(target, textEventArg);
  348. Assert.Equal(expected, target.Text);
  349. }
  350. }
  351. [Theory]
  352. [InlineData("00/00/0000", "12102000", "12/10/2000")]
  353. [InlineData("LLLL", "дбs", "дбs_")]
  354. [InlineData("AA#00", "S2 33", "S2_33")]
  355. public void Mask_Should_Work_Correctly(string mask, string textEventArg, string expected)
  356. {
  357. using (Start())
  358. {
  359. var target = new MaskedTextBox
  360. {
  361. Template = CreateTemplate(),
  362. Mask = mask
  363. };
  364. RaiseTextEvent(target, textEventArg);
  365. Assert.Equal(expected, target.Text);
  366. }
  367. }
  368. [Fact]
  369. public void Press_Enter_Add_Custom_Newline()
  370. {
  371. using (Start())
  372. {
  373. var target = new MaskedTextBox
  374. {
  375. Template = CreateTemplate(),
  376. AcceptsReturn = true,
  377. NewLine = "Test"
  378. };
  379. target.ApplyTemplate();
  380. RaiseKeyEvent(target, Key.Enter, 0);
  381. Assert.Equal("Test", target.Text);
  382. }
  383. }
  384. [Theory]
  385. [InlineData(new object[] { false, TextWrapping.NoWrap, ScrollBarVisibility.Hidden })]
  386. [InlineData(new object[] { false, TextWrapping.Wrap, ScrollBarVisibility.Disabled })]
  387. [InlineData(new object[] { true, TextWrapping.NoWrap, ScrollBarVisibility.Auto })]
  388. [InlineData(new object[] { true, TextWrapping.Wrap, ScrollBarVisibility.Disabled })]
  389. public void Has_Correct_Horizontal_ScrollBar_Visibility(
  390. bool acceptsReturn,
  391. TextWrapping wrapping,
  392. ScrollBarVisibility expected)
  393. {
  394. using (Start())
  395. {
  396. var target = new MaskedTextBox
  397. {
  398. AcceptsReturn = acceptsReturn,
  399. TextWrapping = wrapping,
  400. };
  401. Assert.Equal(expected, ScrollViewer.GetHorizontalScrollBarVisibility(target));
  402. }
  403. }
  404. [Fact]
  405. public void SelectionEnd_Doesnt_Cause_Exception()
  406. {
  407. using (Start())
  408. {
  409. var target = new MaskedTextBox
  410. {
  411. Template = CreateTemplate(),
  412. Text = "0123456789"
  413. };
  414. target.SelectionStart = 0;
  415. target.SelectionEnd = 9;
  416. target.Text = "123";
  417. RaiseTextEvent(target, "456");
  418. Assert.True(true);
  419. }
  420. }
  421. [Fact]
  422. public void SelectionStart_Doesnt_Cause_Exception()
  423. {
  424. using (Start())
  425. {
  426. var target = new MaskedTextBox
  427. {
  428. Template = CreateTemplate(),
  429. Text = "0123456789"
  430. };
  431. target.SelectionStart = 8;
  432. target.SelectionEnd = 9;
  433. target.Text = "123";
  434. RaiseTextEvent(target, "456");
  435. Assert.True(true);
  436. }
  437. }
  438. [Fact]
  439. public void SelectionStartEnd_Are_Valid_AterTextChange()
  440. {
  441. using (Start())
  442. {
  443. var target = new MaskedTextBox
  444. {
  445. Template = CreateTemplate(),
  446. Text = "0123456789"
  447. };
  448. target.SelectionStart = 8;
  449. target.SelectionEnd = 9;
  450. target.Text = "123";
  451. Assert.True(target.SelectionStart <= "123".Length);
  452. Assert.True(target.SelectionEnd <= "123".Length);
  453. }
  454. }
  455. [Fact]
  456. public void SelectedText_Changes_OnSelectionChange()
  457. {
  458. using (Start())
  459. {
  460. var target = new MaskedTextBox
  461. {
  462. Template = CreateTemplate(),
  463. Text = "0123456789"
  464. };
  465. Assert.True(target.SelectedText == "");
  466. target.SelectionStart = 2;
  467. target.SelectionEnd = 4;
  468. Assert.True(target.SelectedText == "23");
  469. }
  470. }
  471. [Fact]
  472. public void SelectedText_EditsText()
  473. {
  474. using (Start())
  475. {
  476. var target = new MaskedTextBox
  477. {
  478. Template = CreateTemplate(),
  479. Text = "0123"
  480. };
  481. target.SelectedText = "AA";
  482. Assert.True(target.Text == "AA0123");
  483. target.SelectionStart = 1;
  484. target.SelectionEnd = 3;
  485. target.SelectedText = "BB";
  486. Assert.True(target.Text == "ABB123");
  487. }
  488. }
  489. [Fact]
  490. public void SelectedText_CanClearText()
  491. {
  492. using (Start())
  493. {
  494. var target = new MaskedTextBox
  495. {
  496. Template = CreateTemplate(),
  497. Text = "0123"
  498. };
  499. target.SelectionStart = 1;
  500. target.SelectionEnd = 3;
  501. target.SelectedText = "";
  502. Assert.True(target.Text == "03");
  503. }
  504. }
  505. [Fact]
  506. public void SelectedText_NullClearsText()
  507. {
  508. using (Start())
  509. {
  510. var target = new MaskedTextBox
  511. {
  512. Template = CreateTemplate(),
  513. Text = "0123"
  514. };
  515. target.SelectionStart = 1;
  516. target.SelectionEnd = 3;
  517. target.SelectedText = null;
  518. Assert.True(target.Text == "03");
  519. }
  520. }
  521. [Fact]
  522. public void CoerceCaretIndex_Doesnt_Cause_Exception_with_malformed_line_ending()
  523. {
  524. using (Start())
  525. {
  526. var target = new MaskedTextBox
  527. {
  528. Template = CreateTemplate(),
  529. Text = "0123456789\r"
  530. };
  531. target.CaretIndex = 11;
  532. Assert.True(true);
  533. }
  534. }
  535. [Theory]
  536. [InlineData(Key.Up)]
  537. [InlineData(Key.Down)]
  538. [InlineData(Key.Home)]
  539. [InlineData(Key.End)]
  540. public void Textbox_doesnt_crash_when_Receives_input_and_template_not_applied(Key key)
  541. {
  542. using (Start(FocusServices))
  543. {
  544. var target1 = new MaskedTextBox
  545. {
  546. Template = CreateTemplate(),
  547. Text = "1234",
  548. };
  549. var root = new TestRoot { Child = target1 };
  550. target1.Focus();
  551. Assert.True(target1.IsFocused);
  552. RaiseKeyEvent(target1, key, KeyModifiers.None);
  553. }
  554. }
  555. [Fact]
  556. public void TextBox_GotFocus_And_LostFocus_Work_Properly()
  557. {
  558. using (Start(FocusServices))
  559. {
  560. var target1 = new MaskedTextBox
  561. {
  562. Template = CreateTemplate(),
  563. Text = "1234"
  564. };
  565. var target2 = new MaskedTextBox
  566. {
  567. Template = CreateTemplate(),
  568. Text = "5678"
  569. };
  570. var sp = new StackPanel();
  571. sp.Children.Add(target1);
  572. sp.Children.Add(target2);
  573. target1.ApplyTemplate();
  574. target2.ApplyTemplate();
  575. var root = new TestRoot { Child = sp };
  576. var gfcount = 0;
  577. var lfcount = 0;
  578. target1.GotFocus += (s, e) => gfcount++;
  579. target2.LostFocus += (s, e) => lfcount++;
  580. target2.Focus();
  581. Assert.False(target1.IsFocused);
  582. Assert.True(target2.IsFocused);
  583. target1.Focus();
  584. Assert.False(target2.IsFocused);
  585. Assert.True(target1.IsFocused);
  586. Assert.Equal(1, gfcount);
  587. Assert.Equal(1, lfcount);
  588. }
  589. }
  590. [Fact]
  591. public void TextBox_CaretIndex_Persists_When_Focus_Lost()
  592. {
  593. using (Start(FocusServices))
  594. {
  595. var target1 = new MaskedTextBox
  596. {
  597. Template = CreateTemplate(),
  598. Text = "1234"
  599. };
  600. var target2 = new MaskedTextBox
  601. {
  602. Template = CreateTemplate(),
  603. Text = "5678"
  604. };
  605. var sp = new StackPanel();
  606. sp.Children.Add(target1);
  607. sp.Children.Add(target2);
  608. target1.ApplyTemplate();
  609. target2.ApplyTemplate();
  610. var root = new TestRoot { Child = sp };
  611. target2.Focus();
  612. target2.CaretIndex = 2;
  613. Assert.False(target1.IsFocused);
  614. Assert.True(target2.IsFocused);
  615. target1.Focus();
  616. Assert.Equal(2, target2.CaretIndex);
  617. }
  618. }
  619. [Fact]
  620. public void TextBox_Reveal_Password_Reset_When_Lost_Focus()
  621. {
  622. using (Start(FocusServices))
  623. {
  624. var target1 = new MaskedTextBox
  625. {
  626. Template = CreateTemplate(),
  627. Text = "1234",
  628. PasswordChar = '*'
  629. };
  630. var target2 = new MaskedTextBox
  631. {
  632. Template = CreateTemplate(),
  633. Text = "5678"
  634. };
  635. var sp = new StackPanel();
  636. sp.Children.Add(target1);
  637. sp.Children.Add(target2);
  638. target1.ApplyTemplate();
  639. target2.ApplyTemplate();
  640. var root = new TestRoot { Child = sp };
  641. target1.Focus();
  642. target1.RevealPassword = true;
  643. target2.Focus();
  644. Assert.False(target1.RevealPassword);
  645. }
  646. }
  647. [Fact]
  648. public void Setting_Bound_Text_To_Null_Works()
  649. {
  650. using (Start())
  651. {
  652. var source = new Class1 { Bar = "bar" };
  653. var target = new MaskedTextBox { DataContext = source };
  654. target.Bind(TextBox.TextProperty, new Binding("Bar"));
  655. Assert.Equal("bar", target.Text);
  656. source.Bar = null;
  657. Assert.Null(target.Text);
  658. }
  659. }
  660. [Theory]
  661. [InlineData("abc", "d", 3, 0, 0, false, "abc")]
  662. [InlineData("abc", "dd", 4, 3, 3, false, "abcd")]
  663. [InlineData("abc", "ddd", 3, 0, 2, true, "ddc")]
  664. [InlineData("abc", "dddd", 4, 1, 3, true, "addd")]
  665. [InlineData("abc", "ddddd", 5, 3, 3, true, "abcdd")]
  666. public async Task MaxLength_Works_Properly(
  667. string initalText,
  668. string textInput,
  669. int maxLength,
  670. int selectionStart,
  671. int selectionEnd,
  672. bool fromClipboard,
  673. string expected)
  674. {
  675. using (Start())
  676. {
  677. var target = new MaskedTextBox
  678. {
  679. Template = CreateTemplate(),
  680. Text = initalText,
  681. MaxLength = maxLength,
  682. SelectionStart = selectionStart,
  683. SelectionEnd = selectionEnd
  684. };
  685. var impl = CreateMockTopLevelImpl();
  686. var topLevel = new TestTopLevel(impl.Object)
  687. {
  688. Template = CreateTopLevelTemplate()
  689. };
  690. topLevel.Content = target;
  691. topLevel.ApplyTemplate();
  692. topLevel.LayoutManager.ExecuteInitialLayoutPass();
  693. target.ApplyTemplate();
  694. if (fromClipboard)
  695. {
  696. await topLevel.Clipboard!.SetTextAsync(textInput);
  697. RaiseKeyEvent(target, Key.V, KeyModifiers.Control);
  698. await topLevel.Clipboard!.ClearAsync();
  699. }
  700. else
  701. {
  702. RaiseTextEvent(target, textInput);
  703. }
  704. Assert.Equal(expected, target.Text);
  705. }
  706. }
  707. [Theory]
  708. [InlineData(Key.X, KeyModifiers.Control)]
  709. [InlineData(Key.Back, KeyModifiers.None)]
  710. [InlineData(Key.Delete, KeyModifiers.None)]
  711. [InlineData(Key.Tab, KeyModifiers.None)]
  712. [InlineData(Key.Enter, KeyModifiers.None)]
  713. public void Keys_Allow_Undo(Key key, KeyModifiers modifiers)
  714. {
  715. using (Start())
  716. {
  717. var target = new MaskedTextBox
  718. {
  719. Template = CreateTemplate(),
  720. Text = "0123",
  721. AcceptsReturn = true,
  722. AcceptsTab = true
  723. };
  724. var impl = CreateMockTopLevelImpl();
  725. var topLevel = new TestTopLevel(impl.Object)
  726. {
  727. Template = CreateTopLevelTemplate()
  728. };
  729. topLevel.Content = target;
  730. topLevel.ApplyTemplate();
  731. topLevel.LayoutManager.ExecuteInitialLayoutPass();
  732. target.SelectionStart = 1;
  733. target.SelectionEnd = 3;
  734. RaiseKeyEvent(target, key, modifiers);
  735. RaiseKeyEvent(target, Key.Z, KeyModifiers.Control); // undo
  736. Assert.Equal("0123", target.Text);
  737. }
  738. }
  739. [Fact]
  740. public void Invalid_Text_Is_Coerced_Without_Raising_Intermediate_Change()
  741. {
  742. using (Start())
  743. {
  744. var target = new MaskedTextBox
  745. {
  746. Template = CreateTemplate()
  747. };
  748. var impl = CreateMockTopLevelImpl();
  749. var topLevel = new TestTopLevel(impl.Object) {
  750. Template = CreateTopLevelTemplate(),
  751. Content = target
  752. };
  753. topLevel.ApplyTemplate();
  754. topLevel.LayoutManager.ExecuteInitialLayoutPass();
  755. var texts = new System.Collections.Generic.List<string>();
  756. target.PropertyChanged += (_, e) =>
  757. {
  758. if (e.Property == TextBox.TextProperty)
  759. texts.Add(e.GetNewValue<string>());
  760. };
  761. target.Mask = "000";
  762. target.Text = "123";
  763. target.Text = "abc";
  764. Assert.Equal(["___", "123"], texts);
  765. }
  766. }
  767. private static TestServices FocusServices => TestServices.MockThreadingInterface.With(
  768. focusManager: new FocusManager(),
  769. keyboardDevice: () => new KeyboardDevice(),
  770. keyboardNavigation: () => new KeyboardNavigationHandler(),
  771. inputManager: new InputManager(),
  772. renderInterface: new HeadlessPlatformRenderInterface(),
  773. fontManagerImpl: new HeadlessFontManagerStub(),
  774. textShaperImpl: new HeadlessTextShaperStub(),
  775. standardCursorFactory: Mock.Of<ICursorFactory>());
  776. private static TestServices Services => TestServices.MockThreadingInterface.With(
  777. renderInterface: new HeadlessPlatformRenderInterface(),
  778. standardCursorFactory: Mock.Of<ICursorFactory>(),
  779. textShaperImpl: new HeadlessTextShaperStub(),
  780. fontManagerImpl: new HeadlessFontManagerStub());
  781. private static IControlTemplate CreateTemplate()
  782. {
  783. return new FuncControlTemplate<MaskedTextBox>((control, scope) =>
  784. new TextPresenter
  785. {
  786. Name = "PART_TextPresenter",
  787. [!!TextPresenter.TextProperty] = new Binding
  788. {
  789. Path = nameof(TextPresenter.Text),
  790. Mode = BindingMode.TwoWay,
  791. Priority = BindingPriority.Template,
  792. RelativeSource = new RelativeSource(RelativeSourceMode.TemplatedParent),
  793. },
  794. [!!TextPresenter.CaretIndexProperty] = new Binding
  795. {
  796. Path = nameof(TextPresenter.CaretIndex),
  797. Mode = BindingMode.TwoWay,
  798. Priority = BindingPriority.Template,
  799. RelativeSource = new RelativeSource(RelativeSourceMode.TemplatedParent),
  800. }
  801. }.RegisterInNameScope(scope));
  802. }
  803. private static void RaiseKeyEvent(MaskedTextBox textBox, Key key, KeyModifiers inputModifiers)
  804. {
  805. textBox.RaiseEvent(new KeyEventArgs
  806. {
  807. RoutedEvent = InputElement.KeyDownEvent,
  808. KeyModifiers = inputModifiers,
  809. Key = key
  810. });
  811. }
  812. private void RaiseTextEvent(MaskedTextBox textBox, string text)
  813. {
  814. textBox.RaiseEvent(new TextInputEventArgs
  815. {
  816. RoutedEvent = InputElement.TextInputEvent,
  817. Text = text
  818. });
  819. }
  820. private static IDisposable Start(TestServices services = null)
  821. {
  822. CultureInfo.CurrentCulture = CultureInfo.CurrentUICulture = CultureInfo.GetCultureInfo("en-US");
  823. return UnitTestApplication.Start(services ?? Services);
  824. }
  825. private class Class1 : NotifyingBase
  826. {
  827. private int _foo;
  828. private string _bar;
  829. public int Foo
  830. {
  831. get { return _foo; }
  832. set { _foo = value; RaisePropertyChanged(); }
  833. }
  834. public string Bar
  835. {
  836. get { return _bar; }
  837. set { _bar = value; RaisePropertyChanged(); }
  838. }
  839. }
  840. private class TestTopLevel : TopLevel
  841. {
  842. private readonly ILayoutManager _layoutManager;
  843. public TestTopLevel(ITopLevelImpl impl, ILayoutManager layoutManager = null)
  844. : base(impl)
  845. {
  846. _layoutManager = layoutManager ?? new LayoutManager(this);
  847. }
  848. private protected override ILayoutManager CreateLayoutManager() => _layoutManager;
  849. }
  850. private static Mock<ITopLevelImpl> CreateMockTopLevelImpl()
  851. {
  852. var clipboard = new Mock<ITopLevelImpl>();
  853. clipboard.Setup(x => x.Compositor).Returns(RendererMocks.CreateDummyCompositor());
  854. clipboard.Setup(r => r.TryGetFeature(typeof(IClipboard)))
  855. .Returns(new HeadlessClipboardStub());
  856. clipboard.SetupGet(x => x.RenderScaling).Returns(1);
  857. return clipboard;
  858. }
  859. private static FuncControlTemplate<TestTopLevel> CreateTopLevelTemplate()
  860. {
  861. return new FuncControlTemplate<TestTopLevel>((x, scope) =>
  862. new ContentPresenter
  863. {
  864. Name = "PART_ContentPresenter",
  865. [!ContentPresenter.ContentProperty] = x[!ContentControl.ContentProperty],
  866. }.RegisterInNameScope(scope));
  867. }
  868. private class TestContextMenu : ContextMenu
  869. {
  870. public TestContextMenu()
  871. {
  872. IsOpen = true;
  873. }
  874. }
  875. }
  876. }