MaskedTextBoxTests.cs 32 KB

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