AutoCompleteBoxPage.xaml.cs 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. using Avalonia.Controls;
  2. using Avalonia.LogicalTree;
  3. using Avalonia.Markup.Xaml;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using Avalonia.Data.Converters;
  10. using Avalonia.Data;
  11. using ControlCatalog.Models;
  12. namespace ControlCatalog.Pages
  13. {
  14. public class AutoCompleteBoxPage : UserControl
  15. {
  16. private StateData[] BuildAllStates()
  17. {
  18. return new StateData[]
  19. {
  20. new StateData("Alabama","AL","Montgomery"),
  21. new StateData("Alaska","AK","Juneau"),
  22. new StateData("Arizona","AZ","Phoenix"),
  23. new StateData("Arkansas","AR","Little Rock"),
  24. new StateData("California","CA","Sacramento"),
  25. new StateData("Colorado","CO","Denver"),
  26. new StateData("Connecticut","CT","Hartford"),
  27. new StateData("Delaware","DE","Dover"),
  28. new StateData("Florida","FL","Tallahassee"),
  29. new StateData("Georgia","GA","Atlanta"),
  30. new StateData("Hawaii","HI","Honolulu"),
  31. new StateData("Idaho","ID","Boise"),
  32. new StateData("Illinois","IL","Springfield"),
  33. new StateData("Indiana","IN","Indianapolis"),
  34. new StateData("Iowa","IA","Des Moines"),
  35. new StateData("Kansas","KS","Topeka"),
  36. new StateData("Kentucky","KY","Frankfort"),
  37. new StateData("Louisiana","LA","Baton Rouge"),
  38. new StateData("Maine","ME","Augusta"),
  39. new StateData("Maryland","MD","Annapolis"),
  40. new StateData("Massachusetts","MA","Boston"),
  41. new StateData("Michigan","MI","Lansing"),
  42. new StateData("Minnesota","MN","St. Paul"),
  43. new StateData("Mississippi","MS","Jackson"),
  44. new StateData("Missouri","MO","Jefferson City"),
  45. new StateData("Montana","MT","Helena"),
  46. new StateData("Nebraska","NE","Lincoln"),
  47. new StateData("Nevada","NV","Carson City"),
  48. new StateData("New Hampshire","NH","Concord"),
  49. new StateData("New Jersey","NJ","Trenton"),
  50. new StateData("New Mexico","NM","Santa Fe"),
  51. new StateData("New York","NY","Albany"),
  52. new StateData("North Carolina","NC","Raleigh"),
  53. new StateData("North Dakota","ND","Bismarck"),
  54. new StateData("Ohio","OH","Columbus"),
  55. new StateData("Oklahoma","OK","Oklahoma City"),
  56. new StateData("Oregon","OR","Salem"),
  57. new StateData("Pennsylvania","PA","Harrisburg"),
  58. new StateData("Rhode Island","RI","Providence"),
  59. new StateData("South Carolina","SC","Columbia"),
  60. new StateData("South Dakota","SD","Pierre"),
  61. new StateData("Tennessee","TN","Nashville"),
  62. new StateData("Texas","TX","Austin"),
  63. new StateData("Utah","UT","Salt Lake City"),
  64. new StateData("Vermont","VT","Montpelier"),
  65. new StateData("Virginia","VA","Richmond"),
  66. new StateData("Washington","WA","Olympia"),
  67. new StateData("West Virginia","WV","Charleston"),
  68. new StateData("Wisconsin","WI","Madison"),
  69. new StateData("Wyoming","WY","Cheyenne"),
  70. };
  71. }
  72. public StateData[] States { get; private set; }
  73. private LinkedList<string>[] BuildAllSentences()
  74. {
  75. return new string[]
  76. {
  77. "Hello world",
  78. "No this is Patrick",
  79. "Never gonna give you up",
  80. "How does one patch KDE2 under FreeBSD"
  81. }
  82. .Select(x => new LinkedList<string>(x.Split(' ')))
  83. .ToArray();
  84. }
  85. public LinkedList<string>[] Sentences { get; private set; }
  86. public AutoCompleteBoxPage()
  87. {
  88. this.InitializeComponent();
  89. States = BuildAllStates();
  90. Sentences = BuildAllSentences();
  91. foreach (AutoCompleteBox box in GetAllAutoCompleteBox().Where(x => x.Name != "CustomAutocompleteBox"))
  92. {
  93. box.Items = States;
  94. }
  95. var converter = new FuncMultiValueConverter<string, string>(parts =>
  96. {
  97. return String.Format("{0} ({1})", parts.ToArray());
  98. });
  99. var binding = new MultiBinding { Converter = converter };
  100. binding.Bindings.Add(new Binding("Name"));
  101. binding.Bindings.Add(new Binding("Abbreviation"));
  102. var multibindingBox = this.Get<AutoCompleteBox>("MultiBindingBox");
  103. multibindingBox.ValueMemberBinding = binding;
  104. var asyncBox = this.Get<AutoCompleteBox>("AsyncBox");
  105. asyncBox.AsyncPopulator = PopulateAsync;
  106. var customAutocompleteBox = this.Get<AutoCompleteBox>("CustomAutocompleteBox");
  107. customAutocompleteBox.Items = Sentences.SelectMany(x => x);
  108. customAutocompleteBox.TextFilter = LastWordContains;
  109. customAutocompleteBox.TextSelector = AppendWord;
  110. }
  111. private IEnumerable<AutoCompleteBox> GetAllAutoCompleteBox()
  112. {
  113. return
  114. this.GetLogicalDescendants()
  115. .OfType<AutoCompleteBox>();
  116. }
  117. private bool StringContains(string str, string? query)
  118. {
  119. if (query == null) return false;
  120. return str.IndexOf(query, StringComparison.OrdinalIgnoreCase) >= 0;
  121. }
  122. private async Task<IEnumerable<object>> PopulateAsync(string? searchText, CancellationToken cancellationToken)
  123. {
  124. await Task.Delay(TimeSpan.FromSeconds(1.5), cancellationToken);
  125. return
  126. States.Where(data => StringContains(data.Name, searchText) || StringContains(data.Capital, searchText))
  127. .ToList();
  128. }
  129. private bool LastWordContains(string? searchText, string? item)
  130. {
  131. var words = searchText?.Split(' ') ?? Array.Empty<string>();
  132. var options = Sentences.Select(x => x.First)
  133. .ToArray<LinkedListNode<string>?>();
  134. for (var i = 0; i < words.Length; ++i)
  135. {
  136. var word = words[i];
  137. for (var j = 0; word is { } && j < options.Length; ++j)
  138. {
  139. if (options[i] is { } option)
  140. {
  141. if (i == words.Length - 1)
  142. {
  143. options[j] = option.Value.ToLower().Contains(word.ToLower()) ? option : null;
  144. }
  145. else
  146. {
  147. options[j] = option.Value.Equals(word, StringComparison.InvariantCultureIgnoreCase) ? option.Next : null;
  148. }
  149. }
  150. }
  151. }
  152. return options.Any(x => x != null && x.Value == item);
  153. }
  154. private string AppendWord(string? text, string? item)
  155. {
  156. if (item is { })
  157. {
  158. string[] parts = text?.Split(' ') ?? Array.Empty<string>();
  159. if (parts.Length == 0)
  160. return item;
  161. parts[parts.Length - 1] = item;
  162. return string.Join(" ", parts);
  163. }
  164. return string.Empty;
  165. }
  166. private void InitializeComponent()
  167. {
  168. AvaloniaXamlLoader.Load(this);
  169. }
  170. }
  171. }