MaskedTextBoxTests.cs 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075
  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
  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. internal class ClipboardStub : IClipboard // in order to get tests working that use the clipboard
  841. {
  842. private string _text;
  843. public Task<string> GetTextAsync() => Task.FromResult(_text);
  844. public Task SetTextAsync(string text)
  845. {
  846. _text = text;
  847. return Task.CompletedTask;
  848. }
  849. public Task ClearAsync()
  850. {
  851. _text = null;
  852. return Task.CompletedTask;
  853. }
  854. public Task SetDataObjectAsync(IDataObject data) => Task.CompletedTask;
  855. public Task<string[]> GetFormatsAsync() => Task.FromResult(Array.Empty<string>());
  856. public Task<object> GetDataAsync(string format) => Task.FromResult((object)null);
  857. public Task FlushAsync() =>
  858. Task.CompletedTask;
  859. }
  860. private class TestTopLevel : TopLevel
  861. {
  862. private readonly ILayoutManager _layoutManager;
  863. public TestTopLevel(ITopLevelImpl impl, ILayoutManager layoutManager = null)
  864. : base(impl)
  865. {
  866. _layoutManager = layoutManager ?? new LayoutManager(this);
  867. }
  868. private protected override ILayoutManager CreateLayoutManager() => _layoutManager;
  869. }
  870. private static Mock<ITopLevelImpl> CreateMockTopLevelImpl()
  871. {
  872. var clipboard = new Mock<ITopLevelImpl>();
  873. clipboard.Setup(x => x.Compositor).Returns(RendererMocks.CreateDummyCompositor());
  874. clipboard.Setup(r => r.TryGetFeature(typeof(IClipboard)))
  875. .Returns(new ClipboardStub());
  876. clipboard.SetupGet(x => x.RenderScaling).Returns(1);
  877. return clipboard;
  878. }
  879. private static FuncControlTemplate<TestTopLevel> CreateTopLevelTemplate()
  880. {
  881. return new FuncControlTemplate<TestTopLevel>((x, scope) =>
  882. new ContentPresenter
  883. {
  884. Name = "PART_ContentPresenter",
  885. [!ContentPresenter.ContentProperty] = x[!ContentControl.ContentProperty],
  886. }.RegisterInNameScope(scope));
  887. }
  888. private class TestContextMenu : ContextMenu
  889. {
  890. public TestContextMenu()
  891. {
  892. IsOpen = true;
  893. }
  894. }
  895. }
  896. }