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

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

https://bitbucket.org/jeremejevs/word-steps
C# | 2678 lines | 1397 code | 254 blank | 1027 comment | 300 complexity | 377f309c4951a40948130697eea689a5 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. }
  1231. SelectionAdapter = GetSelectionAdapterPart();
  1232. TextBox = GetTemplateChild(AutoCompleteBox.ElementTextBox) as TextBox;
  1233. if (TextBox != null)
  1234. {
  1235. #if SILVERLIGHT
  1236. #if WINDOWS_PHONE
  1237. TextBox.AddHandler(UIElement.KeyDownEvent, new KeyEventHandler(OnUIElementKeyDown), true);
  1238. TextBox.AddHandler(UIElement.KeyUpEvent, new KeyEventHandler(OnUIElementKeyUp), true);
  1239. #else
  1240. TextBox.AddHandler(TextBox.TextInputStartEvent, new TextCompositionEventHandler(OnTextBoxTextInputStart), true);
  1241. TextBox.AddHandler(TextBox.TextInputEvent, new TextCompositionEventHandler(OnTextBoxTextInput), true);
  1242. #endif
  1243. #else
  1244. TextBox.PreviewKeyDown += OnTextBoxPreviewKeyDown;
  1245. #endif
  1246. }
  1247. Interaction.OnApplyTemplateBase();
  1248. // If the drop down property indicates that the popup is open,
  1249. // flip its value to invoke the changed handler.
  1250. if (IsDropDownOpen && DropDownPopup != null && !DropDownPopup.IsOpen)
  1251. {
  1252. OpeningDropDown(false);
  1253. }
  1254. }
  1255. /// <summary>
  1256. /// Allows the popup wrapper to fire visual state change events.
  1257. /// </summary>
  1258. /// <param name="sender">The source object.</param>
  1259. /// <param name="e">The event data.</param>
  1260. private void OnDropDownPopupUpdateVisualStates(object sender, EventArgs e)
  1261. {
  1262. UpdateVisualState(true);
  1263. }
  1264. /// <summary>
  1265. /// Allows the popup wrapper to fire the FocusChanged event.
  1266. /// </summary>
  1267. /// <param name="sender">The source object.</param>
  1268. /// <param name="e">The event data.</param>
  1269. private void OnDropDownFocusChanged(object sender, EventArgs e)
  1270. {
  1271. FocusChanged(HasFocus());
  1272. }
  1273. /// <summary>
  1274. /// Begin closing the drop-down.
  1275. /// </summary>
  1276. /// <param name="oldValue">The original value.</param>
  1277. private void ClosingDropDown(bool oldValue)
  1278. {
  1279. bool delayedClosingVisual = false;
  1280. if (DropDownPopup != null)
  1281. {
  1282. delayedClosingVisual = DropDownPopup.UsesClosingVisualState;
  1283. }
  1284. RoutedPropertyChangingEventArgs<bool> args = new RoutedPropertyChangingEventArgs<bool>(IsDropDownOpenProperty, oldValue, false, true);
  1285. OnDropDownClosing(args);
  1286. if (_view == null || _view.Count == 0)
  1287. {
  1288. delayedClosingVisual = false;
  1289. }
  1290. if (args.Cancel)
  1291. {
  1292. _ignorePropertyChange = true;
  1293. SetValue(IsDropDownOpenProperty, oldValue);
  1294. }
  1295. else
  1296. {
  1297. // Immediately close the drop down window:
  1298. // When a popup closed visual state is present, the code path is
  1299. // slightly different and the actual call to CloseDropDown will
  1300. // be called only after the visual state's transition is done
  1301. #if !WINDOWS_PHONE
  1302. RaiseExpandCollapseAutomationEvent(oldValue, false);
  1303. #endif
  1304. if (!delayedClosingVisual)
  1305. {
  1306. CloseDropDown(oldValue, false);
  1307. }
  1308. }
  1309. UpdateVisualState(true);
  1310. }
  1311. /// <summary>
  1312. /// Begin opening the drop down by firing cancelable events, opening the
  1313. /// drop-down or reverting, depending on the event argument values.
  1314. /// </summary>
  1315. /// <param name="oldValue">The original value, if needed for a revert.</param>
  1316. private void OpeningDropDown(bool oldValue)
  1317. {
  1318. if (!IsCompletionEnabled)
  1319. {
  1320. return;
  1321. }
  1322. RoutedPropertyChangingEventArgs<bool> args = new RoutedPropertyChangingEventArgs<bool>(IsDropDownOpenProperty, oldValue, true, true);
  1323. // Opening
  1324. OnDropDownOpening(args);
  1325. if (args.Cancel)
  1326. {
  1327. _ignorePropertyChange = true;
  1328. SetValue(IsDropDownOpenProperty, oldValue);
  1329. }
  1330. else
  1331. {
  1332. #if !WINDOWS_PHONE
  1333. RaiseExpandCollapseAutomationEvent(oldValue, true);
  1334. #endif
  1335. OpenDropDown(oldValue, true);
  1336. }
  1337. UpdateVisualState(true);
  1338. }
  1339. #if !WINDOWS_PHONE
  1340. /// <summary>
  1341. /// Raise an expand/collapse event through the automation peer.
  1342. /// </summary>
  1343. /// <param name="oldValue">The old value.</param>
  1344. /// <param name="newValue">The new value.</param>
  1345. private void RaiseExpandCollapseAutomationEvent(bool oldValue, bool newValue)
  1346. {
  1347. #if SILVERLIGHT
  1348. AutoCompleteBoxAutomationPeer peer = FrameworkElementAutomationPeer.FromElement(this) as AutoCompleteBoxAutomationPeer;
  1349. if (peer != null)
  1350. {
  1351. peer.RaiseExpandCollapseAutomationEvent(oldValue, newValue);
  1352. }
  1353. #endif
  1354. }
  1355. #endif
  1356. #if !SILVERLIGHT
  1357. /// <summary>
  1358. /// Handles the PreviewKeyDown event on the TextBox for WPF. This method
  1359. /// is not implemented for Silverlight.
  1360. /// </summary>
  1361. /// <param name="sender">The source object.</param>
  1362. /// <param name="e">The event data.</param>
  1363. private void OnTextBoxPreviewKeyDown(object sender, KeyEventArgs e)
  1364. {
  1365. OnKeyDown(e);
  1366. }
  1367. #endif
  1368. /// <summary>
  1369. /// Connects to the DropDownPopup Closed event.
  1370. /// </summary>
  1371. /// <param name="sender">The source object.</param>
  1372. /// <param name="e">The event data.</param>
  1373. private void DropDownPopup_Closed(object sender, EventArgs e)
  1374. {
  1375. // Force the drop down dependency property to be false.
  1376. if (IsDropDownOpen)
  1377. {
  1378. IsDropDownOpen = false;
  1379. }
  1380. // Fire the DropDownClosed event
  1381. if (_popupHasOpened)
  1382. {
  1383. OnDropDownClosed(new RoutedPropertyChangedEventArgs<bool>(true, false));
  1384. }
  1385. }
  1386. #if !WINDOWS_PHONE
  1387. /// <summary>
  1388. /// Returns a
  1389. /// <see cref="T:System.Windows.Automation.Peers.AutoCompleteBoxAutomationPeer" />
  1390. /// for use by the Silverlight automation infrastructure.
  1391. /// </summary>
  1392. /// <returns>A
  1393. /// <see cref="T:System.Windows.Automation.Peers.AutoCompleteBoxAutomationPeer" />
  1394. /// for the <see cref="T:Microsoft.Phone.Controls.AutoCompleteBox" />
  1395. /// object.</returns>
  1396. protected override AutomationPeer OnCreateAutomationPeer()
  1397. {
  1398. #if SILVERLIGHT
  1399. return new AutoCompleteBoxAutomationPeer(this);
  1400. #else
  1401. return null;
  1402. #endif
  1403. }
  1404. #endif
  1405. #region Focus
  1406. /// <summary>
  1407. /// Handles the FocusChanged event.
  1408. /// </summary>
  1409. /// <param name="hasFocus">A value indicating whether the control
  1410. /// currently has the focus.</param>
  1411. private void FocusChanged(bool hasFocus)
  1412. {
  1413. // The OnGotFocus & OnLostFocus are asynchronously and cannot
  1414. // reliably tell you that have the focus. All they do is let you
  1415. // know that the focus changed sometime in the past. To determine
  1416. // if you currently have the focus you need to do consult the
  1417. // FocusManager (see HasFocus()).
  1418. if (hasFocus)
  1419. {
  1420. if (TextBox != null && TextBox.SelectionLength == 0)
  1421. {
  1422. #if !WINDOWS_PHONE
  1423. TextBox.SelectAll();
  1424. #endif
  1425. #if WINDOWS_PHONE
  1426. TextBox.Focus();
  1427. #endif
  1428. }
  1429. }
  1430. else
  1431. {
  1432. IsDropDownOpen = false;
  1433. _userCalledPopulate = false;
  1434. #if !WINDOWS_PHONE
  1435. if (TextBox != null)
  1436. {
  1437. TextBox.Select(TextBox.Text.Length, 0);
  1438. }
  1439. #endif
  1440. }
  1441. }
  1442. /// <summary>
  1443. /// Determines whether the text box or drop-down portion of the
  1444. /// <see cref="T:Microsoft.Phone.Controls.AutoCompleteBox" /> control has
  1445. /// focus.
  1446. /// </summary>
  1447. /// <returns>true to indicate the
  1448. /// <see cref="T:Microsoft.Phone.Controls.AutoCompleteBox" /> has focus;
  1449. /// otherwise, false.</returns>
  1450. protected bool HasFocus()
  1451. {
  1452. DependencyObject focused =
  1453. #if SILVERLIGHT
  1454. FocusManager.GetFocusedElement() as DependencyObject;
  1455. #else
  1456. FocusManager.GetFocusedElement(this) as DependencyObject;
  1457. #endif
  1458. while (focused != null)
  1459. {
  1460. if (object.ReferenceEquals(focused, this))
  1461. {
  1462. return true;
  1463. }
  1464. // This helps deal with popups that may not be in the same
  1465. // visual tree
  1466. DependencyObject parent = VisualTreeHelper.GetParent(focused);
  1467. if (parent == null)
  1468. {
  1469. // Try the logical parent.
  1470. FrameworkElement element = focused as FrameworkElement;
  1471. if (element != null)
  1472. {
  1473. parent = element.Parent;
  1474. }
  1475. }
  1476. focused = parent;
  1477. }
  1478. return false;
  1479. }
  1480. /// <summary>
  1481. /// Provides handling for the
  1482. /// <see cref="E:System.Windows.UIElement.GotFocus" /> event.
  1483. /// </summary>
  1484. /// <param name="e">A <see cref="T:System.Windows.RoutedEventArgs" />
  1485. /// that contains the event data.</param>
  1486. protected override void OnGotFocus(RoutedEventArgs e)
  1487. {
  1488. base.OnGotFocus(e);
  1489. FocusChanged(HasFocus());
  1490. }
  1491. /// <summary>
  1492. /// Provides handling for the
  1493. /// <see cref="E:System.Windows.UIElement.LostFocus" /> event.
  1494. /// </summary>
  1495. /// <param name="e">A <see cref="T:System.Windows.RoutedEventArgs" />
  1496. /// that contains the event data.</param>
  1497. protected override void OnLostFocus(RoutedEventArgs e)
  1498. {
  1499. base.OnLostFocus(e);
  1500. FocusChanged(HasFocus());
  1501. }
  1502. #endregion
  1503. /// <summary>
  1504. /// Handle the change of the IsEnabled property.
  1505. /// </summary>
  1506. /// <param name="sender">The source object.</param>
  1507. /// <param name="e">The event data.</param>
  1508. private void ControlIsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
  1509. {
  1510. bool isEnabled = (bool)e.NewValue;
  1511. if (!isEnabled)
  1512. {
  1513. IsDropDownOpen = false;
  1514. }
  1515. }
  1516. /// <summary>
  1517. /// Returns the
  1518. /// <see cref="T:Microsoft.Phone.Controls.ISelectionAdapter" /> part, if
  1519. /// possible.
  1520. /// </summary>
  1521. /// <returns>
  1522. /// A <see cref="T:Microsoft.Phone.Controls.ISelectionAdapter" /> object,
  1523. /// if possible. Otherwise, null.
  1524. /// </returns>
  1525. [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Following the GetTemplateChild pattern for the method.")]
  1526. protected virtual ISelectionAdapter GetSelectionAdapterPart()
  1527. {
  1528. ISelectionAdapter adapter = null;
  1529. Selector selector = GetTemplateChild(ElementSelector) as Selector;
  1530. if (selector != null)
  1531. {
  1532. // Check if it is already an IItemsSelector
  1533. adapter = selector as ISelectionAdapter;
  1534. if (adapter == null)
  1535. {
  1536. // Built in support for wrapping a Selector control
  1537. adapter = new SelectorSelectionAdapter(selector);
  1538. }
  1539. }
  1540. if (adapter == null)
  1541. {
  1542. adapter = GetTemplateChild(ElementSelectionAdapter) as ISelectionAdapter;
  1543. }
  1544. return adapter;
  1545. }
  1546. /// <summary>
  1547. /// Handles the timer tick when using a populate delay.
  1548. /// </summary>
  1549. /// <param name="sender">The source object.</param>
  1550. /// <param name="e">The event arguments.</param>
  1551. private void PopulateDropDown(object sender, EventArgs e)
  1552. {
  1553. if (_delayTimer != null)
  1554. {
  1555. _delayTimer.Stop();
  1556. }
  1557. // Update the prefix/search text.
  1558. SearchText = Text;
  1559. // The Populated event enables advanced, custom filtering. The
  1560. // client needs to directly update the ItemsSource collection or
  1561. // call the Populate method on the control to continue the
  1562. // display process if Cancel is set to true.
  1563. PopulatingEventArgs populating = new PopulatingEventArgs(SearchText);
  1564. OnPopulating(populating);
  1565. if (!populating.Cancel)
  1566. {
  1567. PopulateComplete();
  1568. }
  1569. }
  1570. /// <summary>
  1571. /// Raises the
  1572. /// <see cref="E:Microsoft.Phone.Controls.AutoCompleteBox.Populating" />
  1573. /// event.
  1574. /// </summary>
  1575. /// <param name="e">A
  1576. /// <see cref="T:Microsoft.Phone.Controls.PopulatingEventArgs" /> that
  1577. /// contains the event data.</param>
  1578. protected virtual void OnPopulating(PopulatingEventArgs e)
  1579. {
  1580. PopulatingEventHandler handler = Populating;
  1581. if (handler != null)
  1582. {
  1583. handler(this, e);
  1584. }
  1585. }
  1586. /// <summary>
  1587. /// Raises the
  1588. /// <see cref="E:Microsoft.Phone.Controls.AutoCompleteBox.Populated" />
  1589. /// event.
  1590. /// </summary>
  1591. /// <param name="e">A
  1592. /// <see cref="T:Microsoft.Phone.Controls.PopulatedEventArgs" />
  1593. /// that contains the event data.</param>
  1594. protected virtual void OnPopulated(PopulatedEventArgs e)
  1595. {
  1596. PopulatedEventHandler handler = Populated;
  1597. if (handler != null)
  1598. {
  1599. handler(this, e);
  1600. }
  1601. }
  1602. /// <summary>
  1603. /// Raises the
  1604. /// <see cref="E:Microsoft.Phone.Controls.AutoCompleteBox.SelectionChanged" />
  1605. /// event.
  1606. /// </summary>
  1607. /// <param name="e">A
  1608. /// <see cref="T:Microsoft.Phone.Controls.SelectionChangedEventArgs" />
  1609. /// that contains the event data.</param>
  1610. protected virtual void OnSelectionChanged(SelectionChangedEventArgs e)
  1611. {
  1612. SelectionChangedEventHandler handler = SelectionChanged;
  1613. if (handler != null)
  1614. {
  1615. handler(this, e);
  1616. }
  1617. }
  1618. /// <summary>
  1619. /// Raises the
  1620. /// <see cref="E:Microsoft.Phone.Controls.AutoCompleteBox.DropDownOpening" />
  1621. /// event.
  1622. /// </summary>
  1623. /// <param name="e">A
  1624. /// <see cref="T:Microsoft.Phone.Controls.RoutedPropertyChangingEventArgs`1" />
  1625. /// that contains the event data.</param>
  1626. protected virtual void OnDropDownOpening(RoutedPropertyChangingEventArgs<bool> e)
  1627. {
  1628. RoutedPropertyChangingEventHandler<bool> handler = DropDownOpening;
  1629. if (handler != null)
  1630. {
  1631. handler(this, e);
  1632. }
  1633. }
  1634. /// <summary>
  1635. /// Raises the
  1636. /// <see cref="E:Microsoft.Phone.Controls.AutoCompleteBox.DropDownOpened" />
  1637. /// event.
  1638. /// </summary>
  1639. /// <param name="e">A
  1640. /// <see cref="T:System.Windows.RoutedPropertyChangedEventArgs`1" />
  1641. /// that contains the event data.</param>
  1642. protected virtual void OnDropDownOpened(RoutedPropertyChangedEventArgs<bool> e)
  1643. {
  1644. RoutedPropertyChangedEventHandler<bool> handler = DropDownOpened;
  1645. if (handler != null)
  1646. {
  1647. handler(this, e);
  1648. }
  1649. }
  1650. /// <summary>
  1651. /// Raises the
  1652. /// <see cref="E:Microsoft.Phone.Controls.AutoCompleteBox.DropDownClosing" />
  1653. /// event.
  1654. /// </summary>
  1655. /// <param name="e">A
  1656. /// <see cref="T:Microsoft.Phone.Controls.RoutedPropertyChangingEventArgs`1" />
  1657. /// that contains the event data.</param>
  1658. protected virtual void OnDropDownClosing(RoutedPropertyChangingEventArgs<bool> e)
  1659. {
  1660. RoutedPropertyChangingEventHandler<bool> handler = DropDownClosing;
  1661. if (handler != null)
  1662. {
  1663. handler(this, e);
  1664. }
  1665. }
  1666. /// <summary>
  1667. /// Raises the
  1668. /// <see cref="E:Microsoft.Phone.Controls.AutoCompleteBox.DropDownClosed" />
  1669. /// event.
  1670. /// </summary>
  1671. /// <param name="e">A
  1672. /// <see cref="T:System.Windows.RoutedPropertyChangedEventArgs`1" />
  1673. /// which contains the event data.</param>
  1674. protected virtual void OnDropDownClosed(RoutedPropertyChangedEventArgs<bool> e)
  1675. {
  1676. RoutedPropertyChangedEventHandler<bool> handler = DropDownClosed;
  1677. if (handler != null)
  1678. {
  1679. handler(this, e);
  1680. }
  1681. }
  1682. /// <summary>
  1683. /// Formats an Item for text comparisons based on Converter
  1684. /// and ConverterCulture properties.
  1685. /// </summary>
  1686. /// <param name="value">The object to format.</param>
  1687. /// <param name="clearDataContext">A value indicating whether to clear
  1688. /// the data context after the lookup is performed.</param>
  1689. /// <returns>Formatted Value.</returns>
  1690. private string FormatValue(object value, bool clearDataContext)
  1691. {
  1692. string str = FormatValue(value);
  1693. if (clearDataContext && _valueBindingEvaluator != null)
  1694. {
  1695. _valueBindingEvaluator.ClearDataContext();
  1696. }
  1697. return str;
  1698. }
  1699. /// <summary>
  1700. /// Converts the specified object to a string by using the
  1701. /// <see cref="P:System.Windows.Data.Binding.Converter" /> and
  1702. /// <see cref="P:System.Windows.Data.Binding.ConverterCulture" /> values
  1703. /// of the binding object specified by the
  1704. /// <see cref="P:Microsoft.Phone.Controls.AutoCompleteBox.ValueMemberBinding" />
  1705. /// property.
  1706. /// </summary>
  1707. /// <param name="value">The object to format as a string.</param>
  1708. /// <returns>The string representation of the specified object.</returns>
  1709. /// <remarks>
  1710. /// Override this method to provide a custom string conversion.
  1711. /// </remarks>
  1712. protected virtual string FormatValue(object value)
  1713. {
  1714. if (_valueBindingEvaluator != null)
  1715. {
  1716. return _valueBindingEvaluator.GetDynamicValue(value) ?? string.Empty;
  1717. }
  1718. return value == null ? string.Empty : value.ToString();
  1719. }
  1720. /// <summary>
  1721. /// Raises the
  1722. /// <see cref="E:Microsoft.Phone.Controls.AutoCompleteBox.TextChanged" />
  1723. /// event.
  1724. /// </summary>
  1725. /// <param name="e">A <see cref="T:System.Windows.RoutedEventArgs" />
  1726. /// that contains the event data.</param>
  1727. protected virtual void OnTextChanged(RoutedEventArgs e)
  1728. {
  1729. RoutedEventHandler handler = TextChanged;
  1730. if (handler != null)
  1731. {
  1732. handler(this, e);
  1733. }
  1734. }
  1735. /// <summary>
  1736. /// Handle the TextChanged event that is directly attached to the
  1737. /// TextBox part. This ensures that only user initiated actions will
  1738. /// result in an AutoCompleteBox suggestion and operation.
  1739. /// </summary>
  1740. /// <param name="sender">The source TextBox object.</param>
  1741. /// <param name="e">The TextChanged event data.</param>
  1742. private void OnTextBoxTextChanged(object sender, TextChangedEventArgs e)
  1743. {
  1744. // Call the central updated text method as a user-initiated action
  1745. TextUpdated(_text.Text, true);
  1746. }
  1747. /// <summary>
  1748. /// When selection changes, save the location of the selection start.
  1749. /// </summary>
  1750. /// <param name="sender">The source object.</param>
  1751. /// <param name="e">The event data.</param>
  1752. private void OnTextBoxSelectionChanged(object sender, RoutedEventArgs e)
  1753. {
  1754. // If ignoring updates. This happens after text is updated, and
  1755. // before the PopulateComplete method is called. Required for the
  1756. // IsTextCompletionEnabled feature.
  1757. // Also, do not update if the user is in the middle of using an IME
  1758. if (_ignoreTextSelectionChange || _inputtingText)
  1759. {
  1760. return;
  1761. }
  1762. _textSelectionStart = _text.SelectionStart;
  1763. }
  1764. #if WINDOWS_PHONE
  1765. /// <summary>
  1766. /// Handles KeyDown to set a flag that indicates that the user is inputting
  1767. /// text. This is important for IME input.
  1768. /// </summary>
  1769. /// <param name="sender">The source UIElement object.</param>
  1770. /// <param name="e">The KeyDown event data.</param>
  1771. private void OnUIElementKeyDown(object sender, KeyEventArgs e)
  1772. {
  1773. _inputtingText = true;
  1774. }
  1775. /// <summary>
  1776. /// Handles KeyUp to turn off the flag that indicates that the user is inputting
  1777. /// text. This is important for IME input.
  1778. /// </summary>
  1779. /// <param name="sender">The source UIElement object.</param>
  1780. /// <param name="e">The KeyUp event data.</param>
  1781. private void OnUIElementKeyUp(object sender, KeyEventArgs e)
  1782. {
  1783. _inputtingText = false;
  1784. }
  1785. #else
  1786. /// <summary>
  1787. /// Handles TextInputStart 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 TextBox object.</param>
  1791. /// <param name="e">The TextInputStart event data.</param>
  1792. private void OnTextBoxTextInputStart(object sender, KeyEventArgs e)
  1793. {
  1794. _inputtingText = true;
  1795. }
  1796. /// <summary>
  1797. /// Handles TextInput 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 TextBox object.</param>
  1801. /// <param name="e">The TextInput event data.</param>
  1802. private void OnTextBoxTextInput(object sender, KeyEventArgs e)
  1803. {
  1804. _inputtingText = false;
  1805. }
  1806. #endif
  1807. /// <summary>
  1808. /// Updates both the text box value and underlying text dependency
  1809. /// property value if and when they change. Automatically fires the
  1810. /// text changed events when there is a change.
  1811. /// </summary>
  1812. /// <param name="value">The new string value.</param>
  1813. private void UpdateTextValue(string value)
  1814. {
  1815. UpdateTextValue(value, null);
  1816. }
  1817. /// <summary>
  1818. /// Updates both the text box value and underlying text dependency
  1819. /// property value if and when they change. Automatically fires the
  1820. /// text changed events when there is a change.
  1821. /// </summary>
  1822. /// <param name="value">The new string value.</param>
  1823. /// <param name="userInitiated">A nullable bool value indicating whether
  1824. /// the action was user initiated. In a user initiated mode, the
  1825. /// underlying text dependency property is updated. In a non-user
  1826. /// interaction, the text box value is updated. When user initiated is
  1827. /// null, all values are updated.</param>
  1828. private void UpdateTextValue(string value, bool? userInitiated)
  1829. {
  1830. // Update the Text dependency property
  1831. if ((userInitiated == null || userInitiated == true) && Text != value)
  1832. {
  1833. _ignoreTextPropertyChange++;
  1834. Text = value;
  1835. OnTextChanged(new RoutedEventArgs());
  1836. }
  1837. // Update the TextBox's Text dependency property
  1838. if ((userInitiated == null || userInitiated == false) && TextBox != null && TextBox.Text != value)
  1839. {
  1840. _ignoreTextPropertyChange++;
  1841. TextBox.Text = value ?? string.Empty;
  1842. // Text dependency property value was set, fire event
  1843. if (Text == value || Text == null)
  1844. {
  1845. OnTextChanged(new RoutedEventArgs());
  1846. }
  1847. }
  1848. }
  1849. /// <summary>
  1850. /// Handle the update of the text for the control from any source,
  1851. /// including the TextBox part and the Text dependency property.
  1852. /// </summary>
  1853. /// <param name="newText">The new text.</param>
  1854. /// <param name="userInitiated">A value indicating whether the update
  1855. /// is a user-initiated action. This should be a True value when the
  1856. /// TextUpdated method is called from a TextBox event handler.</param>
  1857. private void TextUpdated(string newText, bool userInitiated)
  1858. {
  1859. // Only process this event if it is coming from someone outside
  1860. // setting the Text dependency property directly.
  1861. if (_ignoreTextPropertyChange > 0)
  1862. {
  1863. _ignoreTextPropertyChange--;
  1864. return;
  1865. }
  1866. if (newText == null)
  1867. {
  1868. newText = string.Empty;
  1869. }
  1870. // The TextBox.TextChanged event was not firing immediately and
  1871. // was causing an immediate update, even with wrapping. If there is
  1872. // a selection currently, no update should happen.
  1873. if (IsTextCompletionEnabled && TextBox != null && TextBox.SelectionLength > 0 && TextBox.SelectionStart != TextBox.Text.Length)
  1874. {
  1875. return;
  1876. }
  1877. // Evaluate the conditions needed for completion.
  1878. // 1. Minimum prefix length
  1879. // 2. If a delay timer is in use, use it
  1880. bool populateReady = newText.Length >= MinimumPrefixLength && MinimumPrefixLength >= 0;
  1881. _userCalledPopulate = populateReady ? userInitiated : false;
  1882. // Update the interface and values only as necessary
  1883. UpdateTextValue(newText, userInitiated);
  1884. if (populateReady)
  1885. {
  1886. _ignoreTextSelectionChange = true;
  1887. if (_delayTimer != null)
  1888. {
  1889. _delayTimer.Start();
  1890. }
  1891. else
  1892. {
  1893. PopulateDropDown(this, EventArgs.Empty);
  1894. }
  1895. }
  1896. else
  1897. {
  1898. SearchText = string.Empty;
  1899. if (SelectedItem != null)
  1900. {
  1901. _skipSelectedItemTextUpdate = true;
  1902. }
  1903. SelectedItem = null;
  1904. if (IsDropDownOpen)
  1905. {
  1906. IsDropDownOpen = false;
  1907. }
  1908. }
  1909. }
  1910. /// <summary>
  1911. /// Notifies the
  1912. /// <see cref="T:Microsoft.Phone.Controls.AutoCompleteBox" /> that the
  1913. /// <see cref="P:Microsoft.Phone.Controls.AutoCompleteBox.ItemsSource" />
  1914. /// property has been set and the data can be filtered to provide
  1915. /// possible matches in the drop-down.
  1916. /// </summary>
  1917. /// <remarks>
  1918. /// Call this method when you are providing custom population of
  1919. /// the drop-down portion of the AutoCompleteBox, to signal the control
  1920. /// that you are done with the population process.
  1921. /// Typically, you use PopulateComplete when the population process
  1922. /// is a long-running process and you want to cancel built-in filtering
  1923. /// of the ItemsSource items. In this case, you can handle the
  1924. /// Populated event and set PopulatingEventArgs.Cancel to true.
  1925. /// When the long-running process has completed you call
  1926. /// PopulateComplete to indicate the drop-down is populated.
  1927. /// </remarks>
  1928. public void PopulateComplete()
  1929. {
  1930. // Apply the search filter
  1931. RefreshView();
  1932. // Fire the Populated event containing the read-only view data.
  1933. PopulatedEventArgs populated = new PopulatedEventArgs(new ReadOnlyCollection<object>(_view));
  1934. OnPopulated(populated);
  1935. if (SelectionAdapter != null && SelectionAdapter.ItemsSource != _view)
  1936. {
  1937. SelectionAdapter.ItemsSource = _view;
  1938. }
  1939. bool isDropDownOpen = _userCalledPopulate && (_view.Count > 0);
  1940. if (isDropDownOpen != IsDropDownOpen)
  1941. {
  1942. _ignorePropertyChange = true;
  1943. IsDropDownOpen = isDropDownOpen;
  1944. }
  1945. if (IsDropDownOpen)
  1946. {
  1947. OpeningDropDown(false);
  1948. if (DropDownPopup != null)
  1949. {
  1950. #if WINDOWS_PHONE
  1951. DropDownPopup.Arrange(null);
  1952. #else
  1953. DropDownPopup.Arrange();
  1954. #endif
  1955. }
  1956. }
  1957. else
  1958. {
  1959. ClosingDropDown(true);
  1960. }
  1961. UpdateTextCompletion(_userCalledPopulate);
  1962. }
  1963. /// <summary>
  1964. /// Performs text completion, if enabled, and a lookup on the underlying
  1965. /// item values for an exact match. Will update the SelectedItem value.
  1966. /// </summary>
  1967. /// <param name="userInitiated">A value indicating whether the operation
  1968. /// was user initiated. Text completion will not be performed when not
  1969. /// directly initiated by the user.</param>
  1970. private void UpdateTextCompletion(bool userInitiated)
  1971. {
  1972. // By default this method will clear the selected value
  1973. object newSelectedItem = null;
  1974. string text = Text;
  1975. // Text search is StartsWith explicit and only when enabled, in
  1976. // line with WPF's ComboBox lookup. When in use it will associate
  1977. // a Value with the Text if it is found in ItemsSource. This is
  1978. // only valid when there is data and the user initiated the action.
  1979. if (_view.Count > 0)
  1980. {
  1981. if (IsTextCompletionEnabled && TextBox != null && userInitiated)
  1982. {
  1983. int currentLength = TextBox.Text.Length;
  1984. int selectionStart = TextBox.SelectionStart;
  1985. if (selectionStart == text.Length && selectionStart > _textSelectionStart)
  1986. {
  1987. // When the FilterMode dependency property is set to
  1988. // either StartsWith or StartsWithCaseSensitive, the
  1989. // first item in the view is used. This will improve
  1990. // performance on the lookup. It assumes that the
  1991. // FilterMode the user has selected is an acceptable
  1992. // case sensitive matching function for their scenario.
  1993. object top = FilterMode == AutoCompleteFilterMode.StartsWith || FilterMode == AutoCompleteFilterMode.StartsWithCaseSensitive
  1994. ? _view[0]
  1995. : TryGetMatch(text, _view, AutoCompleteSearch.GetFilter(AutoCompleteFilterMode.StartsWith));
  1996. // If the search was successful, update SelectedItem
  1997. if (top != null)
  1998. {
  1999. newSelectedItem = top;
  2000. string topString = FormatValue(top, true);
  2001. // Only replace partially when the two words being the same
  2002. int minLength = Math.Min(topString.Length, Text.Length);
  2003. if (AutoCompleteSearch.Equals(Text.Substring(0, minLength), topString.Substring(0, minLength)))
  2004. {
  2005. // Update the text
  2006. UpdateTextValue(topString);
  2007. // Select the text past the user's caret
  2008. TextBox.SelectionStart = currentLength;
  2009. TextBox.SelectionLength = topString.Length - currentLength;
  2010. }
  2011. }
  2012. }
  2013. }
  2014. else
  2015. {
  2016. // Perform an exact string lookup for the text. This is a
  2017. // design change from the original Toolkit release when the
  2018. // IsTextCompletionEnabled property behaved just like the
  2019. // WPF ComboBox's IsTextSearchEnabled property.
  2020. //
  2021. // This change provides the behavior that most people expect
  2022. // to find: a lookup for the value is always performed.
  2023. newSelectedItem = TryGetMatch(text, _view, AutoCompleteSearch.GetFilter(AutoCompleteFilterMode.EqualsCaseSensitive));
  2024. }
  2025. }
  2026. // Update the selected item property
  2027. if (SelectedItem != newSelectedItem)
  2028. {
  2029. _skipSelectedItemTextUpdate = true;
  2030. }
  2031. SelectedItem = newSelectedItem;
  2032. // Restore updates for TextSelection
  2033. if (_ignoreTextSelectionChange)
  2034. {
  2035. _ignoreTextSelectionChange = false;
  2036. if (TextBox != null && !_inputtingText)
  2037. {
  2038. _textSelectionStart = TextBox.SelectionStart;
  2039. }
  2040. }
  2041. }
  2042. /// <summary>
  2043. /// Attempts to look through the view and locate the specific exact
  2044. /// text match.
  2045. /// </summary>
  2046. /// <param name="searchText">The search text.</param>
  2047. /// <param name="view">The view reference.</param>
  2048. /// <param name="predicate">The predicate to use for the partial or
  2049. /// exact match.</param>
  2050. /// <returns>Returns the object or null.</returns>
  2051. private object TryGetMatch(string searchText, ObservableCollection<object> view, AutoCompleteFilterPredicate<string> predicate)
  2052. {
  2053. if (view != null && view.Count > 0)
  2054. {
  2055. foreach (object o in view)
  2056. {
  2057. if (predicate(searchText, FormatValue(o)))
  2058. {
  2059. return o;
  2060. }
  2061. }
  2062. }
  2063. return null;
  2064. }
  2065. /// <summary>
  2066. /// A simple helper method to clear the view and ensure that a view
  2067. /// object is always present and not null.
  2068. /// </summary>
  2069. private void ClearView()
  2070. {
  2071. if (_view == null)
  2072. {
  2073. _view = new ObservableCollection<object>();
  2074. }
  2075. else
  2076. {
  2077. _view.Clear();
  2078. }
  2079. }
  2080. /// <summary>
  2081. /// Walks through the items enumeration. Performance is not going to be
  2082. /// perfect with the current implementation.
  2083. /// </summary>
  2084. private void RefreshView()
  2085. {
  2086. if (_items == null)
  2087. {
  2088. ClearView();
  2089. return;
  2090. }
  2091. // Cache the current text value
  2092. string text = Text ?? string.Empty;
  2093. // Determine if any filtering mode is on
  2094. bool stringFiltering = TextFilter != null;
  2095. bool objectFiltering = FilterMode == AutoCompleteFilterMode.Custom && TextFilter == null;
  2096. int view_index = 0;
  2097. int view_count = _view.Count;
  2098. List<object> items = _items;
  2099. foreach (object item in items)
  2100. {
  2101. bool inResults = !(stringFiltering || objectFiltering);
  2102. if (!inResults)
  2103. {
  2104. inResults = stringFiltering ? TextFilter(text, FormatValue(item)) : ItemFilter(text, item);
  2105. }
  2106. if (view_count > view_index && inResults && _view[view_index] == item)
  2107. {
  2108. // Item is still in the view
  2109. view_index++;
  2110. }
  2111. else if (inResults)
  2112. {
  2113. // Insert the item
  2114. if (view_count > view_index && _view[view_index] != item)
  2115. {
  2116. // Replace item
  2117. // Unfortunately replacing via index throws a fatal
  2118. // exception: View[view_index] = item;
  2119. // Cost: O(n) vs O(1)
  2120. _view.RemoveAt(view_index);
  2121. _view.Insert(view_index, item);
  2122. view_index++;
  2123. }
  2124. else
  2125. {
  2126. // Add the item
  2127. if (view_index == view_count)
  2128. {
  2129. // Constant time is preferred (Add).
  2130. _view.Add(item);
  2131. }
  2132. else
  2133. {
  2134. _view.Insert(view_index, item);
  2135. }
  2136. view_index++;
  2137. view_count++;
  2138. }
  2139. }
  2140. else if (view_count > view_index && _view[view_index] == item)
  2141. {
  2142. // Remove the item
  2143. _view.RemoveAt(view_index);
  2144. view_count--;
  2145. }
  2146. }
  2147. // Clear the evaluator to discard a reference to the last item
  2148. if (_valueBindingEvaluator != null)
  2149. {
  2150. _valueBindingEvaluator.ClearDataContext();
  2151. }
  2152. }
  2153. /// <summary>
  2154. /// Handle any change to the ItemsSource dependency property, update
  2155. /// the underlying ObservableCollection view, and set the selection
  2156. /// adapter's ItemsSource to the view if appropriate.
  2157. /// </summary>
  2158. /// <param name="oldValue">The old enumerable reference.</param>
  2159. /// <param name="newValue">The new enumerable reference.</param>
  2160. [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "oldValue", Justification = "This makes it easy to add validation or other changes in the future.")]
  2161. private void OnItemsSourceChanged(IEnumerable oldValue, IEnumerable newValue)
  2162. {
  2163. // Remove handler for oldValue.CollectionChanged (if present)
  2164. INotifyCollectionChanged oldValueINotifyCollectionChanged = oldValue as INotifyCollectionChanged;
  2165. if (null != oldValueINotifyCollectionChanged && null != _collectionChangedWeakEventListener)
  2166. {
  2167. _collectionChangedWeakEventListener.Detach();
  2168. _collectionChangedWeakEventListener = null;
  2169. }
  2170. // Add handler for newValue.CollectionChanged (if possible)
  2171. INotifyCollectionChanged newValueINotifyCollectionChanged = newValue as INotifyCollectionChanged;
  2172. if (null != newValueINotifyCollectionChanged)
  2173. {
  2174. _collectionChangedWeakEventListener = new WeakEventListener<AutoCompleteBox, object, NotifyCollectionChangedEventArgs>(this);
  2175. _collectionChangedWeakEventListener.OnEventAction = (instance, source, eventArgs) => instance.ItemsSourceCollectionChanged(source, eventArgs);
  2176. _collectionChangedWeakEventListener.OnDetachAction = (weakEventListener) => newValueINotifyCollectionChanged.CollectionChanged -= weakEventListener.OnEvent;
  2177. newValueINotifyCollectionChanged.CollectionChanged += _collectionChangedWeakEventListener.OnEvent;
  2178. }
  2179. // Store a local cached copy of the data
  2180. _items = newValue == null ? null : new List<object>(newValue.Cast<object>().ToList());
  2181. // Clear and set the view on the selection adapter
  2182. ClearView();
  2183. if (SelectionAdapter != null && SelectionAdapter.ItemsSource != _view)
  2184. {
  2185. SelectionAdapter.ItemsSource = _view;
  2186. }
  2187. if (IsDropDownOpen)
  2188. {
  2189. RefreshView();
  2190. }
  2191. }
  2192. /// <summary>
  2193. /// Method that handles the ObservableCollection.CollectionChanged event for the ItemsSource property.
  2194. /// </summary>
  2195. /// <param name="sender">The object that raised the event.</param>
  2196. /// <param name="e">The event data.</param>
  2197. private void ItemsSourceCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
  2198. {
  2199. // Update the cache
  2200. if (e.Action == NotifyCollectionChangedAction.Remove && e.OldItems != null)
  2201. {
  2202. for (int index = 0; index < e.OldItems.Count; index++)
  2203. {
  2204. _items.RemoveAt(e.OldStartingIndex);
  2205. }
  2206. }
  2207. if (e.Action == NotifyCollectionChangedAction.Add && e.NewItems != null && _items.Count >= e.NewStartingIndex)
  2208. {
  2209. for (int index = 0; index < e.NewItems.Count; index++)
  2210. {
  2211. _items.Insert(e.NewStartingIndex + index, e.NewItems[index]);
  2212. }
  2213. }
  2214. if (e.Action == NotifyCollectionChangedAction.Replace && e.NewItems != null && e.OldItems != null)
  2215. {
  2216. for (int index = 0; index < e.NewItems.Count; index++)
  2217. {
  2218. _items[e.NewStartingIndex] = e.NewItems[index];
  2219. }
  2220. }
  2221. // Update the view
  2222. if (e.Action == NotifyCollectionChangedAction.Remove || e.Action == NotifyCollectionChangedAction.Replace)
  2223. {
  2224. for (int index = 0; index < e.OldItems.Count; index++)
  2225. {
  2226. _view.Remove(e.OldItems[index]);
  2227. }
  2228. }
  2229. if (e.Action == NotifyCollectionChangedAction.Reset)
  2230. {
  2231. // Significant changes to the underlying data.
  2232. ClearView();
  2233. if (ItemsSource != null)
  2234. {
  2235. _items = new List<object>(ItemsSource.Cast<object>().ToList());
  2236. }
  2237. }
  2238. // Refresh the observable collection used in the selection adapter.
  2239. RefreshView();
  2240. }
  2241. #region Selection Adapter
  2242. /// <summary>
  2243. /// Handles the SelectionChanged event of the selection adapter.
  2244. /// </summary>
  2245. /// <param name="sender">The source object.</param>
  2246. /// <param name="e">The selection changed event data.</param>
  2247. private void OnAdapterSelectionChanged(object sender, SelectionChangedEventArgs e)
  2248. {
  2249. SelectedItem = _adapter.SelectedItem;
  2250. }
  2251. /// <summary>
  2252. /// Handles the Commit event on the selection adapter.
  2253. /// </summary>
  2254. /// <param name="sender">The source object.</param>
  2255. /// <param name="e">The event data.</param>
  2256. private void OnAdapterSelectionComplete(object sender, RoutedEventArgs e)
  2257. {
  2258. IsDropDownOpen = false;
  2259. // Completion will update the selected value
  2260. UpdateTextCompletion(false);
  2261. // Text should not be selected
  2262. if (TextBox != null)
  2263. {
  2264. TextBox.Select(TextBox.Text.Length, 0);
  2265. }
  2266. Focus();
  2267. }
  2268. /// <summary>
  2269. /// Handles the Cancel event on the selection adapter.
  2270. /// </summary>
  2271. /// <param name="sender">The source object.</param>
  2272. /// <param name="e">The event data.</param>
  2273. private void OnAdapterSelectionCanceled(object sender, RoutedEventArgs e)
  2274. {
  2275. UpdateTextValue(SearchText);
  2276. // Completion will update the selected value
  2277. UpdateTextCompletion(false);
  2278. }
  2279. #endregion
  2280. #region Popup
  2281. /// <summary>
  2282. /// Handles MaxDropDownHeightChanged by re-arranging and updating the
  2283. /// popup arrangement.
  2284. /// </summary>
  2285. /// <param name="newValue">The new value.</param>
  2286. [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "newValue", Justification = "This makes it easy to add validation or other changes in the future.")]
  2287. private void OnMaxDropDownHeightChanged(double newValue)
  2288. {
  2289. if (DropDownPopup != null)
  2290. {
  2291. DropDownPopup.MaxDropDownHeight = newValue;
  2292. #if WINDOWS_PHONE
  2293. DropDownPopup.Arrange(null);
  2294. #else
  2295. DropDownPopup.Arrange();
  2296. #endif
  2297. }
  2298. UpdateVisualState(true);
  2299. }
  2300. /// <summary>
  2301. /// Private method that directly opens the popup, checks the expander
  2302. /// button, and then fires the Opened event.
  2303. /// </summary>
  2304. /// <param name="oldValue">The old value.</param>
  2305. /// <param name="newValue">The new value.</param>
  2306. private void OpenDropDown(bool oldValue, bool newValue)
  2307. {
  2308. if (DropDownPopup != null)
  2309. {
  2310. DropDownPopup.IsOpen = true;
  2311. }
  2312. _popupHasOpened = true;
  2313. OnDropDownOpened(new RoutedPropertyChangedEventArgs<bool>(oldValue, newValue));
  2314. }
  2315. /// <summary>
  2316. /// Private method that directly closes the popup, flips the Checked
  2317. /// value, and then fires the Closed event.
  2318. /// </summary>
  2319. /// <param name="oldValue">The old value.</param>
  2320. /// <param name="newValue">The new value.</param>
  2321. private void CloseDropDown(bool oldValue, bool newValue)
  2322. {
  2323. if (_popupHasOpened)
  2324. {
  2325. if (SelectionAdapter != null)
  2326. {
  2327. SelectionAdapter.SelectedItem = null;
  2328. }
  2329. if (DropDownPopup != null)
  2330. {
  2331. DropDownPopup.IsOpen = false;
  2332. }
  2333. OnDropDownClosed(new RoutedPropertyChangedEventArgs<bool>(oldValue, newValue));
  2334. }
  2335. }
  2336. #endregion
  2337. /// <summary>
  2338. /// Provides handling for the
  2339. /// <see cref="E:System.Windows.UIElement.KeyDown" /> event.
  2340. /// </summary>
  2341. /// <param name="e">A <see cref="T:System.Windows.Input.KeyEventArgs" />
  2342. /// that contains the event data.</param>
  2343. protected override void OnKeyDown(KeyEventArgs e)
  2344. {
  2345. if (e == null)
  2346. {
  2347. throw new ArgumentNullException("e");
  2348. }
  2349. base.OnKeyDown(e);
  2350. if (e.Handled || !IsEnabled)
  2351. {
  2352. return;
  2353. }
  2354. // The drop down is open, pass along the key event arguments to the
  2355. // selection adapter. If it isn't handled by the adapter's logic,
  2356. // then we handle some simple navigation scenarios for controlling
  2357. // the drop down.
  2358. if (IsDropDownOpen)
  2359. {
  2360. if (SelectionAdapter != null)
  2361. {
  2362. SelectionAdapter.HandleKeyDown(e);
  2363. if (e.Handled)
  2364. {
  2365. return;
  2366. }
  2367. }
  2368. if (e.Key == Key.Escape)
  2369. {
  2370. OnAdapterSelectionCanceled(this, new RoutedEventArgs());
  2371. e.Handled = true;
  2372. }
  2373. }
  2374. else
  2375. {
  2376. // The drop down is not open, the Down key will toggle it open.
  2377. if (e.Key == Key.Down)
  2378. {
  2379. IsDropDownOpen = true;
  2380. e.Handled = true;
  2381. }
  2382. }
  2383. // Standard drop down navigation
  2384. switch (e.Key)
  2385. {
  2386. case Key.F4:
  2387. IsDropDownOpen = !IsDropDownOpen;
  2388. e.Handled = true;
  2389. break;
  2390. case Key.Enter:
  2391. OnAdapterSelectionComplete(this, new RoutedEventArgs());
  2392. e.Handled = true;
  2393. break;
  2394. default:
  2395. break;
  2396. }
  2397. }
  2398. /// <summary>
  2399. /// Update the visual state of the control.
  2400. /// </summary>
  2401. /// <param name="useTransitions">
  2402. /// A value indicating whether to automatically generate transitions to
  2403. /// the new state, or instantly transition to the new state.
  2404. /// </param>
  2405. void IUpdateVisualState.UpdateVisualState(bool useTransitions)
  2406. {
  2407. UpdateVisualState(useTransitions);
  2408. }
  2409. /// <summary>
  2410. /// Update the current visual state of the button.
  2411. /// </summary>
  2412. /// <param name="useTransitions">
  2413. /// True to use transitions when updating the visual state, false to
  2414. /// snap directly to the new visual state.
  2415. /// </param>
  2416. internal virtual void UpdateVisualState(bool useTransitions)
  2417. {
  2418. // Popup
  2419. VisualStateManager.GoToState(this, IsDropDownOpen ? VisualStates.StatePopupOpened : VisualStates.StatePopupClosed, useTransitions);
  2420. // Handle the Common and Focused states
  2421. Interaction.UpdateVisualStateBase(useTransitions);
  2422. }
  2423. }
  2424. }