PageRenderTime 55ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-toolkit/Microsoft.Phone.Controls.Toolkit/AutoCompleteBox/AutoCompleteBox.cs

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