PageRenderTime 37ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/Toolkit-development/Input/AutoCompleteBox/System/Windows/Controls/AutoCompleteBox.cs

#
C# | 2743 lines | 1451 code | 253 blank | 1039 comment | 297 complexity | 7e1681fb24864c3e26cda6cb6b797283 MD5 | raw file
  1. // (c) Copyright Microsoft Corporation.
  2. // This source is subject to the Microsoft Public License (Ms-PL).
  3. // Please see http://go.microsoft.com/fwlink/?LinkID=131993] for details.
  4. // All other rights reserved.
  5. using System;
  6. using System.Collections;
  7. using System.Collections.Generic;
  8. using System.Collections.ObjectModel;
  9. using System.Collections.Specialized;
  10. using System.Diagnostics.CodeAnalysis;
  11. using System.Globalization;
  12. using System.Linq;
  13. using System.Windows.Automation.Peers;
  14. using System.Windows.Controls.Primitives;
  15. using System.Windows.Data;
  16. using System.Windows.Input;
  17. using System.Windows.Interop;
  18. using System.Windows.Markup;
  19. using System.Windows.Media;
  20. using System.Windows.Threading;
  21. namespace System.Windows.Controls
  22. {
  23. /// <summary>
  24. /// Represents a control that provides a text box for user input and a
  25. /// drop-down that contains possible matches based on the input in the text
  26. /// box.
  27. /// </summary>
  28. /// <QualityBand>Stable</QualityBand>
  29. [TemplatePart(Name = AutoCompleteBox.ElementSelectionAdapter, Type = typeof(ISelectionAdapter))]
  30. [TemplatePart(Name = AutoCompleteBox.ElementSelector, Type = typeof(Selector))]
  31. [TemplatePart(Name = AutoCompleteBox.ElementTextBox, Type = typeof(TextBox))]
  32. [TemplatePart(Name = AutoCompleteBox.ElementPopup, Type = typeof(Popup))]
  33. [StyleTypedProperty(Property = AutoCompleteBox.ElementTextBoxStyle, StyleTargetType = typeof(TextBox))]
  34. [StyleTypedProperty(Property = AutoCompleteBox.ElementItemContainerStyle, StyleTargetType = typeof(ListBox))]
  35. [TemplateVisualState(Name = VisualStates.StateNormal, GroupName = VisualStates.GroupCommon)]
  36. [TemplateVisualState(Name = VisualStates.StateMouseOver, GroupName = VisualStates.GroupCommon)]
  37. [TemplateVisualState(Name = VisualStates.StatePressed, GroupName = VisualStates.GroupCommon)]
  38. [TemplateVisualState(Name = VisualStates.StateDisabled, GroupName = VisualStates.GroupCommon)]
  39. [TemplateVisualState(Name = VisualStates.StateFocused, GroupName = VisualStates.GroupFocus)]
  40. [TemplateVisualState(Name = VisualStates.StateUnfocused, GroupName = VisualStates.GroupFocus)]
  41. [TemplateVisualState(Name = VisualStates.StatePopupClosed, GroupName = VisualStates.GroupPopup)]
  42. [TemplateVisualState(Name = VisualStates.StatePopupOpened, GroupName = VisualStates.GroupPopup)]
  43. [TemplateVisualState(Name = VisualStates.StateValid, GroupName = VisualStates.GroupValidation)]
  44. [TemplateVisualState(Name = VisualStates.StateInvalidFocused, GroupName = VisualStates.GroupValidation)]
  45. [TemplateVisualState(Name = VisualStates.StateInvalidUnfocused, GroupName = VisualStates.GroupValidation)]
  46. [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "Large implementation keeps the components contained.")]
  47. [ContentProperty("ItemsSource")]
  48. public partial class AutoCompleteBox : Control, IUpdateVisualState
  49. {
  50. #region Template part and style names
  51. /// <summary>
  52. /// Specifies the name of the selection adapter TemplatePart.
  53. /// </summary>
  54. private const string ElementSelectionAdapter = "SelectionAdapter";
  55. /// <summary>
  56. /// Specifies the name of the Selector TemplatePart.
  57. /// </summary>
  58. private const string ElementSelector = "Selector";
  59. /// <summary>
  60. /// Specifies the name of the Popup TemplatePart.
  61. /// </summary>
  62. private const string ElementPopup = "Popup";
  63. /// <summary>
  64. /// The name for the text box part.
  65. /// </summary>
  66. private const string ElementTextBox = "Text";
  67. /// <summary>
  68. /// The name for the text box style.
  69. /// </summary>
  70. private const string ElementTextBoxStyle = "TextBoxStyle";
  71. /// <summary>
  72. /// The name for the adapter's item container style.
  73. /// </summary>
  74. private const string ElementItemContainerStyle = "ItemContainerStyle";
  75. #endregion
  76. /// <summary>
  77. /// Gets or sets a local cached copy of the items data.
  78. /// </summary>
  79. private List<object> _items;
  80. /// <summary>
  81. /// Gets or sets the observable collection that contains references to
  82. /// all of the items in the generated view of data that is provided to
  83. /// the selection-style control adapter.
  84. /// </summary>
  85. private ObservableCollection<object> _view;
  86. /// <summary>
  87. /// Gets or sets a value to ignore a number of pending change handlers.
  88. /// The value is decremented after each use. This is used to reset the
  89. /// value of properties without performing any of the actions in their
  90. /// change handlers.
  91. /// </summary>
  92. /// <remarks>The int is important as a value because the TextBox
  93. /// TextChanged event does not immediately fire, and this will allow for
  94. /// nested property changes to be ignored.</remarks>
  95. private int _ignoreTextPropertyChange;
  96. /// <summary>
  97. /// Gets or sets a value indicating whether to ignore calling a pending
  98. /// change handlers.
  99. /// </summary>
  100. private bool _ignorePropertyChange;
  101. /// <summary>
  102. /// Gets or sets a value indicating whether to ignore the selection
  103. /// changed event.
  104. /// </summary>
  105. private bool _ignoreTextSelectionChange;
  106. /// <summary>
  107. /// Gets or sets a value indicating whether to skip the text update
  108. /// processing when the selected item is updated.
  109. /// </summary>
  110. private bool _skipSelectedItemTextUpdate;
  111. /// <summary>
  112. /// Gets or sets the last observed text box selection start location.
  113. /// </summary>
  114. private int _textSelectionStart;
  115. /// <summary>
  116. /// Gets or sets a value indicating whether the user initiated the
  117. /// current populate call.
  118. /// </summary>
  119. private bool _userCalledPopulate;
  120. /// <summary>
  121. /// A value indicating whether the popup has been opened at least once.
  122. /// </summary>
  123. private bool _popupHasOpened;
  124. /// <summary>
  125. /// Gets or sets the DispatcherTimer used for the MinimumPopulateDelay
  126. /// condition for auto completion.
  127. /// </summary>
  128. private DispatcherTimer _delayTimer;
  129. /// <summary>
  130. /// Gets or sets a value indicating whether a read-only dependency
  131. /// property change handler should allow the value to be set. This is
  132. /// used to ensure that read-only properties cannot be changed via
  133. /// SetValue, etc.
  134. /// </summary>
  135. private bool _allowWrite;
  136. /// <summary>
  137. /// Gets or sets the helper that provides all of the standard
  138. /// interaction functionality. Making it internal for subclass access.
  139. /// </summary>
  140. internal InteractionHelper Interaction { get; set; }
  141. /// <summary>
  142. /// Gets or sets the BindingEvaluator, a framework element that can
  143. /// provide updated string values from a single binding.
  144. /// </summary>
  145. private BindingEvaluator<string> _valueBindingEvaluator;
  146. /// <summary>
  147. /// A weak event listener for the collection changed event.
  148. /// </summary>
  149. private WeakEventListener<AutoCompleteBox, object, NotifyCollectionChangedEventArgs> _collectionChangedWeakEventListener;
  150. #region public int MinimumPrefixLength
  151. /// <summary>
  152. /// Gets or sets the minimum number of characters required to be entered
  153. /// in the text box before the
  154. /// <see cref="T:System.Windows.Controls.AutoCompleteBox" /> displays
  155. /// possible matches.
  156. /// matches.
  157. /// </summary>
  158. /// <value>
  159. /// The minimum number of characters to be entered in the text box
  160. /// before the <see cref="T:System.Windows.Controls.AutoCompleteBox" />
  161. /// displays possible matches. The default is 1.
  162. /// </value>
  163. /// <remarks>
  164. /// If you set MinimumPrefixLength to -1, the AutoCompleteBox will
  165. /// not provide possible matches. There is no maximum value, but
  166. /// setting MinimumPrefixLength to value that is too large will
  167. /// prevent the AutoCompleteBox from providing possible matches as well.
  168. /// </remarks>
  169. public int MinimumPrefixLength
  170. {
  171. get { return (int)GetValue(MinimumPrefixLengthProperty); }
  172. set { SetValue(MinimumPrefixLengthProperty, value); }
  173. }
  174. /// <summary>
  175. /// Identifies the
  176. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.MinimumPrefixLength" />
  177. /// dependency property.
  178. /// </summary>
  179. /// <value>The identifier for the
  180. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.MinimumPrefixLength" />
  181. /// dependency property.</value>
  182. public static readonly DependencyProperty MinimumPrefixLengthProperty =
  183. DependencyProperty.Register(
  184. "MinimumPrefixLength",
  185. typeof(int),
  186. typeof(AutoCompleteBox),
  187. new PropertyMetadata(1, OnMinimumPrefixLengthPropertyChanged));
  188. /// <summary>
  189. /// MinimumPrefixLengthProperty property changed handler.
  190. /// </summary>
  191. /// <param name="d">AutoCompleteBox that changed its MinimumPrefixLength.</param>
  192. /// <param name="e">Event arguments.</param>
  193. [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly", Justification = "MinimumPrefixLength is the name of the actual dependency property.")]
  194. private static void OnMinimumPrefixLengthPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  195. {
  196. int newValue = (int)e.NewValue;
  197. if (newValue < 0 && newValue != -1)
  198. {
  199. throw new ArgumentOutOfRangeException("MinimumPrefixLength");
  200. }
  201. }
  202. #endregion public int MinimumPrefixLength
  203. #region public int MinimumPopulateDelay
  204. /// <summary>
  205. /// Gets or sets the minimum delay, in milliseconds, after text is typed
  206. /// in the text box before the
  207. /// <see cref="T:System.Windows.Controls.AutoCompleteBox" /> control
  208. /// populates the list of possible matches in the drop-down.
  209. /// </summary>
  210. /// <value>The minimum delay, in milliseconds, after text is typed in
  211. /// the text box, but before the
  212. /// <see cref="T:System.Windows.Controls.AutoCompleteBox" /> populates
  213. /// the list of possible matches in the drop-down. The default is 0.</value>
  214. /// <exception cref="T:System.ArgumentException">The set value is less than 0.</exception>
  215. public int MinimumPopulateDelay
  216. {
  217. get { return (int)GetValue(MinimumPopulateDelayProperty); }
  218. set { SetValue(MinimumPopulateDelayProperty, value); }
  219. }
  220. /// <summary>
  221. /// Identifies the
  222. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.MinimumPopulateDelay" />
  223. /// dependency property.
  224. /// </summary>
  225. /// <value>The identifier for the
  226. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.MinimumPopulateDelay" />
  227. /// dependency property.</value>
  228. public static readonly DependencyProperty MinimumPopulateDelayProperty =
  229. DependencyProperty.Register(
  230. "MinimumPopulateDelay",
  231. typeof(int),
  232. typeof(AutoCompleteBox),
  233. new PropertyMetadata(OnMinimumPopulateDelayPropertyChanged));
  234. /// <summary>
  235. /// MinimumPopulateDelayProperty property changed handler. Any current
  236. /// dispatcher timer will be stopped. The timer will not be restarted
  237. /// until the next TextUpdate call by the user.
  238. /// </summary>
  239. /// <param name="d">AutoCompleteTextBox that changed its
  240. /// MinimumPopulateDelay.</param>
  241. /// <param name="e">Event arguments.</param>
  242. [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly", Justification = "The exception is most likely to be called through the CLR property setter.")]
  243. private static void OnMinimumPopulateDelayPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  244. {
  245. AutoCompleteBox source = d as AutoCompleteBox;
  246. if (source._ignorePropertyChange)
  247. {
  248. source._ignorePropertyChange = false;
  249. return;
  250. }
  251. int newValue = (int)e.NewValue;
  252. if (newValue < 0)
  253. {
  254. source._ignorePropertyChange = true;
  255. d.SetValue(e.Property, e.OldValue);
  256. throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Properties.Resources.AutoComplete_OnMinimumPopulateDelayPropertyChanged_InvalidValue, newValue), "value");
  257. }
  258. // Stop any existing timer
  259. if (source._delayTimer != null)
  260. {
  261. source._delayTimer.Stop();
  262. if (newValue == 0)
  263. {
  264. source._delayTimer = null;
  265. }
  266. }
  267. // Create or clear a dispatcher timer instance
  268. if (newValue > 0 && source._delayTimer == null)
  269. {
  270. source._delayTimer = new DispatcherTimer();
  271. source._delayTimer.Tick += source.PopulateDropDown;
  272. }
  273. // Set the new tick interval
  274. if (newValue > 0 && source._delayTimer != null)
  275. {
  276. source._delayTimer.Interval = TimeSpan.FromMilliseconds(newValue);
  277. }
  278. }
  279. #endregion public int MinimumPopulateDelay
  280. #region public bool IsTextCompletionEnabled
  281. /// <summary>
  282. /// Gets or sets a value indicating whether the first possible match
  283. /// found during the filtering process will be displayed automatically
  284. /// in the text box.
  285. /// </summary>
  286. /// <value>
  287. /// True if the first possible match found will be displayed
  288. /// automatically in the text box; otherwise, false. The default is
  289. /// false.
  290. /// </value>
  291. public bool IsTextCompletionEnabled
  292. {
  293. get { return (bool)GetValue(IsTextCompletionEnabledProperty); }
  294. set { SetValue(IsTextCompletionEnabledProperty, value); }
  295. }
  296. /// <summary>
  297. /// Identifies the
  298. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.IsTextCompletionEnabled" />
  299. /// dependency property.
  300. /// </summary>
  301. /// <value>The identifier for the
  302. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.IsTextCompletionEnabled" />
  303. /// dependency property.</value>
  304. public static readonly DependencyProperty IsTextCompletionEnabledProperty =
  305. DependencyProperty.Register(
  306. "IsTextCompletionEnabled",
  307. typeof(bool),
  308. typeof(AutoCompleteBox),
  309. new PropertyMetadata(false, null));
  310. #endregion public bool IsTextCompletionEnabled
  311. #region public DataTemplate ItemTemplate
  312. /// <summary>
  313. /// Gets or sets the <see cref="T:System.Windows.DataTemplate" /> used
  314. /// to display each item in the drop-down portion of the control.
  315. /// </summary>
  316. /// <value>The <see cref="T:System.Windows.DataTemplate" /> used to
  317. /// display each item in the drop-down. The default is null.</value>
  318. /// <remarks>
  319. /// You use the ItemTemplate property to specify the visualization
  320. /// of the data objects in the drop-down portion of the AutoCompleteBox
  321. /// control. If your AutoCompleteBox is bound to a collection and you
  322. /// do not provide specific display instructions by using a
  323. /// DataTemplate, the resulting UI of each item is a string
  324. /// representation of each object in the underlying collection.
  325. /// </remarks>
  326. public DataTemplate ItemTemplate
  327. {
  328. get { return GetValue(ItemTemplateProperty) as DataTemplate; }
  329. set { SetValue(ItemTemplateProperty, value); }
  330. }
  331. /// <summary>
  332. /// Identifies the
  333. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.ItemTemplate" />
  334. /// dependency property.
  335. /// </summary>
  336. /// <value>The identifier for the
  337. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.ItemTemplate" />
  338. /// dependency property.</value>
  339. public static readonly DependencyProperty ItemTemplateProperty =
  340. DependencyProperty.Register(
  341. "ItemTemplate",
  342. typeof(DataTemplate),
  343. typeof(AutoCompleteBox),
  344. new PropertyMetadata(null));
  345. #endregion public DataTemplate ItemTemplate
  346. #region public Style ItemContainerStyle
  347. /// <summary>
  348. /// Gets or sets the <see cref="T:System.Windows.Style" /> that is
  349. /// applied to the selection adapter contained in the drop-down portion
  350. /// of the <see cref="T:System.Windows.Controls.AutoCompleteBox" />
  351. /// control.
  352. /// </summary>
  353. /// <value>The <see cref="T:System.Windows.Style" /> applied to the
  354. /// selection adapter contained in the drop-down portion of the
  355. /// <see cref="T:System.Windows.Controls.AutoCompleteBox" /> control.
  356. /// The default is null.</value>
  357. /// <remarks>
  358. /// The default selection adapter contained in the drop-down is a
  359. /// ListBox control.
  360. /// </remarks>
  361. public Style ItemContainerStyle
  362. {
  363. get { return GetValue(ItemContainerStyleProperty) as Style; }
  364. set { SetValue(ItemContainerStyleProperty, value); }
  365. }
  366. /// <summary>
  367. /// Identifies the
  368. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.ItemContainerStyle" />
  369. /// dependency property.
  370. /// </summary>
  371. /// <value>The identifier for the
  372. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.ItemContainerStyle" />
  373. /// dependency property.</value>
  374. public static readonly DependencyProperty ItemContainerStyleProperty =
  375. DependencyProperty.Register(
  376. ElementItemContainerStyle,
  377. typeof(Style),
  378. typeof(AutoCompleteBox),
  379. new PropertyMetadata(null, null));
  380. #endregion public Style ItemContainerStyle
  381. #region public Style TextBoxStyle
  382. /// <summary>
  383. /// Gets or sets the <see cref="T:System.Windows.Style" /> applied to
  384. /// the text box portion of the
  385. /// <see cref="T:System.Windows.Controls.AutoCompleteBox" /> control.
  386. /// </summary>
  387. /// <value>The <see cref="T:System.Windows.Style" /> applied to the text
  388. /// box portion of the
  389. /// <see cref="T:System.Windows.Controls.AutoCompleteBox" /> control.
  390. /// The default is null.</value>
  391. public Style TextBoxStyle
  392. {
  393. get { return GetValue(TextBoxStyleProperty) as Style; }
  394. set { SetValue(TextBoxStyleProperty, value); }
  395. }
  396. /// <summary>
  397. /// Identifies the
  398. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.TextBoxStyle" />
  399. /// dependency property.
  400. /// </summary>
  401. /// <value>The identifier for the
  402. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.TextBoxStyle" />
  403. /// dependency property.</value>
  404. public static readonly DependencyProperty TextBoxStyleProperty =
  405. DependencyProperty.Register(
  406. ElementTextBoxStyle,
  407. typeof(Style),
  408. typeof(AutoCompleteBox),
  409. new PropertyMetadata(null));
  410. #endregion public Style TextBoxStyle
  411. #region public double MaxDropDownHeight
  412. /// <summary>
  413. /// Gets or sets the maximum height of the drop-down portion of the
  414. /// <see cref="T:System.Windows.Controls.AutoCompleteBox" /> control.
  415. /// </summary>
  416. /// <value>The maximum height of the drop-down portion of the
  417. /// <see cref="T:System.Windows.Controls.AutoCompleteBox" /> control.
  418. /// The default is <see cref="F:System.Double.PositiveInfinity" />.</value>
  419. /// <exception cref="T:System.ArgumentException">The specified value is less than 0.</exception>
  420. public double MaxDropDownHeight
  421. {
  422. get { return (double)GetValue(MaxDropDownHeightProperty); }
  423. set { SetValue(MaxDropDownHeightProperty, value); }
  424. }
  425. /// <summary>
  426. /// Identifies the
  427. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.MaxDropDownHeight" />
  428. /// dependency property.
  429. /// </summary>
  430. /// <value>The identifier for the
  431. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.MaxDropDownHeight" />
  432. /// dependency property.</value>
  433. public static readonly DependencyProperty MaxDropDownHeightProperty =
  434. DependencyProperty.Register(
  435. "MaxDropDownHeight",
  436. typeof(double),
  437. typeof(AutoCompleteBox),
  438. new PropertyMetadata(double.PositiveInfinity, OnMaxDropDownHeightPropertyChanged));
  439. /// <summary>
  440. /// MaxDropDownHeightProperty property changed handler.
  441. /// </summary>
  442. /// <param name="d">AutoCompleteTextBox that changed its MaxDropDownHeight.</param>
  443. /// <param name="e">Event arguments.</param>
  444. [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly", Justification = "The exception will be called through a CLR setter in most cases.")]
  445. private static void OnMaxDropDownHeightPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  446. {
  447. AutoCompleteBox source = d as AutoCompleteBox;
  448. if (source._ignorePropertyChange)
  449. {
  450. source._ignorePropertyChange = false;
  451. return;
  452. }
  453. double newValue = (double)e.NewValue;
  454. // Revert to the old value if invalid (negative)
  455. if (newValue < 0)
  456. {
  457. source._ignorePropertyChange = true;
  458. source.SetValue(e.Property, e.OldValue);
  459. throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Properties.Resources.AutoComplete_OnMaxDropDownHeightPropertyChanged_InvalidValue, e.NewValue), "value");
  460. }
  461. source.OnMaxDropDownHeightChanged(newValue);
  462. }
  463. #endregion public double MaxDropDownHeight
  464. #region public bool IsDropDownOpen
  465. /// <summary>
  466. /// Gets or sets a value indicating whether the drop-down portion of
  467. /// the control is open.
  468. /// </summary>
  469. /// <value>
  470. /// True if the drop-down is open; otherwise, false. The default is
  471. /// false.
  472. /// </value>
  473. public bool IsDropDownOpen
  474. {
  475. get { return (bool)GetValue(IsDropDownOpenProperty); }
  476. set { SetValue(IsDropDownOpenProperty, value); }
  477. }
  478. /// <summary>
  479. /// Identifies the
  480. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.IsDropDownOpen" />
  481. /// dependency property.
  482. /// </summary>
  483. /// <value>The identifier for the
  484. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.IsDropDownOpen" />
  485. /// dependency property.</value>
  486. public static readonly DependencyProperty IsDropDownOpenProperty =
  487. DependencyProperty.Register(
  488. "IsDropDownOpen",
  489. typeof(bool),
  490. typeof(AutoCompleteBox),
  491. new PropertyMetadata(false, OnIsDropDownOpenPropertyChanged));
  492. /// <summary>
  493. /// IsDropDownOpenProperty property changed handler.
  494. /// </summary>
  495. /// <param name="d">AutoCompleteTextBox that changed its IsDropDownOpen.</param>
  496. /// <param name="e">Event arguments.</param>
  497. private static void OnIsDropDownOpenPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  498. {
  499. AutoCompleteBox source = d as AutoCompleteBox;
  500. // Ignore the change if requested
  501. if (source._ignorePropertyChange)
  502. {
  503. source._ignorePropertyChange = false;
  504. return;
  505. }
  506. bool oldValue = (bool)e.OldValue;
  507. bool newValue = (bool)e.NewValue;
  508. if (newValue)
  509. {
  510. source.TextUpdated(source.Text, true);
  511. }
  512. else
  513. {
  514. source.ClosingDropDown(oldValue);
  515. }
  516. source.UpdateVisualState(true);
  517. }
  518. #endregion public bool IsDropDownOpen
  519. #region public IEnumerable ItemsSource
  520. /// <summary>
  521. /// Gets or sets a collection that is used to generate the items for the
  522. /// drop-down portion of the
  523. /// <see cref="T:System.Windows.Controls.AutoCompleteBox" /> control.
  524. /// </summary>
  525. /// <value>The collection that is used to generate the items of the
  526. /// drop-down portion of the
  527. /// <see cref="T:System.Windows.Controls.AutoCompleteBox" /> control.</value>
  528. public IEnumerable ItemsSource
  529. {
  530. get { return GetValue(ItemsSourceProperty) as IEnumerable; }
  531. set { SetValue(ItemsSourceProperty, value); }
  532. }
  533. /// <summary>
  534. /// Identifies the
  535. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.ItemsSource" />
  536. /// dependency property.
  537. /// </summary>
  538. /// <value>The identifier for the
  539. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.ItemsSource" />
  540. /// dependency property.</value>
  541. public static readonly DependencyProperty ItemsSourceProperty =
  542. DependencyProperty.Register(
  543. "ItemsSource",
  544. typeof(IEnumerable),
  545. typeof(AutoCompleteBox),
  546. new PropertyMetadata(OnItemsSourcePropertyChanged));
  547. /// <summary>
  548. /// ItemsSourceProperty property changed handler.
  549. /// </summary>
  550. /// <param name="d">AutoCompleteBox that changed its ItemsSource.</param>
  551. /// <param name="e">Event arguments.</param>
  552. private static void OnItemsSourcePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  553. {
  554. AutoCompleteBox autoComplete = d as AutoCompleteBox;
  555. autoComplete.OnItemsSourceChanged((IEnumerable)e.OldValue, (IEnumerable)e.NewValue);
  556. }
  557. #endregion public IEnumerable ItemsSource
  558. #region public object SelectedItem
  559. /// <summary>
  560. /// Gets or sets the selected item in the drop-down.
  561. /// </summary>
  562. /// <value>The selected item in the drop-down.</value>
  563. /// <remarks>
  564. /// If the IsTextCompletionEnabled property is true and text typed by
  565. /// the user matches an item in the ItemsSource collection, which is
  566. /// then displayed in the text box, the SelectedItem property will be
  567. /// a null reference.
  568. /// </remarks>
  569. public object SelectedItem
  570. {
  571. get { return GetValue(SelectedItemProperty) as object; }
  572. set { SetValue(SelectedItemProperty, value); }
  573. }
  574. /// <summary>
  575. /// Identifies the
  576. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.SelectedItem" />
  577. /// dependency property.
  578. /// </summary>
  579. /// <value>The identifier the
  580. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.SelectedItem" />
  581. /// dependency property.</value>
  582. public static readonly DependencyProperty SelectedItemProperty =
  583. DependencyProperty.Register(
  584. "SelectedItem",
  585. typeof(object),
  586. typeof(AutoCompleteBox),
  587. new PropertyMetadata(OnSelectedItemPropertyChanged));
  588. /// <summary>
  589. /// SelectedItemProperty property changed handler. Fires the
  590. /// SelectionChanged event. The event data will contain any non-null
  591. /// removed items and non-null additions.
  592. /// </summary>
  593. /// <param name="d">AutoCompleteBox that changed its SelectedItem.</param>
  594. /// <param name="e">Event arguments.</param>
  595. private static void OnSelectedItemPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  596. {
  597. AutoCompleteBox source = d as AutoCompleteBox;
  598. if (source._ignorePropertyChange)
  599. {
  600. source._ignorePropertyChange = false;
  601. return;
  602. }
  603. // Update the text display
  604. if (source._skipSelectedItemTextUpdate)
  605. {
  606. source._skipSelectedItemTextUpdate = false;
  607. }
  608. else
  609. {
  610. source.OnSelectedItemChanged(e.NewValue);
  611. }
  612. // Fire the SelectionChanged event
  613. List<object> removed = new List<object>();
  614. if (e.OldValue != null)
  615. {
  616. removed.Add(e.OldValue);
  617. }
  618. List<object> added = new List<object>();
  619. if (e.NewValue != null)
  620. {
  621. added.Add(e.NewValue);
  622. }
  623. source.OnSelectionChanged(new SelectionChangedEventArgs(
  624. #if !SILVERLIGHT
  625. SelectionChangedEvent,
  626. #endif
  627. removed,
  628. added));
  629. }
  630. /// <summary>
  631. /// Called when the selected item is changed, updates the text value
  632. /// that is displayed in the text box part.
  633. /// </summary>
  634. /// <param name="newItem">The new item.</param>
  635. private void OnSelectedItemChanged(object newItem)
  636. {
  637. string text;
  638. if (newItem == null)
  639. {
  640. text = SearchText;
  641. }
  642. else
  643. {
  644. text = FormatValue(newItem, true);
  645. }
  646. // Update the Text property and the TextBox values
  647. UpdateTextValue(text);
  648. // Move the caret to the end of the text box
  649. if (TextBox != null && Text != null)
  650. {
  651. TextBox.SelectionStart = Text.Length;
  652. }
  653. }
  654. #endregion public object SelectedItem
  655. #region public string Text
  656. /// <summary>
  657. /// Gets or sets the text in the text box portion of the
  658. /// <see cref="T:System.Windows.Controls.AutoCompleteBox" /> control.
  659. /// </summary>
  660. /// <value>The text in the text box portion of the
  661. /// <see cref="T:System.Windows.Controls.AutoCompleteBox" /> control.</value>
  662. public string Text
  663. {
  664. get { return GetValue(TextProperty) as string; }
  665. set { SetValue(TextProperty, value); }
  666. }
  667. /// <summary>
  668. /// Identifies the
  669. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.Text" />
  670. /// dependency property.
  671. /// </summary>
  672. /// <value>The identifier for the
  673. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.Text" />
  674. /// dependency property.</value>
  675. public static readonly DependencyProperty TextProperty =
  676. DependencyProperty.Register(
  677. "Text",
  678. typeof(string),
  679. typeof(AutoCompleteBox),
  680. new PropertyMetadata(string.Empty, OnTextPropertyChanged));
  681. /// <summary>
  682. /// TextProperty property changed handler.
  683. /// </summary>
  684. /// <param name="d">AutoCompleteBox that changed its Text.</param>
  685. /// <param name="e">Event arguments.</param>
  686. private static void OnTextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  687. {
  688. AutoCompleteBox source = d as AutoCompleteBox;
  689. source.TextUpdated((string)e.NewValue, false);
  690. }
  691. #endregion public string Text
  692. #region public string SearchText
  693. /// <summary>
  694. /// Gets the text that is used to filter items in the
  695. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.ItemsSource" />
  696. /// item collection.
  697. /// </summary>
  698. /// <value>The text that is used to filter items in the
  699. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.ItemsSource" />
  700. /// item collection.</value>
  701. /// <remarks>
  702. /// The SearchText value is typically the same as the
  703. /// Text property, but is set after the TextChanged event occurs
  704. /// and before the Populating event.
  705. /// </remarks>
  706. public string SearchText
  707. {
  708. get { return (string)GetValue(SearchTextProperty); }
  709. private set
  710. {
  711. try
  712. {
  713. _allowWrite = true;
  714. SetValue(SearchTextProperty, value);
  715. }
  716. finally
  717. {
  718. _allowWrite = false;
  719. }
  720. }
  721. }
  722. /// <summary>
  723. /// Identifies the
  724. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.SearchText" />
  725. /// dependency property.
  726. /// </summary>
  727. /// <value>The identifier for the
  728. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.SearchText" />
  729. /// dependency property.</value>
  730. public static readonly DependencyProperty SearchTextProperty =
  731. DependencyProperty.Register(
  732. "SearchText",
  733. typeof(string),
  734. typeof(AutoCompleteBox),
  735. new PropertyMetadata(string.Empty, OnSearchTextPropertyChanged));
  736. /// <summary>
  737. /// OnSearchTextProperty property changed handler.
  738. /// </summary>
  739. /// <param name="d">AutoCompleteBox that changed its SearchText.</param>
  740. /// <param name="e">Event arguments.</param>
  741. private static void OnSearchTextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  742. {
  743. AutoCompleteBox source = d as AutoCompleteBox;
  744. if (source._ignorePropertyChange)
  745. {
  746. source._ignorePropertyChange = false;
  747. return;
  748. }
  749. // Ensure the property is only written when expected
  750. if (!source._allowWrite)
  751. {
  752. // Reset the old value before it was incorrectly written
  753. source._ignorePropertyChange = true;
  754. source.SetValue(e.Property, e.OldValue);
  755. throw new InvalidOperationException(Properties.Resources.AutoComplete_OnSearchTextPropertyChanged_InvalidWrite);
  756. }
  757. }
  758. #endregion public string SearchText
  759. #region public AutoCompleteFilterMode FilterMode
  760. /// <summary>
  761. /// Gets or sets how the text in the text box is used to filter items
  762. /// specified by the
  763. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.ItemsSource" />
  764. /// property for display in the drop-down.
  765. /// </summary>
  766. /// <value>One of the
  767. /// <see cref="T:System.Windows.Controls.AutoCompleteFilterMode" />
  768. /// values The default is
  769. /// <see cref="F:System.Windows.Controls.AutoCompleteFilterMode.StartsWith" />.</value>
  770. /// <exception cref="T:System.ArgumentException">The specified value is
  771. /// not a valid
  772. /// <see cref="T:System.Windows.Controls.AutoCompleteFilterMode" />.</exception>
  773. /// <remarks>
  774. /// Use the FilterMode property to specify how possible matches are
  775. /// filtered. For example, possible matches can be filtered in a
  776. /// predefined or custom way. The search mode is automatically set to
  777. /// Custom if you set the ItemFilter property.
  778. /// </remarks>
  779. public AutoCompleteFilterMode FilterMode
  780. {
  781. get { return (AutoCompleteFilterMode)GetValue(FilterModeProperty); }
  782. set { SetValue(FilterModeProperty, value); }
  783. }
  784. /// <summary>
  785. /// Gets the identifier for the
  786. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.FilterMode" />
  787. /// dependency property.
  788. /// </summary>
  789. public static readonly DependencyProperty FilterModeProperty =
  790. DependencyProperty.Register(
  791. "FilterMode",
  792. typeof(AutoCompleteFilterMode),
  793. typeof(AutoCompleteBox),
  794. new PropertyMetadata(AutoCompleteFilterMode.StartsWith, OnFilterModePropertyChanged));
  795. /// <summary>
  796. /// FilterModeProperty property changed handler.
  797. /// </summary>
  798. /// <param name="d">AutoCompleteBox that changed its FilterMode.</param>
  799. /// <param name="e">Event arguments.</param>
  800. [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly", Justification = "The exception will be thrown when the CLR setter is used in most situations.")]
  801. private static void OnFilterModePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  802. {
  803. AutoCompleteBox source = d as AutoCompleteBox;
  804. AutoCompleteFilterMode mode = (AutoCompleteFilterMode)e.NewValue;
  805. if (mode != AutoCompleteFilterMode.Contains &&
  806. mode != AutoCompleteFilterMode.ContainsCaseSensitive &&
  807. mode != AutoCompleteFilterMode.ContainsOrdinal &&
  808. mode != AutoCompleteFilterMode.ContainsOrdinalCaseSensitive &&
  809. mode != AutoCompleteFilterMode.Custom &&
  810. mode != AutoCompleteFilterMode.Equals &&
  811. mode != AutoCompleteFilterMode.EqualsCaseSensitive &&
  812. mode != AutoCompleteFilterMode.EqualsOrdinal &&
  813. mode != AutoCompleteFilterMode.EqualsOrdinalCaseSensitive &&
  814. mode != AutoCompleteFilterMode.None &&
  815. mode != AutoCompleteFilterMode.StartsWith &&
  816. mode != AutoCompleteFilterMode.StartsWithCaseSensitive &&
  817. mode != AutoCompleteFilterMode.StartsWithOrdinal &&
  818. mode != AutoCompleteFilterMode.StartsWithOrdinalCaseSensitive)
  819. {
  820. source.SetValue(e.Property, e.OldValue);
  821. throw new ArgumentException(Properties.Resources.AutoComplete_OnFilterModePropertyChanged_InvalidValue, "value");
  822. }
  823. // Sets the filter predicate for the new value
  824. AutoCompleteFilterMode newValue = (AutoCompleteFilterMode)e.NewValue;
  825. source.TextFilter = AutoCompleteSearch.GetFilter(newValue);
  826. }
  827. #endregion public AutoCompleteFilterMode FilterMode
  828. #region public AutoCompleteFilterPredicate ItemFilter
  829. /// <summary>
  830. /// Gets or sets the custom method that uses user-entered text to filter
  831. /// the items specified by the
  832. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.ItemsSource" />
  833. /// property for display in the drop-down.
  834. /// </summary>
  835. /// <value>The custom method that uses the user-entered text to filter
  836. /// the items specified by the
  837. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.ItemsSource" />
  838. /// property. The default is null.</value>
  839. /// <remarks>
  840. /// The filter mode is automatically set to Custom if you set the
  841. /// ItemFilter property.
  842. /// </remarks>
  843. public AutoCompleteFilterPredicate<object> ItemFilter
  844. {
  845. get { return GetValue(ItemFilterProperty) as AutoCompleteFilterPredicate<object>; }
  846. set { SetValue(ItemFilterProperty, value); }
  847. }
  848. /// <summary>
  849. /// Identifies the
  850. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.ItemFilter" />
  851. /// dependency property.
  852. /// </summary>
  853. /// <value>The identifier for the
  854. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.ItemFilter" />
  855. /// dependency property.</value>
  856. public static readonly DependencyProperty ItemFilterProperty =
  857. DependencyProperty.Register(
  858. "ItemFilter",
  859. typeof(AutoCompleteFilterPredicate<object>),
  860. typeof(AutoCompleteBox),
  861. new PropertyMetadata(OnItemFilterPropertyChanged));
  862. /// <summary>
  863. /// ItemFilterProperty property changed handler.
  864. /// </summary>
  865. /// <param name="d">AutoCompleteBox that changed its ItemFilter.</param>
  866. /// <param name="e">Event arguments.</param>
  867. private static void OnItemFilterPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  868. {
  869. AutoCompleteBox source = d as AutoCompleteBox;
  870. AutoCompleteFilterPredicate<object> value = e.NewValue as AutoCompleteFilterPredicate<object>;
  871. // If null, revert to the "None" predicate
  872. if (value == null)
  873. {
  874. source.FilterMode = AutoCompleteFilterMode.None;
  875. }
  876. else
  877. {
  878. source.FilterMode = AutoCompleteFilterMode.Custom;
  879. source.TextFilter = null;
  880. }
  881. }
  882. #endregion public AutoCompleteFilterPredicate ItemFilter
  883. #region public AutoCompleteStringFilterPredicate TextFilter
  884. /// <summary>
  885. /// Gets or sets the custom method that uses the user-entered text to
  886. /// filter items specified by the
  887. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.ItemsSource" />
  888. /// property in a text-based way for display in the drop-down.
  889. /// </summary>
  890. /// <value>The custom method that uses the user-entered text to filter
  891. /// items specified by the
  892. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.ItemsSource" />
  893. /// property in a text-based way for display in the drop-down.</value>
  894. /// <remarks>
  895. /// The search mode is automatically set to Custom if you set the
  896. /// TextFilter property.
  897. /// </remarks>
  898. public AutoCompleteFilterPredicate<string> TextFilter
  899. {
  900. get { return GetValue(TextFilterProperty) as AutoCompleteFilterPredicate<string>; }
  901. set { SetValue(TextFilterProperty, value); }
  902. }
  903. /// <summary>
  904. /// Identifies the
  905. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.TextFilter" />
  906. /// dependency property.
  907. /// </summary>
  908. /// <value>The identifier for the
  909. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.TextFilter" />
  910. /// dependency property.</value>
  911. public static readonly DependencyProperty TextFilterProperty =
  912. DependencyProperty.Register(
  913. "TextFilter",
  914. typeof(AutoCompleteFilterPredicate<string>),
  915. typeof(AutoCompleteBox),
  916. new PropertyMetadata(AutoCompleteSearch.GetFilter(AutoCompleteFilterMode.StartsWith)));
  917. #endregion public AutoCompleteStringFilterPredicate TextFilter
  918. #region Template parts
  919. /// <summary>
  920. /// Gets or sets the drop down popup control.
  921. /// </summary>
  922. private PopupHelper DropDownPopup { get; set; }
  923. /// <summary>
  924. /// The TextBox template part.
  925. /// </summary>
  926. private TextBox _text;
  927. /// <summary>
  928. /// The SelectionAdapter.
  929. /// </summary>
  930. private ISelectionAdapter _adapter;
  931. /// <summary>
  932. /// Gets or sets the Text template part.
  933. /// </summary>
  934. internal TextBox TextBox
  935. {
  936. get { return _text; }
  937. set
  938. {
  939. // Detach existing handlers
  940. if (_text != null)
  941. {
  942. _text.SelectionChanged -= OnTextBoxSelectionChanged;
  943. _text.TextChanged -= OnTextBoxTextChanged;
  944. }
  945. _text = value;
  946. // Attach handlers
  947. if (_text != null)
  948. {
  949. _text.SelectionChanged += OnTextBoxSelectionChanged;
  950. _text.TextChanged += OnTextBoxTextChanged;
  951. if (Text != null)
  952. {
  953. UpdateTextValue(Text);
  954. }
  955. }
  956. }
  957. }
  958. /// <summary>
  959. /// Gets or sets the selection adapter used to populate the drop-down
  960. /// with a list of selectable items.
  961. /// </summary>
  962. /// <value>The selection adapter used to populate the drop-down with a
  963. /// list of selectable items.</value>
  964. /// <remarks>
  965. /// You can use this property when you create an automation peer to
  966. /// use with AutoCompleteBox or deriving from AutoCompleteBox to
  967. /// create a custom control.
  968. /// </remarks>
  969. protected internal ISelectionAdapter SelectionAdapter
  970. {
  971. get { return _adapter; }
  972. set
  973. {
  974. if (_adapter != null)
  975. {
  976. _adapter.SelectionChanged -= OnAdapterSelectionChanged;
  977. _adapter.Commit -= OnAdapterSelectionComplete;
  978. _adapter.Cancel -= OnAdapterSelectionCanceled;
  979. _adapter.Cancel -= OnAdapterSelectionComplete;
  980. _adapter.ItemsSource = null;
  981. }
  982. _adapter = value;
  983. if (_adapter != null)
  984. {
  985. _adapter.SelectionChanged += OnAdapterSelectionChanged;
  986. _adapter.Commit += OnAdapterSelectionComplete;
  987. _adapter.Cancel += OnAdapterSelectionCanceled;
  988. _adapter.Cancel += OnAdapterSelectionComplete;
  989. _adapter.ItemsSource = _view;
  990. }
  991. }
  992. }
  993. #endregion
  994. /// <summary>
  995. /// Occurs when the text in the text box portion of the
  996. /// <see cref="T:System.Windows.Controls.AutoCompleteBox" /> changes.
  997. /// </summary>
  998. #if SILVERLIGHT
  999. public event RoutedEventHandler TextChanged;
  1000. #else
  1001. public static readonly RoutedEvent TextChangedEvent = EventManager.RegisterRoutedEvent("TextChanged", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(AutoCompleteBox));
  1002. /// <summary>
  1003. /// Occurs when the text in the text box portion of the
  1004. /// <see cref="T:System.Windows.Controls.AutoCompleteBox" /> changes.
  1005. /// </summary>
  1006. public event RoutedEventHandler TextChanged
  1007. {
  1008. add { AddHandler(TextChangedEvent, value); }
  1009. remove { RemoveHandler(TextChangedEvent, value); }
  1010. }
  1011. #endif
  1012. /// <summary>
  1013. /// Occurs when the
  1014. /// <see cref="T:System.Windows.Controls.AutoCompleteBox" /> is
  1015. /// populating the drop-down with possible matches based on the
  1016. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.Text" />
  1017. /// property.
  1018. /// </summary>
  1019. /// <remarks>
  1020. /// If the event is canceled, by setting the PopulatingEventArgs.Cancel
  1021. /// property to true, the AutoCompleteBox will not automatically
  1022. /// populate the selection adapter contained in the drop-down.
  1023. /// In this case, if you want possible matches to appear, you must
  1024. /// provide the logic for populating the selection adapter.
  1025. /// </remarks>
  1026. #if SILVERLIGHT
  1027. public event PopulatingEventHandler Populating;
  1028. #else
  1029. public static readonly RoutedEvent PopulatingEvent = EventManager.RegisterRoutedEvent("Populating", RoutingStrategy.Bubble, typeof(PopulatingEventHandler), typeof(AutoCompleteBox));
  1030. /// <summary>
  1031. /// Occurs when the
  1032. /// <see cref="T:System.Windows.Controls.AutoCompleteBox" /> is
  1033. /// populating the drop-down with possible matches based on the
  1034. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.Text" />
  1035. /// property.
  1036. /// </summary>
  1037. /// <remarks>
  1038. /// If the event is canceled, by setting the PopulatingEventArgs.Cancel
  1039. /// property to true, the AutoCompleteBox will not automatically
  1040. /// populate the selection adapter contained in the drop-down.
  1041. /// In this case, if you want possible matches to appear, you must
  1042. /// provide the logic for populating the selection adapter.
  1043. /// </remarks>
  1044. public event PopulatingEventHandler Populating
  1045. {
  1046. add { AddHandler(PopulatingEvent, value); }
  1047. remove { RemoveHandler(PopulatingEvent, value); }
  1048. }
  1049. #endif
  1050. /// <summary>
  1051. /// Occurs when the
  1052. /// <see cref="T:System.Windows.Controls.AutoCompleteBox" /> has
  1053. /// populated the drop-down with possible matches based on the
  1054. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.Text" />
  1055. /// property.
  1056. /// </summary>
  1057. #if SILVERLIGHT
  1058. public event PopulatedEventHandler Populated;
  1059. #else
  1060. public static readonly RoutedEvent PopulatedEvent = EventManager.RegisterRoutedEvent("Populated", RoutingStrategy.Bubble, typeof(PopulatedEventHandler), typeof(AutoCompleteBox));
  1061. /// <summary>
  1062. /// Occurs when the
  1063. /// <see cref="T:System.Windows.Controls.AutoCompleteBox" /> has
  1064. /// populated the drop-down with possible matches based on the
  1065. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.Text" />
  1066. /// property.
  1067. /// </summary>
  1068. public event PopulatedEventHandler Populated
  1069. {
  1070. add { AddHandler(PopulatedEvent, value); }
  1071. remove { RemoveHandler(PopulatedEvent, value); }
  1072. }
  1073. #endif
  1074. /// <summary>
  1075. /// Occurs when the value of the
  1076. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.IsDropDownOpen" />
  1077. /// property is changing from false to true.
  1078. /// </summary>
  1079. #if SILVERLIGHT
  1080. public event RoutedPropertyChangingEventHandler<bool> DropDownOpening;
  1081. #else
  1082. public static readonly RoutedEvent DropDownOpeningEvent = EventManager.RegisterRoutedEvent("DropDownOpening", RoutingStrategy.Bubble, typeof(RoutedPropertyChangingEventHandler<bool>), typeof(AutoCompleteBox));
  1083. /// <summary>
  1084. /// Occurs when the value of the
  1085. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.IsDropDownOpen" />
  1086. /// property is changing from false to true.
  1087. /// </summary>
  1088. public event RoutedPropertyChangingEventHandler<bool> DropDownOpening
  1089. {
  1090. add { AddHandler(PopulatedEvent, value); }
  1091. remove { RemoveHandler(PopulatedEvent, value); }
  1092. }
  1093. #endif
  1094. /// <summary>
  1095. /// Occurs when the value of the
  1096. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.IsDropDownOpen" />
  1097. /// property has changed from false to true and the drop-down is open.
  1098. /// </summary>
  1099. #if SILVERLIGHT
  1100. public event RoutedPropertyChangedEventHandler<bool> DropDownOpened;
  1101. #else
  1102. public static readonly RoutedEvent DropDownOpenedEvent = EventManager.RegisterRoutedEvent("DropDownOpened", RoutingStrategy.Bubble, typeof(RoutedPropertyChangedEventHandler<bool>), typeof(AutoCompleteBox));
  1103. /// <summary>
  1104. /// Occurs when the value of the
  1105. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.IsDropDownOpen" />
  1106. /// property has changed from false to true and the drop-down is open.
  1107. /// </summary>
  1108. public event RoutedPropertyChangedEventHandler<bool> DropDownOpened
  1109. {
  1110. add { AddHandler(DropDownOpenedEvent, value); }
  1111. remove { RemoveHandler(DropDownOpenedEvent, value); }
  1112. }
  1113. #endif
  1114. /// <summary>
  1115. /// Occurs when the
  1116. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.IsDropDownOpen" />
  1117. /// property is changing from true to false.
  1118. /// </summary>
  1119. #if SILVERLIGHT
  1120. public event RoutedPropertyChangingEventHandler<bool> DropDownClosing;
  1121. #else
  1122. public static readonly RoutedEvent DropDownClosingEvent = EventManager.RegisterRoutedEvent("DropDownClosing", RoutingStrategy.Bubble, typeof(RoutedPropertyChangingEventHandler<bool>), typeof(AutoCompleteBox));
  1123. /// <summary>
  1124. /// Occurs when the
  1125. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.IsDropDownOpen" />
  1126. /// property is changing from true to false.
  1127. /// </summary>
  1128. public event RoutedPropertyChangingEventHandler<bool> DropDownClosing
  1129. {
  1130. add { AddHandler(DropDownClosingEvent, value); }
  1131. remove { RemoveHandler(DropDownClosingEvent, value); }
  1132. }
  1133. #endif
  1134. /// <summary>
  1135. /// Occurs when the
  1136. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.IsDropDownOpen" />
  1137. /// property was changed from true to false and the drop-down is open.
  1138. /// </summary>
  1139. #if SILVERLIGHT
  1140. public event RoutedPropertyChangedEventHandler<bool> DropDownClosed;
  1141. #else
  1142. public static readonly RoutedEvent DropDownClosedEvent = EventManager.RegisterRoutedEvent("DropDownClosed", RoutingStrategy.Bubble, typeof(RoutedPropertyChangedEventHandler<bool>), typeof(AutoCompleteBox));
  1143. /// <summary>
  1144. /// Occurs when the
  1145. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.IsDropDownOpen" />
  1146. /// property was changed from true to false and the drop-down is open.
  1147. /// </summary>
  1148. public event RoutedPropertyChangedEventHandler<bool> DropDownClosed
  1149. {
  1150. add { AddHandler(DropDownClosedEvent, value); }
  1151. remove { RemoveHandler(DropDownClosedEvent, value); }
  1152. }
  1153. #endif
  1154. /// <summary>
  1155. /// Occurs when the selected item in the drop-down portion of the
  1156. /// <see cref="T:System.Windows.Controls.AutoCompleteBox" /> has
  1157. /// changed.
  1158. /// </summary>
  1159. #if SILVERLIGHT
  1160. public event SelectionChangedEventHandler SelectionChanged;
  1161. #else
  1162. public static readonly RoutedEvent SelectionChangedEvent = EventManager.RegisterRoutedEvent("SelectionChanged", RoutingStrategy.Bubble, typeof(SelectionChangedEventHandler), typeof(AutoCompleteBox));
  1163. /// <summary>
  1164. /// Occurs when the selected item in the drop-down portion of the
  1165. /// <see cref="T:System.Windows.Controls.AutoCompleteBox" /> has
  1166. /// changed.
  1167. /// </summary>
  1168. public event SelectionChangedEventHandler SelectionChanged
  1169. {
  1170. add { AddHandler(SelectionChangedEvent, value); }
  1171. remove { RemoveHandler(SelectionChangedEvent, value); }
  1172. }
  1173. #endif
  1174. /// <summary>
  1175. /// Gets or sets the <see cref="T:System.Windows.Data.Binding" /> that
  1176. /// is used to get the values for display in the text portion of
  1177. /// the <see cref="T:System.Windows.Controls.AutoCompleteBox" />
  1178. /// control.
  1179. /// </summary>
  1180. /// <value>The <see cref="T:System.Windows.Data.Binding" /> object used
  1181. /// when binding to a collection property.</value>
  1182. public Binding ValueMemberBinding
  1183. {
  1184. get
  1185. {
  1186. return _valueBindingEvaluator != null ? _valueBindingEvaluator.ValueBinding : null;
  1187. }
  1188. set
  1189. {
  1190. _valueBindingEvaluator = new BindingEvaluator<string>(value);
  1191. }
  1192. }
  1193. /// <summary>
  1194. /// Gets or sets the property path that is used to get values for
  1195. /// display in the text portion of the
  1196. /// <see cref="T:System.Windows.Controls.AutoCompleteBox" /> control.
  1197. /// </summary>
  1198. /// <value>The property path that is used to get values for display in
  1199. /// the text portion of the
  1200. /// <see cref="T:System.Windows.Controls.AutoCompleteBox" /> control.</value>
  1201. public string ValueMemberPath
  1202. {
  1203. get
  1204. {
  1205. return (ValueMemberBinding != null) ? ValueMemberBinding.Path.Path : null;
  1206. }
  1207. set
  1208. {
  1209. ValueMemberBinding = value == null ? null : new Binding(value);
  1210. }
  1211. }
  1212. #if !SILVERLIGHT
  1213. /// <summary>
  1214. /// Initializes the static members of the
  1215. /// <see cref="T:System.Windows.Controls.AutoCompleteBox" /> class.
  1216. /// </summary>
  1217. static AutoCompleteBox()
  1218. {
  1219. DefaultStyleKeyProperty.OverrideMetadata(typeof(AutoCompleteBox), new FrameworkPropertyMetadata(typeof(AutoCompleteBox)));
  1220. }
  1221. #endif
  1222. /// <summary>
  1223. /// Initializes a new instance of the
  1224. /// <see cref="T:System.Windows.Controls.AutoCompleteBox" /> class.
  1225. /// </summary>
  1226. public AutoCompleteBox()
  1227. {
  1228. #if SILVERLIGHT
  1229. DefaultStyleKey = typeof(AutoCompleteBox);
  1230. Loaded += (sender, e) => ApplyTemplate();
  1231. #endif
  1232. IsEnabledChanged += ControlIsEnabledChanged;
  1233. Interaction = new InteractionHelper(this);
  1234. // Creating the view here ensures that View is always != null
  1235. ClearView();
  1236. }
  1237. /// <summary>
  1238. /// Arranges and sizes the
  1239. /// <see cref="T:System.Windows.Controls.AutoCompleteBox" />
  1240. /// control and its contents.
  1241. /// </summary>
  1242. /// <param name="finalSize">The size allowed for the
  1243. /// <see cref="T:System.Windows.Controls.AutoCompleteBox" /> control.</param>
  1244. /// <returns>The <paramref name="finalSize" />, unchanged.</returns>
  1245. protected override Size ArrangeOverride(Size finalSize)
  1246. {
  1247. Size r = base.ArrangeOverride(finalSize);
  1248. if (DropDownPopup != null)
  1249. {
  1250. DropDownPopup.Arrange();
  1251. }
  1252. return r;
  1253. }
  1254. /// <summary>
  1255. /// Builds the visual tree for the
  1256. /// <see cref="T:System.Windows.Controls.AutoCompleteBox" /> control
  1257. /// when a new template is applied.
  1258. /// </summary>
  1259. public override void OnApplyTemplate()
  1260. {
  1261. #if !SILVERLIGHT
  1262. if (TextBox != null)
  1263. {
  1264. TextBox.PreviewKeyDown -= OnTextBoxPreviewKeyDown;
  1265. }
  1266. #endif
  1267. if (DropDownPopup != null)
  1268. {
  1269. DropDownPopup.Closed -= DropDownPopup_Closed;
  1270. DropDownPopup.FocusChanged -= OnDropDownFocusChanged;
  1271. DropDownPopup.UpdateVisualStates -= OnDropDownPopupUpdateVisualStates;
  1272. DropDownPopup.BeforeOnApplyTemplate();
  1273. DropDownPopup = null;
  1274. }
  1275. base.OnApplyTemplate();
  1276. // Set the template parts. Individual part setters remove and add
  1277. // any event handlers.
  1278. Popup popup = GetTemplateChild(ElementPopup) as Popup;
  1279. if (popup != null)
  1280. {
  1281. DropDownPopup = new PopupHelper(this, popup);
  1282. DropDownPopup.MaxDropDownHeight = MaxDropDownHeight;
  1283. DropDownPopup.AfterOnApplyTemplate();
  1284. DropDownPopup.Closed += DropDownPopup_Closed;
  1285. DropDownPopup.FocusChanged += OnDropDownFocusChanged;
  1286. DropDownPopup.UpdateVisualStates += OnDropDownPopupUpdateVisualStates;
  1287. }
  1288. SelectionAdapter = GetSelectionAdapterPart();
  1289. TextBox = GetTemplateChild(AutoCompleteBox.ElementTextBox) as TextBox;
  1290. #if !SILVERLIGHT
  1291. if (TextBox != null)
  1292. {
  1293. TextBox.PreviewKeyDown += OnTextBoxPreviewKeyDown;
  1294. }
  1295. #endif
  1296. Interaction.OnApplyTemplateBase();
  1297. // If the drop down property indicates that the popup is open,
  1298. // flip its value to invoke the changed handler.
  1299. if (IsDropDownOpen && DropDownPopup != null && !DropDownPopup.IsOpen)
  1300. {
  1301. OpeningDropDown(false);
  1302. }
  1303. }
  1304. /// <summary>
  1305. /// Allows the popup wrapper to fire visual state change events.
  1306. /// </summary>
  1307. /// <param name="sender">The source object.</param>
  1308. /// <param name="e">The event data.</param>
  1309. private void OnDropDownPopupUpdateVisualStates(object sender, EventArgs e)
  1310. {
  1311. UpdateVisualState(true);
  1312. }
  1313. /// <summary>
  1314. /// Allows the popup wrapper to fire the FocusChanged event.
  1315. /// </summary>
  1316. /// <param name="sender">The source object.</param>
  1317. /// <param name="e">The event data.</param>
  1318. private void OnDropDownFocusChanged(object sender, EventArgs e)
  1319. {
  1320. FocusChanged(HasFocus());
  1321. }
  1322. /// <summary>
  1323. /// Begin closing the drop-down.
  1324. /// </summary>
  1325. /// <param name="oldValue">The original value.</param>
  1326. private void ClosingDropDown(bool oldValue)
  1327. {
  1328. bool delayedClosingVisual = false;
  1329. if (DropDownPopup != null)
  1330. {
  1331. delayedClosingVisual = DropDownPopup.UsesClosingVisualState;
  1332. }
  1333. #if SILVERLIGHT
  1334. RoutedPropertyChangingEventArgs<bool> args = new RoutedPropertyChangingEventArgs<bool>(IsDropDownOpenProperty, oldValue, false, true);
  1335. #else
  1336. RoutedPropertyChangingEventArgs<bool> args = new RoutedPropertyChangingEventArgs<bool>(IsDropDownOpenProperty, oldValue, false, true, DropDownClosingEvent);
  1337. #endif
  1338. OnDropDownClosing(args);
  1339. if (_view == null || _view.Count == 0)
  1340. {
  1341. delayedClosingVisual = false;
  1342. }
  1343. if (args.Cancel)
  1344. {
  1345. _ignorePropertyChange = true;
  1346. SetValue(IsDropDownOpenProperty, oldValue);
  1347. }
  1348. else
  1349. {
  1350. // Immediately close the drop down window:
  1351. // When a popup closed visual state is present, the code path is
  1352. // slightly different and the actual call to CloseDropDown will
  1353. // be called only after the visual state's transition is done
  1354. RaiseExpandCollapseAutomationEvent(oldValue, false);
  1355. if (!delayedClosingVisual)
  1356. {
  1357. CloseDropDown(oldValue, false);
  1358. }
  1359. }
  1360. UpdateVisualState(true);
  1361. }
  1362. /// <summary>
  1363. /// Begin opening the drop down by firing cancelable events, opening the
  1364. /// drop-down or reverting, depending on the event argument values.
  1365. /// </summary>
  1366. /// <param name="oldValue">The original value, if needed for a revert.</param>
  1367. private void OpeningDropDown(bool oldValue)
  1368. {
  1369. #if SILVERLIGHT
  1370. RoutedPropertyChangingEventArgs<bool> args = new RoutedPropertyChangingEventArgs<bool>(IsDropDownOpenProperty, oldValue, true, true);
  1371. #else
  1372. RoutedPropertyChangingEventArgs<bool> args = new RoutedPropertyChangingEventArgs<bool>(IsDropDownOpenProperty, oldValue, true, true, DropDownOpeningEvent);
  1373. #endif
  1374. // Opening
  1375. OnDropDownOpening(args);
  1376. if (args.Cancel)
  1377. {
  1378. _ignorePropertyChange = true;
  1379. SetValue(IsDropDownOpenProperty, oldValue);
  1380. }
  1381. else
  1382. {
  1383. RaiseExpandCollapseAutomationEvent(oldValue, true);
  1384. OpenDropDown(oldValue, true);
  1385. }
  1386. UpdateVisualState(true);
  1387. }
  1388. /// <summary>
  1389. /// Raise an expand/collapse event through the automation peer.
  1390. /// </summary>
  1391. /// <param name="oldValue">The old value.</param>
  1392. /// <param name="newValue">The new value.</param>
  1393. private void RaiseExpandCollapseAutomationEvent(bool oldValue, bool newValue)
  1394. {
  1395. AutoCompleteBoxAutomationPeer peer = FrameworkElementAutomationPeer.FromElement(this) as AutoCompleteBoxAutomationPeer;
  1396. if (peer != null)
  1397. {
  1398. peer.RaiseExpandCollapseAutomationEvent(oldValue, newValue);
  1399. }
  1400. }
  1401. #if !SILVERLIGHT
  1402. /// <summary>
  1403. /// Handles the PreviewKeyDown event on the TextBox for WPF. This method
  1404. /// is not implemented for Silverlight.
  1405. /// </summary>
  1406. /// <param name="sender">The source object.</param>
  1407. /// <param name="e">The event data.</param>
  1408. private void OnTextBoxPreviewKeyDown(object sender, KeyEventArgs e)
  1409. {
  1410. OnKeyDown(e);
  1411. }
  1412. #endif
  1413. /// <summary>
  1414. /// Connects to the DropDownPopup Closed event.
  1415. /// </summary>
  1416. /// <param name="sender">The source object.</param>
  1417. /// <param name="e">The event data.</param>
  1418. private void DropDownPopup_Closed(object sender, EventArgs e)
  1419. {
  1420. // Force the drop down dependency property to be false.
  1421. if (IsDropDownOpen)
  1422. {
  1423. IsDropDownOpen = false;
  1424. }
  1425. // Fire the DropDownClosed event
  1426. if (_popupHasOpened)
  1427. {
  1428. #if SILVERLIGHT
  1429. OnDropDownClosed(new RoutedPropertyChangedEventArgs<bool>(true, false));
  1430. #else
  1431. OnDropDownClosed(new RoutedPropertyChangedEventArgs<bool>(true, false, DropDownClosedEvent));
  1432. #endif
  1433. }
  1434. }
  1435. /// <summary>
  1436. /// Creates an
  1437. /// <see cref="T:System.Windows.Automation.Peers.AutoCompleteBoxAutomationPeer" />
  1438. /// </summary>
  1439. /// <returns>A
  1440. /// <see cref="T:System.Windows.Automation.Peers.AutoCompleteBoxAutomationPeer" />
  1441. /// for the <see cref="T:System.Windows.Controls.AutoCompleteBox" />
  1442. /// object.</returns>
  1443. protected override AutomationPeer OnCreateAutomationPeer()
  1444. {
  1445. return new AutoCompleteBoxAutomationPeer(this);
  1446. }
  1447. #region Focus
  1448. /// <summary>
  1449. /// Handles the FocusChanged event.
  1450. /// </summary>
  1451. /// <param name="hasFocus">A value indicating whether the control
  1452. /// currently has the focus.</param>
  1453. private void FocusChanged(bool hasFocus)
  1454. {
  1455. // The OnGotFocus & OnLostFocus are asynchronously and cannot
  1456. // reliably tell you that have the focus. All they do is let you
  1457. // know that the focus changed sometime in the past. To determine
  1458. // if you currently have the focus you need to do consult the
  1459. // FocusManager (see HasFocus()).
  1460. if (hasFocus)
  1461. {
  1462. if (TextBox != null && TextBox.SelectionLength == 0)
  1463. {
  1464. TextBox.SelectAll();
  1465. }
  1466. }
  1467. else
  1468. {
  1469. IsDropDownOpen = false;
  1470. _userCalledPopulate = false;
  1471. if (TextBox != null)
  1472. {
  1473. TextBox.Select(TextBox.Text.Length, 0);
  1474. }
  1475. }
  1476. }
  1477. /// <summary>
  1478. /// Determines whether the text box or drop-down portion of the
  1479. /// <see cref="T:System.Windows.Controls.AutoCompleteBox" /> control has
  1480. /// focus.
  1481. /// </summary>
  1482. /// <returns>true to indicate the
  1483. /// <see cref="T:System.Windows.Controls.AutoCompleteBox" /> has focus;
  1484. /// otherwise, false.</returns>
  1485. protected bool HasFocus()
  1486. {
  1487. DependencyObject focused =
  1488. #if SILVERLIGHT
  1489. FocusManager.GetFocusedElement() as DependencyObject;
  1490. #else
  1491. // For WPF, check if the element that has focus is within the control, as
  1492. // FocusManager.GetFocusedElement(this) will return null in such a case.
  1493. this.IsKeyboardFocusWithin ? Keyboard.FocusedElement as DependencyObject : FocusManager.GetFocusedElement(this) as DependencyObject;
  1494. #endif
  1495. while (focused != null)
  1496. {
  1497. if (object.ReferenceEquals(focused, this))
  1498. {
  1499. return true;
  1500. }
  1501. // This helps deal with popups that may not be in the same
  1502. // visual tree
  1503. DependencyObject parent = VisualTreeHelper.GetParent(focused);
  1504. if (parent == null)
  1505. {
  1506. // Try the logical parent.
  1507. FrameworkElement element = focused as FrameworkElement;
  1508. if (element != null)
  1509. {
  1510. parent = element.Parent;
  1511. }
  1512. }
  1513. focused = parent;
  1514. }
  1515. return false;
  1516. }
  1517. /// <summary>
  1518. /// Provides handling for the
  1519. /// <see cref="E:System.Windows.UIElement.GotFocus" /> event.
  1520. /// </summary>
  1521. /// <param name="e">A <see cref="T:System.Windows.RoutedEventArgs" />
  1522. /// that contains the event data.</param>
  1523. protected override void OnGotFocus(RoutedEventArgs e)
  1524. {
  1525. base.OnGotFocus(e);
  1526. FocusChanged(HasFocus());
  1527. }
  1528. #if !SILVERLIGHT
  1529. /// <summary>
  1530. /// Handles change of keyboard focus, which is treated differently than control focus
  1531. /// </summary>
  1532. /// <param name="e"></param>
  1533. protected override void OnIsKeyboardFocusWithinChanged(DependencyPropertyChangedEventArgs e)
  1534. {
  1535. base.OnIsKeyboardFocusWithinChanged(e);
  1536. FocusChanged((bool)e.NewValue);
  1537. }
  1538. #endif
  1539. /// <summary>
  1540. /// Provides handling for the
  1541. /// <see cref="E:System.Windows.UIElement.LostFocus" /> event.
  1542. /// </summary>
  1543. /// <param name="e">A <see cref="T:System.Windows.RoutedEventArgs" />
  1544. /// that contains the event data.</param>
  1545. protected override void OnLostFocus(RoutedEventArgs e)
  1546. {
  1547. base.OnLostFocus(e);
  1548. FocusChanged(HasFocus());
  1549. }
  1550. #endregion
  1551. /// <summary>
  1552. /// Handle the change of the IsEnabled property.
  1553. /// </summary>
  1554. /// <param name="sender">The source object.</param>
  1555. /// <param name="e">The event data.</param>
  1556. private void ControlIsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
  1557. {
  1558. bool isEnabled = (bool)e.NewValue;
  1559. if (!isEnabled)
  1560. {
  1561. IsDropDownOpen = false;
  1562. }
  1563. }
  1564. /// <summary>
  1565. /// Returns the
  1566. /// <see cref="T:System.Windows.Controls.ISelectionAdapter" /> part, if
  1567. /// possible.
  1568. /// </summary>
  1569. /// <returns>
  1570. /// A <see cref="T:System.Windows.Controls.ISelectionAdapter" /> object,
  1571. /// if possible. Otherwise, null.
  1572. /// </returns>
  1573. [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Following the GetTemplateChild pattern for the method.")]
  1574. protected virtual ISelectionAdapter GetSelectionAdapterPart()
  1575. {
  1576. ISelectionAdapter adapter = null;
  1577. Selector selector = GetTemplateChild(ElementSelector) as Selector;
  1578. if (selector != null)
  1579. {
  1580. // Check if it is already an IItemsSelector
  1581. adapter = selector as ISelectionAdapter;
  1582. if (adapter == null)
  1583. {
  1584. // Built in support for wrapping a Selector control
  1585. adapter = new SelectorSelectionAdapter(selector);
  1586. }
  1587. }
  1588. if (adapter == null)
  1589. {
  1590. adapter = GetTemplateChild(ElementSelectionAdapter) as ISelectionAdapter;
  1591. }
  1592. return adapter;
  1593. }
  1594. /// <summary>
  1595. /// Handles the timer tick when using a populate delay.
  1596. /// </summary>
  1597. /// <param name="sender">The source object.</param>
  1598. /// <param name="e">The event arguments.</param>
  1599. private void PopulateDropDown(object sender, EventArgs e)
  1600. {
  1601. if (_delayTimer != null)
  1602. {
  1603. _delayTimer.Stop();
  1604. }
  1605. // Update the prefix/search text.
  1606. SearchText = Text;
  1607. // The Populated event enables advanced, custom filtering. The
  1608. // client needs to directly update the ItemsSource collection or
  1609. // call the Populate method on the control to continue the
  1610. // display process if Cancel is set to true.
  1611. #if SILVERLIGHT
  1612. PopulatingEventArgs populating = new PopulatingEventArgs(SearchText);
  1613. #else
  1614. PopulatingEventArgs populating = new PopulatingEventArgs(SearchText, PopulatingEvent);
  1615. #endif
  1616. OnPopulating(populating);
  1617. if (!populating.Cancel)
  1618. {
  1619. PopulateComplete();
  1620. }
  1621. }
  1622. /// <summary>
  1623. /// Raises the
  1624. /// <see cref="E:System.Windows.Controls.AutoCompleteBox.Populating" />
  1625. /// event.
  1626. /// </summary>
  1627. /// <param name="e">A
  1628. /// <see cref="T:System.Windows.Controls.PopulatingEventArgs" /> that
  1629. /// contains the event data.</param>
  1630. protected virtual void OnPopulating(PopulatingEventArgs e)
  1631. {
  1632. #if SILVERLIGHT
  1633. PopulatingEventHandler handler = Populating;
  1634. if (handler != null)
  1635. {
  1636. handler(this, e);
  1637. }
  1638. #else
  1639. RaiseEvent(e);
  1640. #endif
  1641. }
  1642. /// <summary>
  1643. /// Raises the
  1644. /// <see cref="E:System.Windows.Controls.AutoCompleteBox.Populated" />
  1645. /// event.
  1646. /// </summary>
  1647. /// <param name="e">A
  1648. /// <see cref="T:System.Windows.Controls.PopulatedEventArgs" />
  1649. /// that contains the event data.</param>
  1650. protected virtual void OnPopulated(PopulatedEventArgs e)
  1651. {
  1652. #if SILVERLIGHT
  1653. PopulatedEventHandler handler = Populated;
  1654. if (handler != null)
  1655. {
  1656. handler(this, e);
  1657. }
  1658. #else
  1659. RaiseEvent(e);
  1660. #endif
  1661. }
  1662. /// <summary>
  1663. /// Raises the
  1664. /// <see cref="E:System.Windows.Controls.AutoCompleteBox.SelectionChanged" />
  1665. /// event.
  1666. /// </summary>
  1667. /// <param name="e">A
  1668. /// <see cref="T:System.Windows.Controls.SelectionChangedEventArgs" />
  1669. /// that contains the event data.</param>
  1670. protected virtual void OnSelectionChanged(SelectionChangedEventArgs e)
  1671. {
  1672. #if SILVERLIGHT
  1673. SelectionChangedEventHandler handler = SelectionChanged;
  1674. if (handler != null)
  1675. {
  1676. handler(this, e);
  1677. }
  1678. #else
  1679. RaiseEvent(e);
  1680. #endif
  1681. }
  1682. /// <summary>
  1683. /// Raises the
  1684. /// <see cref="E:System.Windows.Controls.AutoCompleteBox.DropDownOpening" />
  1685. /// event.
  1686. /// </summary>
  1687. /// <param name="e">A
  1688. /// <see cref="T:System.Windows.Controls.RoutedPropertyChangingEventArgs`1" />
  1689. /// that contains the event data.</param>
  1690. protected virtual void OnDropDownOpening(RoutedPropertyChangingEventArgs<bool> e)
  1691. {
  1692. #if SILVERLIGHT
  1693. RoutedPropertyChangingEventHandler<bool> handler = DropDownOpening;
  1694. if (handler != null)
  1695. {
  1696. handler(this, e);
  1697. }
  1698. #else
  1699. RaiseEvent(e);
  1700. #endif
  1701. }
  1702. /// <summary>
  1703. /// Raises the
  1704. /// <see cref="E:System.Windows.Controls.AutoCompleteBox.DropDownOpened" />
  1705. /// event.
  1706. /// </summary>
  1707. /// <param name="e">A
  1708. /// <see cref="T:System.Windows.RoutedPropertyChangedEventArgs`1" />
  1709. /// that contains the event data.</param>
  1710. protected virtual void OnDropDownOpened(RoutedPropertyChangedEventArgs<bool> e)
  1711. {
  1712. #if SILVERLIGHT
  1713. RoutedPropertyChangedEventHandler<bool> handler = DropDownOpened;
  1714. if (handler != null)
  1715. {
  1716. handler(this, e);
  1717. }
  1718. #else
  1719. RaiseEvent(e);
  1720. #endif
  1721. }
  1722. /// <summary>
  1723. /// Raises the
  1724. /// <see cref="E:System.Windows.Controls.AutoCompleteBox.DropDownClosing" />
  1725. /// event.
  1726. /// </summary>
  1727. /// <param name="e">A
  1728. /// <see cref="T:System.Windows.Controls.RoutedPropertyChangingEventArgs`1" />
  1729. /// that contains the event data.</param>
  1730. protected virtual void OnDropDownClosing(RoutedPropertyChangingEventArgs<bool> e)
  1731. {
  1732. #if SILVERLIGHT
  1733. RoutedPropertyChangingEventHandler<bool> handler = DropDownClosing;
  1734. if (handler != null)
  1735. {
  1736. handler(this, e);
  1737. }
  1738. #else
  1739. RaiseEvent(e);
  1740. #endif
  1741. }
  1742. /// <summary>
  1743. /// Raises the
  1744. /// <see cref="E:System.Windows.Controls.AutoCompleteBox.DropDownClosed" />
  1745. /// event.
  1746. /// </summary>
  1747. /// <param name="e">A
  1748. /// <see cref="T:System.Windows.RoutedPropertyChangedEventArgs`1" />
  1749. /// which contains the event data.</param>
  1750. protected virtual void OnDropDownClosed(RoutedPropertyChangedEventArgs<bool> e)
  1751. {
  1752. #if SILVERLIGHT
  1753. RoutedPropertyChangedEventHandler<bool> handler = DropDownClosed;
  1754. if (handler != null)
  1755. {
  1756. handler(this, e);
  1757. }
  1758. #else
  1759. RaiseEvent(e);
  1760. #endif
  1761. }
  1762. /// <summary>
  1763. /// Formats an Item for text comparisons based on Converter
  1764. /// and ConverterCulture properties.
  1765. /// </summary>
  1766. /// <param name="value">The object to format.</param>
  1767. /// <param name="clearDataContext">A value indicating whether to clear
  1768. /// the data context after the lookup is performed.</param>
  1769. /// <returns>Formatted Value.</returns>
  1770. private string FormatValue(object value, bool clearDataContext)
  1771. {
  1772. string str = FormatValue(value);
  1773. if (clearDataContext && _valueBindingEvaluator != null)
  1774. {
  1775. _valueBindingEvaluator.ClearDataContext();
  1776. }
  1777. return str;
  1778. }
  1779. /// <summary>
  1780. /// Converts the specified object to a string by using the
  1781. /// <see cref="P:System.Windows.Data.Binding.Converter" /> and
  1782. /// <see cref="P:System.Windows.Data.Binding.ConverterCulture" /> values
  1783. /// of the binding object specified by the
  1784. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.ValueMemberBinding" />
  1785. /// property.
  1786. /// </summary>
  1787. /// <param name="value">The object to format as a string.</param>
  1788. /// <returns>The string representation of the specified object.</returns>
  1789. /// <remarks>
  1790. /// Override this method to provide a custom string conversion.
  1791. /// </remarks>
  1792. protected virtual string FormatValue(object value)
  1793. {
  1794. if (_valueBindingEvaluator != null)
  1795. {
  1796. return _valueBindingEvaluator.GetDynamicValue(value) ?? string.Empty;
  1797. }
  1798. return value == null ? string.Empty : value.ToString();
  1799. }
  1800. /// <summary>
  1801. /// Raises the
  1802. /// <see cref="E:System.Windows.Controls.AutoCompleteBox.TextChanged" />
  1803. /// event.
  1804. /// </summary>
  1805. /// <param name="e">A <see cref="T:System.Windows.RoutedEventArgs" />
  1806. /// that contains the event data.</param>
  1807. protected virtual void OnTextChanged(RoutedEventArgs e)
  1808. {
  1809. #if SILVERLIGHT
  1810. RoutedEventHandler handler = TextChanged;
  1811. if (handler != null)
  1812. {
  1813. handler(this, e);
  1814. }
  1815. #else
  1816. RaiseEvent(e);
  1817. #endif
  1818. }
  1819. /// <summary>
  1820. /// Handle the TextChanged event that is directly attached to the
  1821. /// TextBox part. This ensures that only user initiated actions will
  1822. /// result in an AutoCompleteBox suggestion and operation.
  1823. /// </summary>
  1824. /// <param name="sender">The source TextBox object.</param>
  1825. /// <param name="e">The TextChanged event data.</param>
  1826. private void OnTextBoxTextChanged(object sender, TextChangedEventArgs e)
  1827. {
  1828. // Call the central updated text method as a user-initiated action
  1829. TextUpdated(_text.Text, true);
  1830. }
  1831. /// <summary>
  1832. /// When selection changes, save the location of the selection start.
  1833. /// </summary>
  1834. /// <param name="sender">The source object.</param>
  1835. /// <param name="e">The event data.</param>
  1836. private void OnTextBoxSelectionChanged(object sender, RoutedEventArgs e)
  1837. {
  1838. // If ignoring updates. This happens after text is updated, and
  1839. // before the PopulateComplete method is called. Required for the
  1840. // IsTextCompletionEnabled feature.
  1841. if (_ignoreTextSelectionChange)
  1842. {
  1843. return;
  1844. }
  1845. _textSelectionStart = _text.SelectionStart;
  1846. }
  1847. /// <summary>
  1848. /// Updates both the text box value and underlying text dependency
  1849. /// property value if and when they change. Automatically fires the
  1850. /// text changed events when there is a change.
  1851. /// </summary>
  1852. /// <param name="value">The new string value.</param>
  1853. private void UpdateTextValue(string value)
  1854. {
  1855. UpdateTextValue(value, null);
  1856. }
  1857. /// <summary>
  1858. /// Updates both the text box value and underlying text dependency
  1859. /// property value if and when they change. Automatically fires the
  1860. /// text changed events when there is a change.
  1861. /// </summary>
  1862. /// <param name="value">The new string value.</param>
  1863. /// <param name="userInitiated">A nullable bool value indicating whether
  1864. /// the action was user initiated. In a user initiated mode, the
  1865. /// underlying text dependency property is updated. In a non-user
  1866. /// interaction, the text box value is updated. When user initiated is
  1867. /// null, all values are updated.</param>
  1868. private void UpdateTextValue(string value, bool? userInitiated)
  1869. {
  1870. // Update the Text dependency property
  1871. if ((userInitiated == null || userInitiated == true) && Text != value)
  1872. {
  1873. _ignoreTextPropertyChange++;
  1874. Text = value;
  1875. #if SILVERLIGHT
  1876. OnTextChanged(new RoutedEventArgs());
  1877. #else
  1878. OnTextChanged(new RoutedEventArgs(TextChangedEvent));
  1879. #endif
  1880. }
  1881. // Update the TextBox's Text dependency property
  1882. if ((userInitiated == null || userInitiated == false) && TextBox != null && TextBox.Text != value)
  1883. {
  1884. _ignoreTextPropertyChange++;
  1885. TextBox.Text = value ?? string.Empty;
  1886. // Text dependency property value was set, fire event
  1887. if (Text == value || Text == null)
  1888. {
  1889. #if SILVERLIGHT
  1890. OnTextChanged(new RoutedEventArgs());
  1891. #else
  1892. OnTextChanged(new RoutedEventArgs(TextChangedEvent));
  1893. #endif
  1894. }
  1895. }
  1896. }
  1897. /// <summary>
  1898. /// Handle the update of the text for the control from any source,
  1899. /// including the TextBox part and the Text dependency property.
  1900. /// </summary>
  1901. /// <param name="newText">The new text.</param>
  1902. /// <param name="userInitiated">A value indicating whether the update
  1903. /// is a user-initiated action. This should be a True value when the
  1904. /// TextUpdated method is called from a TextBox event handler.</param>
  1905. private void TextUpdated(string newText, bool userInitiated)
  1906. {
  1907. // Only process this event if it is coming from someone outside
  1908. // setting the Text dependency property directly.
  1909. if (_ignoreTextPropertyChange > 0)
  1910. {
  1911. _ignoreTextPropertyChange--;
  1912. return;
  1913. }
  1914. if (newText == null)
  1915. {
  1916. newText = string.Empty;
  1917. }
  1918. // The TextBox.TextChanged event was not firing immediately and
  1919. // was causing an immediate update, even with wrapping. If there is
  1920. // a selection currently, no update should happen.
  1921. if (IsTextCompletionEnabled && TextBox != null && TextBox.SelectionLength > 0 && TextBox.SelectionStart != TextBox.Text.Length)
  1922. {
  1923. return;
  1924. }
  1925. // Evaluate the conditions needed for completion.
  1926. // 1. Minimum prefix length
  1927. // 2. If a delay timer is in use, use it
  1928. bool populateReady = newText.Length >= MinimumPrefixLength && MinimumPrefixLength >= 0;
  1929. _userCalledPopulate = populateReady ? userInitiated : false;
  1930. // Update the interface and values only as necessary
  1931. UpdateTextValue(newText, userInitiated);
  1932. if (populateReady)
  1933. {
  1934. _ignoreTextSelectionChange = true;
  1935. if (_delayTimer != null)
  1936. {
  1937. _delayTimer.Start();
  1938. }
  1939. else
  1940. {
  1941. PopulateDropDown(this, EventArgs.Empty);
  1942. }
  1943. }
  1944. else
  1945. {
  1946. SearchText = string.Empty;
  1947. if (SelectedItem != null)
  1948. {
  1949. _skipSelectedItemTextUpdate = true;
  1950. }
  1951. SelectedItem = null;
  1952. if (IsDropDownOpen)
  1953. {
  1954. IsDropDownOpen = false;
  1955. }
  1956. }
  1957. }
  1958. /// <summary>
  1959. /// Notifies the
  1960. /// <see cref="T:System.Windows.Controls.AutoCompleteBox" /> that the
  1961. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.ItemsSource" />
  1962. /// property has been set and the data can be filtered to provide
  1963. /// possible matches in the drop-down.
  1964. /// </summary>
  1965. /// <remarks>
  1966. /// Call this method when you are providing custom population of
  1967. /// the drop-down portion of the AutoCompleteBox, to signal the control
  1968. /// that you are done with the population process.
  1969. /// Typically, you use PopulateComplete when the population process
  1970. /// is a long-running process and you want to cancel built-in filtering
  1971. /// of the ItemsSource items. In this case, you can handle the
  1972. /// Populated event and set PopulatingEventArgs.Cancel to true.
  1973. /// When the long-running process has completed you call
  1974. /// PopulateComplete to indicate the drop-down is populated.
  1975. /// </remarks>
  1976. public void PopulateComplete()
  1977. {
  1978. // Apply the search filter
  1979. RefreshView();
  1980. // Fire the Populated event containing the read-only view data.
  1981. #if SILVERLIGHT
  1982. PopulatedEventArgs populated = new PopulatedEventArgs(new ReadOnlyCollection<object>(_view));
  1983. #else
  1984. PopulatedEventArgs populated = new PopulatedEventArgs(new ReadOnlyCollection<object>(_view), PopulatedEvent);
  1985. #endif
  1986. OnPopulated(populated);
  1987. if (SelectionAdapter != null && SelectionAdapter.ItemsSource != _view)
  1988. {
  1989. SelectionAdapter.ItemsSource = _view;
  1990. }
  1991. bool isDropDownOpen = _userCalledPopulate && (_view.Count > 0);
  1992. if (isDropDownOpen != IsDropDownOpen)
  1993. {
  1994. _ignorePropertyChange = true;
  1995. IsDropDownOpen = isDropDownOpen;
  1996. }
  1997. if (IsDropDownOpen)
  1998. {
  1999. OpeningDropDown(false);
  2000. if (DropDownPopup != null)
  2001. {
  2002. DropDownPopup.Arrange();
  2003. }
  2004. }
  2005. else
  2006. {
  2007. ClosingDropDown(true);
  2008. }
  2009. UpdateTextCompletion(_userCalledPopulate);
  2010. }
  2011. /// <summary>
  2012. /// Performs text completion, if enabled, and a lookup on the underlying
  2013. /// item values for an exact match. Will update the SelectedItem value.
  2014. /// </summary>
  2015. /// <param name="userInitiated">A value indicating whether the operation
  2016. /// was user initiated. Text completion will not be performed when not
  2017. /// directly initiated by the user.</param>
  2018. private void UpdateTextCompletion(bool userInitiated)
  2019. {
  2020. // By default this method will clear the selected value
  2021. object newSelectedItem = null;
  2022. string text = Text;
  2023. // Text search is StartsWith explicit and only when enabled, in
  2024. // line with WPF's ComboBox lookup. When in use it will associate
  2025. // a Value with the Text if it is found in ItemsSource. This is
  2026. // only valid when there is data and the user initiated the action.
  2027. if (_view.Count > 0)
  2028. {
  2029. if (IsTextCompletionEnabled && TextBox != null && userInitiated)
  2030. {
  2031. int currentLength = TextBox.Text.Length;
  2032. int selectionStart = TextBox.SelectionStart;
  2033. if (selectionStart == text.Length && selectionStart > _textSelectionStart)
  2034. {
  2035. // When the FilterMode dependency property is set to
  2036. // either StartsWith or StartsWithCaseSensitive, the
  2037. // first item in the view is used. This will improve
  2038. // performance on the lookup. It assumes that the
  2039. // FilterMode the user has selected is an acceptable
  2040. // case sensitive matching function for their scenario.
  2041. object top = FilterMode == AutoCompleteFilterMode.StartsWith || FilterMode == AutoCompleteFilterMode.StartsWithCaseSensitive
  2042. ? _view[0]
  2043. : TryGetMatch(text, _view, AutoCompleteSearch.GetFilter(AutoCompleteFilterMode.StartsWith));
  2044. // If the search was successful, update SelectedItem
  2045. if (top != null)
  2046. {
  2047. newSelectedItem = top;
  2048. string topString = FormatValue(top, true);
  2049. // Only replace partially when the two words being the same
  2050. int minLength = Math.Min(topString.Length, Text.Length);
  2051. if (AutoCompleteSearch.Equals(Text.Substring(0, minLength), topString.Substring(0, minLength)))
  2052. {
  2053. // Update the text
  2054. UpdateTextValue(topString);
  2055. // Select the text past the user's caret
  2056. TextBox.SelectionStart = currentLength;
  2057. TextBox.SelectionLength = topString.Length - currentLength;
  2058. }
  2059. }
  2060. }
  2061. }
  2062. else
  2063. {
  2064. // Perform an exact string lookup for the text. This is a
  2065. // design change from the original Toolkit release when the
  2066. // IsTextCompletionEnabled property behaved just like the
  2067. // WPF ComboBox's IsTextSearchEnabled property.
  2068. //
  2069. // This change provides the behavior that most people expect
  2070. // to find: a lookup for the value is always performed.
  2071. newSelectedItem = TryGetMatch(text, _view, AutoCompleteSearch.GetFilter(AutoCompleteFilterMode.EqualsCaseSensitive));
  2072. }
  2073. }
  2074. // Update the selected item property
  2075. if (SelectedItem != newSelectedItem)
  2076. {
  2077. _skipSelectedItemTextUpdate = true;
  2078. }
  2079. SelectedItem = newSelectedItem;
  2080. // Restore updates for TextSelection
  2081. if (_ignoreTextSelectionChange)
  2082. {
  2083. _ignoreTextSelectionChange = false;
  2084. if (TextBox != null)
  2085. {
  2086. _textSelectionStart = TextBox.SelectionStart;
  2087. }
  2088. }
  2089. }
  2090. /// <summary>
  2091. /// Attempts to look through the view and locate the specific exact
  2092. /// text match.
  2093. /// </summary>
  2094. /// <param name="searchText">The search text.</param>
  2095. /// <param name="view">The view reference.</param>
  2096. /// <param name="predicate">The predicate to use for the partial or
  2097. /// exact match.</param>
  2098. /// <returns>Returns the object or null.</returns>
  2099. private object TryGetMatch(string searchText, ObservableCollection<object> view, AutoCompleteFilterPredicate<string> predicate)
  2100. {
  2101. if (view != null && view.Count > 0)
  2102. {
  2103. foreach (object o in view)
  2104. {
  2105. if (predicate(searchText, FormatValue(o)))
  2106. {
  2107. return o;
  2108. }
  2109. }
  2110. }
  2111. return null;
  2112. }
  2113. /// <summary>
  2114. /// A simple helper method to clear the view and ensure that a view
  2115. /// object is always present and not null.
  2116. /// </summary>
  2117. private void ClearView()
  2118. {
  2119. if (_view == null)
  2120. {
  2121. _view = new ObservableCollection<object>();
  2122. }
  2123. else
  2124. {
  2125. _view.Clear();
  2126. }
  2127. }
  2128. /// <summary>
  2129. /// Walks through the items enumeration. Performance is not going to be
  2130. /// perfect with the current implementation.
  2131. /// </summary>
  2132. private void RefreshView()
  2133. {
  2134. if (_items == null)
  2135. {
  2136. ClearView();
  2137. return;
  2138. }
  2139. // Cache the current text value
  2140. string text = Text ?? string.Empty;
  2141. // Determine if any filtering mode is on
  2142. bool stringFiltering = TextFilter != null;
  2143. bool objectFiltering = FilterMode == AutoCompleteFilterMode.Custom && TextFilter == null;
  2144. int view_index = 0;
  2145. int view_count = _view.Count;
  2146. List<object> items = _items;
  2147. foreach (object item in items)
  2148. {
  2149. bool inResults = !(stringFiltering || objectFiltering);
  2150. if (!inResults)
  2151. {
  2152. inResults = stringFiltering ? TextFilter(text, FormatValue(item)) : ItemFilter(text, item);
  2153. }
  2154. if (view_count > view_index && inResults && _view[view_index] == item)
  2155. {
  2156. // Item is still in the view
  2157. view_index++;
  2158. }
  2159. else if (inResults)
  2160. {
  2161. // Insert the item
  2162. if (view_count > view_index && _view[view_index] != item)
  2163. {
  2164. // Replace item
  2165. // Unfortunately replacing via index throws a fatal
  2166. // exception: View[view_index] = item;
  2167. // Cost: O(n) vs O(1)
  2168. _view.RemoveAt(view_index);
  2169. _view.Insert(view_index, item);
  2170. view_index++;
  2171. }
  2172. else
  2173. {
  2174. // Add the item
  2175. if (view_index == view_count)
  2176. {
  2177. // Constant time is preferred (Add).
  2178. _view.Add(item);
  2179. }
  2180. else
  2181. {
  2182. _view.Insert(view_index, item);
  2183. }
  2184. view_index++;
  2185. view_count++;
  2186. }
  2187. }
  2188. else if (view_count > view_index && _view[view_index] == item)
  2189. {
  2190. // Remove the item
  2191. _view.RemoveAt(view_index);
  2192. view_count--;
  2193. }
  2194. }
  2195. // Clear the evaluator to discard a reference to the last item
  2196. if (_valueBindingEvaluator != null)
  2197. {
  2198. _valueBindingEvaluator.ClearDataContext();
  2199. }
  2200. }
  2201. /// <summary>
  2202. /// Handle any change to the ItemsSource dependency property, update
  2203. /// the underlying ObservableCollection view, and set the selection
  2204. /// adapter's ItemsSource to the view if appropriate.
  2205. /// </summary>
  2206. /// <param name="oldValue">The old enumerable reference.</param>
  2207. /// <param name="newValue">The new enumerable reference.</param>
  2208. [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "oldValue", Justification = "This makes it easy to add validation or other changes in the future.")]
  2209. private void OnItemsSourceChanged(IEnumerable oldValue, IEnumerable newValue)
  2210. {
  2211. // Remove handler for oldValue.CollectionChanged (if present)
  2212. INotifyCollectionChanged oldValueINotifyCollectionChanged = oldValue as INotifyCollectionChanged;
  2213. if (null != oldValueINotifyCollectionChanged && null != _collectionChangedWeakEventListener)
  2214. {
  2215. _collectionChangedWeakEventListener.Detach();
  2216. _collectionChangedWeakEventListener = null;
  2217. }
  2218. // Add handler for newValue.CollectionChanged (if possible)
  2219. INotifyCollectionChanged newValueINotifyCollectionChanged = newValue as INotifyCollectionChanged;
  2220. if (null != newValueINotifyCollectionChanged)
  2221. {
  2222. _collectionChangedWeakEventListener = new WeakEventListener<AutoCompleteBox, object, NotifyCollectionChangedEventArgs>(this);
  2223. _collectionChangedWeakEventListener.OnEventAction = (instance, source, eventArgs) => instance.ItemsSourceCollectionChanged(source, eventArgs);
  2224. _collectionChangedWeakEventListener.OnDetachAction = (weakEventListener) => newValueINotifyCollectionChanged.CollectionChanged -= weakEventListener.OnEvent;
  2225. newValueINotifyCollectionChanged.CollectionChanged += _collectionChangedWeakEventListener.OnEvent;
  2226. }
  2227. // Store a local cached copy of the data
  2228. _items = newValue == null ? null : new List<object>(newValue.Cast<object>().ToList());
  2229. // Clear and set the view on the selection adapter
  2230. ClearView();
  2231. if (SelectionAdapter != null && SelectionAdapter.ItemsSource != _view)
  2232. {
  2233. SelectionAdapter.ItemsSource = _view;
  2234. }
  2235. if (IsDropDownOpen)
  2236. {
  2237. RefreshView();
  2238. }
  2239. }
  2240. /// <summary>
  2241. /// Method that handles the ObservableCollection.CollectionChanged event for the ItemsSource property.
  2242. /// </summary>
  2243. /// <param name="sender">The object that raised the event.</param>
  2244. /// <param name="e">The event data.</param>
  2245. private void ItemsSourceCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
  2246. {
  2247. // Update the cache
  2248. if (e.Action == NotifyCollectionChangedAction.Remove && e.OldItems != null)
  2249. {
  2250. for (int index = 0; index < e.OldItems.Count; index++)
  2251. {
  2252. _items.RemoveAt(e.OldStartingIndex);
  2253. }
  2254. }
  2255. if (e.Action == NotifyCollectionChangedAction.Add && e.NewItems != null && _items.Count >= e.NewStartingIndex)
  2256. {
  2257. for (int index = 0; index < e.NewItems.Count; index++)
  2258. {
  2259. _items.Insert(e.NewStartingIndex + index, e.NewItems[index]);
  2260. }
  2261. }
  2262. if (e.Action == NotifyCollectionChangedAction.Replace && e.NewItems != null && e.OldItems != null)
  2263. {
  2264. for (int index = 0; index < e.NewItems.Count; index++)
  2265. {
  2266. _items[e.NewStartingIndex] = e.NewItems[index];
  2267. }
  2268. }
  2269. // Update the view
  2270. if (e.Action == NotifyCollectionChangedAction.Remove || e.Action == NotifyCollectionChangedAction.Replace)
  2271. {
  2272. for (int index = 0; index < e.OldItems.Count; index++)
  2273. {
  2274. _view.Remove(e.OldItems[index]);
  2275. }
  2276. }
  2277. if (e.Action == NotifyCollectionChangedAction.Reset)
  2278. {
  2279. // Significant changes to the underlying data.
  2280. ClearView();
  2281. if (ItemsSource != null)
  2282. {
  2283. _items = new List<object>(ItemsSource.Cast<object>().ToList());
  2284. }
  2285. }
  2286. // Refresh the observable collection used in the selection adapter.
  2287. RefreshView();
  2288. }
  2289. #region Selection Adapter
  2290. /// <summary>
  2291. /// Handles the SelectionChanged event of the selection adapter.
  2292. /// </summary>
  2293. /// <param name="sender">The source object.</param>
  2294. /// <param name="e">The selection changed event data.</param>
  2295. private void OnAdapterSelectionChanged(object sender, SelectionChangedEventArgs e)
  2296. {
  2297. SelectedItem = _adapter.SelectedItem;
  2298. }
  2299. /// <summary>
  2300. /// Handles the Commit event on the selection adapter.
  2301. /// </summary>
  2302. /// <param name="sender">The source object.</param>
  2303. /// <param name="e">The event data.</param>
  2304. private void OnAdapterSelectionComplete(object sender, RoutedEventArgs e)
  2305. {
  2306. IsDropDownOpen = false;
  2307. // Completion will update the selected value
  2308. UpdateTextCompletion(false);
  2309. // Text should not be selected
  2310. if (TextBox != null)
  2311. {
  2312. TextBox.Select(TextBox.Text.Length, 0);
  2313. }
  2314. #if SILVERLIGHT
  2315. Focus();
  2316. #else
  2317. // Focus is treated differently in SL and WPF.
  2318. // This forces the textbox to get keyboard focus, in the case where
  2319. // another part of the control may have temporarily received focus.
  2320. if (TextBox != null)
  2321. {
  2322. Keyboard.Focus(TextBox);
  2323. }
  2324. else
  2325. {
  2326. Focus();
  2327. }
  2328. #endif
  2329. }
  2330. /// <summary>
  2331. /// Handles the Cancel event on the selection adapter.
  2332. /// </summary>
  2333. /// <param name="sender">The source object.</param>
  2334. /// <param name="e">The event data.</param>
  2335. private void OnAdapterSelectionCanceled(object sender, RoutedEventArgs e)
  2336. {
  2337. UpdateTextValue(SearchText);
  2338. // Completion will update the selected value
  2339. UpdateTextCompletion(false);
  2340. }
  2341. #endregion
  2342. #region Popup
  2343. /// <summary>
  2344. /// Handles MaxDropDownHeightChanged by re-arranging and updating the
  2345. /// popup arrangement.
  2346. /// </summary>
  2347. /// <param name="newValue">The new value.</param>
  2348. [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "newValue", Justification = "This makes it easy to add validation or other changes in the future.")]
  2349. private void OnMaxDropDownHeightChanged(double newValue)
  2350. {
  2351. if (DropDownPopup != null)
  2352. {
  2353. DropDownPopup.MaxDropDownHeight = newValue;
  2354. DropDownPopup.Arrange();
  2355. }
  2356. UpdateVisualState(true);
  2357. }
  2358. /// <summary>
  2359. /// Private method that directly opens the popup, checks the expander
  2360. /// button, and then fires the Opened event.
  2361. /// </summary>
  2362. /// <param name="oldValue">The old value.</param>
  2363. /// <param name="newValue">The new value.</param>
  2364. private void OpenDropDown(bool oldValue, bool newValue)
  2365. {
  2366. if (DropDownPopup != null)
  2367. {
  2368. DropDownPopup.IsOpen = true;
  2369. }
  2370. _popupHasOpened = true;
  2371. #if SILVERLIGHT
  2372. OnDropDownOpened(new RoutedPropertyChangedEventArgs<bool>(oldValue, newValue));
  2373. #else
  2374. OnDropDownOpened(new RoutedPropertyChangedEventArgs<bool>(oldValue, newValue, DropDownOpenedEvent));
  2375. #endif
  2376. }
  2377. /// <summary>
  2378. /// Private method that directly closes the popup, flips the Checked
  2379. /// value, and then fires the Closed event.
  2380. /// </summary>
  2381. /// <param name="oldValue">The old value.</param>
  2382. /// <param name="newValue">The new value.</param>
  2383. private void CloseDropDown(bool oldValue, bool newValue)
  2384. {
  2385. if (_popupHasOpened)
  2386. {
  2387. if (SelectionAdapter != null)
  2388. {
  2389. SelectionAdapter.SelectedItem = null;
  2390. }
  2391. if (DropDownPopup != null)
  2392. {
  2393. DropDownPopup.IsOpen = false;
  2394. }
  2395. #if SILVERLIGHT
  2396. OnDropDownClosed(new RoutedPropertyChangedEventArgs<bool>(oldValue, newValue));
  2397. #else
  2398. OnDropDownClosed(new RoutedPropertyChangedEventArgs<bool>(oldValue, newValue, DropDownClosedEvent));
  2399. #endif
  2400. }
  2401. }
  2402. #endregion
  2403. /// <summary>
  2404. /// Provides handling for the
  2405. /// <see cref="E:System.Windows.UIElement.KeyDown" /> event.
  2406. /// </summary>
  2407. /// <param name="e">A <see cref="T:System.Windows.Input.KeyEventArgs" />
  2408. /// that contains the event data.</param>
  2409. protected override void OnKeyDown(KeyEventArgs e)
  2410. {
  2411. if (e == null)
  2412. {
  2413. throw new ArgumentNullException("e");
  2414. }
  2415. base.OnKeyDown(e);
  2416. if (e.Handled || !IsEnabled)
  2417. {
  2418. return;
  2419. }
  2420. // The drop down is open, pass along the key event arguments to the
  2421. // selection adapter. If it isn't handled by the adapter's logic,
  2422. // then we handle some simple navigation scenarios for controlling
  2423. // the drop down.
  2424. if (IsDropDownOpen)
  2425. {
  2426. if (SelectionAdapter != null)
  2427. {
  2428. SelectionAdapter.HandleKeyDown(e);
  2429. if (e.Handled)
  2430. {
  2431. return;
  2432. }
  2433. }
  2434. if (e.Key == Key.Escape)
  2435. {
  2436. OnAdapterSelectionCanceled(this, new RoutedEventArgs());
  2437. e.Handled = true;
  2438. }
  2439. }
  2440. else
  2441. {
  2442. // The drop down is not open, the Down key will toggle it open.
  2443. if (e.Key == Key.Down)
  2444. {
  2445. IsDropDownOpen = true;
  2446. e.Handled = true;
  2447. }
  2448. }
  2449. // Standard drop down navigation
  2450. switch (e.Key)
  2451. {
  2452. case Key.F4:
  2453. IsDropDownOpen = !IsDropDownOpen;
  2454. e.Handled = true;
  2455. break;
  2456. case Key.Enter:
  2457. OnAdapterSelectionComplete(this, new RoutedEventArgs());
  2458. e.Handled = true;
  2459. break;
  2460. default:
  2461. break;
  2462. }
  2463. }
  2464. /// <summary>
  2465. /// Update the visual state of the control.
  2466. /// </summary>
  2467. /// <param name="useTransitions">
  2468. /// A value indicating whether to automatically generate transitions to
  2469. /// the new state, or instantly transition to the new state.
  2470. /// </param>
  2471. void IUpdateVisualState.UpdateVisualState(bool useTransitions)
  2472. {
  2473. UpdateVisualState(useTransitions);
  2474. }
  2475. /// <summary>
  2476. /// Update the current visual state of the button.
  2477. /// </summary>
  2478. /// <param name="useTransitions">
  2479. /// True to use transitions when updating the visual state, false to
  2480. /// snap directly to the new visual state.
  2481. /// </param>
  2482. internal virtual void UpdateVisualState(bool useTransitions)
  2483. {
  2484. // Popup
  2485. VisualStateManager.GoToState(this, IsDropDownOpen ? VisualStates.StatePopupOpened : VisualStates.StatePopupClosed, useTransitions);
  2486. // Handle the Common and Focused states
  2487. Interaction.UpdateVisualStateBase(useTransitions);
  2488. }
  2489. }
  2490. }