SearchComboBox.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. using System.Collections;
  2. using System.ComponentModel;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using System.Windows;
  6. using System.Windows.Controls;
  7. using System.Windows.Controls.Primitives;
  8. using System.Windows.Data;
  9. using System.Windows.Input;
  10. namespace FWindSoft.Wpf.Controls
  11. {
  12. /// <summary>
  13. /// 带搜索功能的comboBox
  14. /// </summary>
  15. /// [TemplatePart(Name = "PART_textBoxNewItem", Type=typeof(TextBox))]
  16. [TemplatePart(Name = "PART_SearchText", Type = typeof(TextBox))]
  17. [TemplatePart(Name = "PART_Popup", Type = typeof(Popup))]
  18. [TemplatePart(Name = "PART_Button", Type = typeof(Button))]
  19. public class SearchComboBox : ListBox
  20. {
  21. static SearchComboBox()
  22. {
  23. DefaultStyleKeyProperty.OverrideMetadata(typeof(SearchComboBox), new FrameworkPropertyMetadata(typeof(SearchComboBox)));
  24. }
  25. public SearchComboBox()
  26. {
  27. Keyboard.AddPreviewKeyDownHandler(this, OnKeyDown);
  28. Keyboard.AddPreviewKeyUpHandler(this, OnKeyUp);
  29. this.AddHandler(ListBoxItem.PreviewMouseDownEvent,new MouseButtonEventHandler(MouseButtonEventHandler));
  30. this.IsTextSearchCaseSensitive = false;
  31. this.IsTextSearchEnabled = false;
  32. this.InEdit = false;
  33. this.SetValue(KeyboardNavigation.DirectionalNavigationProperty, KeyboardNavigationMode.Contained);
  34. }
  35. private void MouseButtonEventHandler(object sender, MouseButtonEventArgs e)
  36. {
  37. var element = e.OriginalSource as UIElement;
  38. if (element == null)
  39. return;
  40. var listItem = element.GetParentTypeSelf<ListBoxItem>();
  41. if (listItem == null)
  42. return;
  43. if (listItem.DataContext == this.SelectedItem)
  44. {
  45. SyncSelectedItemText();
  46. }
  47. }
  48. private void OnKeyDown(object sender, KeyEventArgs e)
  49. {
  50. if (e.Key == Key.Enter && IsDropDownOpen)
  51. {
  52. this.IsDropDownOpen = false;
  53. if (this.SelectedItem != null)
  54. {
  55. SyncSelectedItemText();
  56. }
  57. return;
  58. }
  59. if (!(Key.Up == e.Key || Key.Down == e.Key))
  60. {
  61. //EditableTextBox.Focus();
  62. }
  63. else
  64. {
  65. UIElement item = ItemContainerGenerator.ContainerFromItem(SelectedItem) as UIElement;
  66. if ((item == null) && (Items.Count > 0))
  67. item = ItemContainerGenerator.ContainerFromItem(Items[0]) as UIElement;
  68. if (item != null)
  69. item.Focus();
  70. }
  71. }
  72. private void OnKeyUp(object sender, KeyEventArgs e)
  73. {
  74. EditableTextBox.Focus();
  75. }
  76. #region 属性相关
  77. /// <summary>
  78. /// 关联文本
  79. /// </summary>
  80. public static readonly DependencyProperty TextProperty =
  81. DependencyProperty.Register("Text", typeof(string), typeof(SearchComboBox));
  82. /// <summary>
  83. /// 关联文本
  84. /// </summary>
  85. public string Text
  86. {
  87. get { return (string)GetValue(TextProperty); }
  88. set { SetValue(TextProperty, value); }
  89. }
  90. /// <summary>
  91. /// 是否下拉打开
  92. /// </summary>
  93. public static readonly DependencyProperty IsDropDownOpenProperty =
  94. DependencyProperty.Register("IsDropDownOpen", typeof(bool), typeof(SearchComboBox));
  95. /// <summary>
  96. /// 是否下拉打开
  97. /// </summary>
  98. public bool IsDropDownOpen
  99. {
  100. get { return (bool)GetValue(IsDropDownOpenProperty); }
  101. set { SetValue(IsDropDownOpenProperty, value); }
  102. }
  103. /// <summary>
  104. /// Dependency backing for the MaxDropDownHeight property.
  105. /// </summary>
  106. public static readonly DependencyProperty MaxDropDownHeightProperty =
  107. ComboBox.MaxDropDownHeightProperty.AddOwner(typeof(SearchComboBox));
  108. /// <summary>
  109. /// Gets or sets a value indicating the maximium height of the drop down.
  110. /// </summary>
  111. public double MaxDropDownHeight
  112. {
  113. get { return (double)GetValue(MaxDropDownHeightProperty); }
  114. set { SetValue(MaxDropDownHeightProperty, value); }
  115. }
  116. /// <summary>
  117. /// 是否下拉打开
  118. /// </summary>
  119. public static readonly DependencyProperty IsReadOnlyProperty =
  120. DependencyProperty.Register("IsReadOnly", typeof(bool), typeof(SearchComboBox));
  121. /// <summary>
  122. /// 是否下拉打开
  123. /// </summary>
  124. public bool IsReadOnly
  125. {
  126. get { return (bool)GetValue(IsReadOnlyProperty); }
  127. set { SetValue(IsReadOnlyProperty, value); }
  128. }
  129. #endregion
  130. /*
  131. * 选中项会在数据源发生变化时变化,所以要保证全局的选中项
  132. */
  133. /// <summary>
  134. /// 真实的选中项
  135. /// </summary>
  136. private object RealSelectedItem { get; set; }
  137. #region 内部编辑
  138. private bool InEdit { get; set; }
  139. public void BeginInEdit()
  140. {
  141. InEdit = true;
  142. }
  143. public void EndInEdit()
  144. {
  145. InEdit = false;
  146. }
  147. #endregion
  148. #region 相关
  149. /*
  150. * 1、过滤过程中,对SelectedItem赋值,不要引起Text的变化
  151. * 2、内部引发的Text事件,不触发过滤事件
  152. * 3、编辑完成是离开控件
  153. */
  154. #endregion
  155. private static readonly DependencyProperty m_DisplayProperty =
  156. DependencyProperty.Register("m_DisplayProperty", typeof(object), typeof(SearchComboBox));
  157. private string GetDisplay(object item)
  158. {
  159. BindingOperations.SetBinding(this, m_DisplayProperty, new Binding(DisplayMemberPath) { Source = item });
  160. var propertyValue = GetValue(m_DisplayProperty);
  161. BindingOperations.ClearBinding(this, m_DisplayProperty);
  162. return propertyValue?.ToString() ?? string.Empty;
  163. }
  164. private Popup Popup { get; set; }
  165. protected TextBox EditableTextBox { get; set; }
  166. public override void OnApplyTemplate()
  167. {
  168. base.OnApplyTemplate();
  169. Popup = (Popup)this.Template.FindName("PART_Popup", this);
  170. EditableTextBox = (TextBox) this.Template.FindName("PART_SearchText", this);
  171. this.EditableTextBox.TextChanged += EditableTextBox_TextChanged;
  172. this.EditableTextBox.LostFocus += EditableTextBox_LostFocus;
  173. var toggle = (Button)this.Template.FindName("PART_Button", this);
  174. toggle.Click += Toggle_Click;
  175. this.PreviewMouseLeftButtonDown += Toggle_PreviewMouseLeftButtonDown;
  176. }
  177. private void Toggle_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
  178. {
  179. m_IsOpen = this.IsDropDownOpen;
  180. }
  181. private bool m_IsOpen;
  182. private void Toggle_Click(object sender, RoutedEventArgs e)
  183. {
  184. if (this.ItemsSource == null)
  185. return;
  186. GlobalFlag = true;
  187. RefreshFilter();
  188. SetSelectedItem();
  189. this.IsDropDownOpen = !m_IsOpen;
  190. //Popup.StaysOpen = false;
  191. }
  192. private void EditableTextBox_LostFocus(object sender, RoutedEventArgs e)
  193. {
  194. GlobalFlag = true;
  195. RefreshFilter();
  196. SetSelectedItem();
  197. }
  198. private void SetSelectedItem()
  199. {
  200. if(this.RealSelectedItem==null)
  201. {
  202. if (this.ItemsSource != null)
  203. {
  204. foreach (var item in ItemsSource)
  205. {
  206. this.RealSelectedItem = item;//.FirstOrDefault();
  207. break;
  208. }
  209. }
  210. }
  211. this.SelectedItem = this.RealSelectedItem;
  212. try
  213. {
  214. BeginInEdit();
  215. this.Text = GetDisplay(this.SelectedItem);
  216. }
  217. finally
  218. {
  219. EndInEdit();
  220. }
  221. }
  222. private void EditableTextBox_TextChanged(object sender, TextChangedEventArgs e)
  223. {
  224. TextChanged();
  225. }
  226. protected override void OnSelectionChanged(SelectionChangedEventArgs e)
  227. {
  228. try
  229. {
  230. BeginInEdit();
  231. base.OnSelectionChanged(e);
  232. if (!InSelected)
  233. {
  234. this.Text = GetDisplay(this.SelectedItem);
  235. this.EditableTextBox.Select(this.Text.Length, 0);
  236. this.RealSelectedItem = this.SelectedItem;
  237. }
  238. }
  239. finally
  240. {
  241. EndInEdit();
  242. }
  243. }
  244. /// <summary>
  245. /// 同步text显示
  246. /// </summary>
  247. private void SyncSelectedItemText()
  248. {
  249. try
  250. {
  251. BeginInEdit();
  252. if (!InSelected)
  253. {
  254. var text= GetDisplay(this.SelectedItem);
  255. //this.Text = this.SelectedItem?.ToString() ?? string.Empty;
  256. this.EditableTextBox.Text = text;
  257. this.EditableTextBox.Select(text.Length, 0);
  258. this.RealSelectedItem = this.SelectedItem;
  259. }
  260. }
  261. finally
  262. {
  263. EndInEdit();
  264. }
  265. }
  266. #region 选项控制
  267. /// <summary>
  268. /// 是否是内部选择
  269. /// </summary>
  270. private bool InSelected { get; set; } = false;
  271. private void SetSelectedItem(object item)
  272. {
  273. try
  274. {
  275. InSelected = true;
  276. this.SelectedItem = item;
  277. }
  278. finally
  279. {
  280. InSelected = false;
  281. }
  282. }
  283. #endregion
  284. #region 过滤相关
  285. private void RefreshFilter()
  286. {
  287. if (this.ItemsSource != null)
  288. {
  289. try
  290. {
  291. BeginInEdit();
  292. InSelected = true;
  293. ICollectionView view = CollectionViewSource.GetDefaultView(this.ItemsSource);
  294. view.Refresh();
  295. }
  296. finally
  297. {
  298. InSelected = false;
  299. EndInEdit();
  300. }
  301. }
  302. }
  303. /// <summary>
  304. /// 全局过滤标志,为true 则不进行过滤,初始值为ture
  305. /// </summary>
  306. private bool GlobalFlag { get; set; } = true;
  307. private bool FilterPredicate(object value)
  308. {
  309. if (GlobalFlag)
  310. return true;
  311. if (value == null)
  312. return false;
  313. var text = this.EditableTextBox.Text;
  314. if (text.Length== 0)
  315. return true;
  316. string prefix = text;
  317. return GetDisplay(value).Contains(prefix);
  318. }
  319. #endregion
  320. protected override void OnItemsSourceChanged(IEnumerable oldValue, IEnumerable newValue)
  321. {
  322. if (newValue != null)
  323. {
  324. ICollectionView view = CollectionViewSource.GetDefaultView(newValue);
  325. view.Filter += this.FilterPredicate;
  326. }
  327. if (oldValue != null)
  328. {
  329. ICollectionView view = CollectionViewSource.GetDefaultView(oldValue);
  330. view.Filter -= this.FilterPredicate;
  331. }
  332. base.OnItemsSourceChanged(oldValue, newValue);
  333. }
  334. private void TextChanged()
  335. {
  336. if (!this.IsTextSearchEnabled && !this.InEdit)
  337. {
  338. var text = this.EditableTextBox.Text??string.Empty;
  339. if (true||text.Length > 0)
  340. {
  341. GlobalFlag = false;
  342. this.RefreshFilter();
  343. //Poupup.IsOpen = true;
  344. IsDropDownOpen = true;
  345. foreach (object item in CollectionViewSource.GetDefaultView(this.ItemsSource))
  346. {
  347. string display = item.ToString();
  348. SetSelectedItem(item);
  349. if (display == text)
  350. {
  351. this.RealSelectedItem = item;
  352. }
  353. break;
  354. }
  355. }
  356. }
  357. }
  358. }
  359. }