PageRenderTime 28ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 1ms

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

#
C# | 2743 lines | 1451 code | 253 blank | 1039 comment | 297 complexity | 7e1681fb24864c3e26cda6cb6b797283 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. // (c) Copyright Microsoft Corporation.
  2. // This source is subject to the Microsoft Public License (Ms-PL).
  3. // Please see http://go.microsoft.com/fwlink/?LinkID=131993] for details.
  4. // All other rights reserved.
  5. using System;
  6. using System.Collections;
  7. using System.Collections.Generic;
  8. using System.Collections.ObjectModel;
  9. using System.Collections.Specialized;
  10. using System.Diagnostics.CodeAnalysis;
  11. using System.Globalization;
  12. using System.Linq;
  13. using System.Windows.Automation.Peers;
  14. using System.Windows.Controls.Primitives;
  15. using System.Windows.Data;
  16. using System.Windows.Input;
  17. using System.Windows.Interop;
  18. using System.Windows.Markup;
  19. using System.Windows.Media;
  20. using System.Windows.Threading;
  21. namespace System.Windows.Controls
  22. {
  23. /// <summary>
  24. /// Represents a control that provides a text box for user input and a
  25. /// drop-down that contains possible matches based on the input in the text
  26. /// box.
  27. /// </summary>
  28. /// <QualityBand>Stable</QualityBand>
  29. [TemplatePart(Name = AutoCompleteBox.ElementSelectionAdapter, Type = typeof(ISelectionAdapter))]
  30. [TemplatePart(Name = AutoCompleteBox.ElementSelector, Type = typeof(Selector))]
  31. [TemplatePart(Name = AutoCompleteBox.ElementTextBox, Type = typeof(TextBox))]
  32. [TemplatePart(Name = AutoCompleteBox.ElementPopup, Type = typeof(Popup))]
  33. [StyleTypedProperty(Property = AutoCompleteBox.ElementTextBoxStyle, StyleTargetType = typeof(TextBox))]
  34. [StyleTypedProperty(Property = AutoCompleteBox.ElementItemContainerStyle, StyleTargetType = typeof(ListBox))]
  35. [TemplateVisualState(Name = VisualStates.StateNormal, GroupName = VisualStates.GroupCommon)]
  36. [TemplateVisualState(Name = VisualStates.StateMouseOver, GroupName = VisualStates.GroupCommon)]
  37. [TemplateVisualState(Name = VisualStates.StatePressed, GroupName = VisualStates.GroupCommon)]
  38. [TemplateVisualState(Name = VisualStates.StateDisabled, GroupName = VisualStates.GroupCommon)]
  39. [TemplateVisualState(Name = VisualStates.StateFocused, GroupName = VisualStates.GroupFocus)]
  40. [TemplateVisualState(Name = VisualStates.StateUnfocused, GroupName = VisualStates.GroupFocus)]
  41. [TemplateVisualState(Name = VisualStates.StatePopupClosed, GroupName = VisualStates.GroupPopup)]
  42. [TemplateVisualState(Name = VisualStates.StatePopupOpened, GroupName = VisualStates.GroupPopup)]
  43. [TemplateVisualState(Name = VisualStates.StateValid, GroupName = VisualStates.GroupValidation)]
  44. [TemplateVisualState(Name = VisualStates.StateInvalidFocused, GroupName = VisualStates.GroupValidation)]
  45. [TemplateVisualState(Name = VisualStates.StateInvalidUnfocused, GroupName = VisualStates.GroupValidation)]
  46. [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "Large implementation keeps the components contained.")]
  47. [ContentProperty("ItemsSource")]
  48. public partial class AutoCompleteBox : Control, IUpdateVisualState
  49. {
  50. #region Template part and style names
  51. /// <summary>
  52. /// Specifies the name of the selection adapter TemplatePart.
  53. /// </summary>
  54. private const string ElementSelectionAdapter = "SelectionAdapter";
  55. /// <summary>
  56. /// Specifies the name of the Selector TemplatePart.
  57. /// </summary>
  58. private const string ElementSelector = "Selector";
  59. /// <summary>
  60. /// Specifies the name of the Popup TemplatePart.
  61. /// </summary>
  62. private const string ElementPopup = "Popup";
  63. /// <summary>
  64. /// The name for the text box part.
  65. /// </summary>
  66. private const string ElementTextBox = "Text";
  67. /// <summary>
  68. /// The name for the text box style.
  69. /// </summary>
  70. private const string ElementTextBoxStyle = "TextBoxStyle";
  71. /// <summary>
  72. /// The name for the adapter's item container style.
  73. /// </summary>
  74. private const string ElementItemContainerStyle = "ItemContainerStyle";
  75. #endregion
  76. /// <summary>
  77. /// Gets or sets a local cached copy of the items data.
  78. /// </summary>
  79. private List<object> _items;
  80. /// <summary>
  81. /// Gets or sets the observable collection that contains references to
  82. /// all of the items in the generated view of data that is provided to
  83. /// the selection-style control adapter.
  84. /// </summary>
  85. private ObservableCollection<object> _view;
  86. /// <summary>
  87. /// Gets or sets a value to ignore a number of pending change handlers.
  88. /// The value is decremented after each use. This is used to reset the
  89. /// value of properties without performing any of the actions in their
  90. /// change handlers.
  91. /// </summary>
  92. /// <remarks>The int is important as a value because the TextBox
  93. /// TextChanged event does not immediately fire, and this will allow for
  94. /// nested property changes to be ignored.</remarks>
  95. private int _ignoreTextPropertyChange;
  96. /// <summary>
  97. /// Gets or sets a value indicating whether to ignore calling a pending
  98. /// change handlers.
  99. /// </summary>
  100. private bool _ignorePropertyChange;
  101. /// <summary>
  102. /// Gets or sets a value indicating whether to ignore the selection
  103. /// changed event.
  104. /// </summary>
  105. private bool _ignoreTextSelectionChange;
  106. /// <summary>
  107. /// Gets or sets a value indicating whether to skip the text update
  108. /// processing when the selected item is updated.
  109. /// </summary>
  110. private bool _skipSelectedItemTextUpdate;
  111. /// <summary>
  112. /// Gets or sets the last observed text box selection start location.
  113. /// </summary>
  114. private int _textSelectionStart;
  115. /// <summary>
  116. /// Gets or sets a value indicating whether the user initiated the
  117. /// current populate call.
  118. /// </summary>
  119. private bool _userCalledPopulate;
  120. /// <summary>
  121. /// A value indicating whether the popup has been opened at least once.
  122. /// </summary>
  123. private bool _popupHasOpened;
  124. /// <summary>
  125. /// Gets or sets the DispatcherTimer used for the MinimumPopulateDelay
  126. /// condition for auto completion.
  127. /// </summary>
  128. private DispatcherTimer _delayTimer;
  129. /// <summary>
  130. /// Gets or sets a value indicating whether a read-only dependency
  131. /// property change handler should allow the value to be set. This is
  132. /// used to ensure that read-only properties cannot be changed via
  133. /// SetValue, etc.
  134. /// </summary>
  135. private bool _allowWrite;
  136. /// <summary>
  137. /// Gets or sets the helper that provides all of the standard
  138. /// interaction functionality. Making it internal for subclass access.
  139. /// </summary>
  140. internal InteractionHelper Interaction { get; set; }
  141. /// <summary>
  142. /// Gets or sets the BindingEvaluator, a framework element that can
  143. /// provide updated string values from a single binding.
  144. /// </summary>
  145. private BindingEvaluator<string> _valueBindingEvaluator;
  146. /// <summary>
  147. /// A weak event listener for the collection changed event.
  148. /// </summary>
  149. private WeakEventListener<AutoCompleteBox, object, NotifyCollectionChangedEventArgs> _collectionChangedWeakEventListener;
  150. #region public int MinimumPrefixLength
  151. /// <summary>
  152. /// Gets or sets the minimum number of characters required to be entered
  153. /// in the text box before the
  154. /// <see cref="T:System.Windows.Controls.AutoCompleteBox" /> displays
  155. /// possible matches.
  156. /// matches.
  157. /// </summary>
  158. /// <value>
  159. /// The minimum number of characters to be entered in the text box
  160. /// before the <see cref="T:System.Windows.Controls.AutoCompleteBox" />
  161. /// displays possible matches. The default is 1.
  162. /// </value>
  163. /// <remarks>
  164. /// If you set MinimumPrefixLength to -1, the AutoCompleteBox will
  165. /// not provide possible matches. There is no maximum value, but
  166. /// setting MinimumPrefixLength to value that is too large will
  167. /// prevent the AutoCompleteBox from providing possible matches as well.
  168. /// </remarks>
  169. public int MinimumPrefixLength
  170. {
  171. get { return (int)GetValue(MinimumPrefixLengthProperty); }
  172. set { SetValue(MinimumPrefixLengthProperty, value); }
  173. }
  174. /// <summary>
  175. /// Identifies the
  176. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.MinimumPrefixLength" />
  177. /// dependency property.
  178. /// </summary>
  179. /// <value>The identifier for the
  180. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.MinimumPrefixLength" />
  181. /// dependency property.</value>
  182. public static readonly DependencyProperty MinimumPrefixLengthProperty =
  183. DependencyProperty.Register(
  184. "MinimumPrefixLength",
  185. typeof(int),
  186. typeof(AutoCompleteBox),
  187. new PropertyMetadata(1, OnMinimumPrefixLengthPropertyChanged));
  188. /// <summary>
  189. /// MinimumPrefixLengthProperty property changed handler.
  190. /// </summary>
  191. /// <param name="d">AutoCompleteBox that changed its MinimumPrefixLength.</param>
  192. /// <param name="e">Event arguments.</param>
  193. [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly", Justification = "MinimumPrefixLength is the name of the actual dependency property.")]
  194. private static void OnMinimumPrefixLengthPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  195. {
  196. int newValue = (int)e.NewValue;
  197. if (newValue < 0 && newValue != -1)
  198. {
  199. throw new ArgumentOutOfRangeException("MinimumPrefixLength");
  200. }
  201. }
  202. #endregion public int MinimumPrefixLength
  203. #region public int MinimumPopulateDelay
  204. /// <summary>
  205. /// Gets or sets the minimum delay, in milliseconds, after text is typed
  206. /// in the text box before the
  207. /// <see cref="T:System.Windows.Controls.AutoCompleteBox" /> control
  208. /// populates the list of possible matches in the drop-down.
  209. /// </summary>
  210. /// <value>The minimum delay, in milliseconds, after text is typed in
  211. /// the text box, but before the
  212. /// <see cref="T:System.Windows.Controls.AutoCompleteBox" /> populates
  213. /// the list of possible matches in the drop-down. The default is 0.</value>
  214. /// <exception cref="T:System.ArgumentException">The set value is less than 0.</exception>
  215. public int MinimumPopulateDelay
  216. {
  217. get { return (int)GetValue(MinimumPopulateDelayProperty); }
  218. set { SetValue(MinimumPopulateDelayProperty, value); }
  219. }
  220. /// <summary>
  221. /// Identifies the
  222. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.MinimumPopulateDelay" />
  223. /// dependency property.
  224. /// </summary>
  225. /// <value>The identifier for the
  226. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.MinimumPopulateDelay" />
  227. /// dependency property.</value>
  228. public static readonly DependencyProperty MinimumPopulateDelayProperty =
  229. DependencyProperty.Register(
  230. "MinimumPopulateDelay",
  231. typeof(int),
  232. typeof(AutoCompleteBox),
  233. new PropertyMetadata(OnMinimumPopulateDelayPropertyChanged));
  234. /// <summary>
  235. /// MinimumPopulateDelayProperty property changed handler. Any current
  236. /// dispatcher timer will be stopped. The timer will not be restarted
  237. /// until the next TextUpdate call by the user.
  238. /// </summary>
  239. /// <param name="d">AutoCompleteTextBox that changed its
  240. /// MinimumPopulateDelay.</param>
  241. /// <param name="e">Event arguments.</param>
  242. [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly", Justification = "The exception is most likely to be called through the CLR property setter.")]
  243. private static void OnMinimumPopulateDelayPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  244. {
  245. AutoCompleteBox source = d as AutoCompleteBox;
  246. if (source._ignorePropertyChange)
  247. {
  248. source._ignorePropertyChange = false;
  249. return;
  250. }
  251. int newValue = (int)e.NewValue;
  252. if (newValue < 0)
  253. {
  254. source._ignorePropertyChange = true;
  255. d.SetValue(e.Property, e.OldValue);
  256. throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Properties.Resources.AutoComplete_OnMinimumPopulateDelayPropertyChanged_InvalidValue, newValue), "value");
  257. }
  258. // Stop any existing timer
  259. if (source._delayTimer != null)
  260. {
  261. source._delayTimer.Stop();
  262. if (newValue == 0)
  263. {
  264. source._delayTimer = null;
  265. }
  266. }
  267. // Create or clear a dispatcher timer instance
  268. if (newValue > 0 && source._delayTimer == null)
  269. {
  270. source._delayTimer = new DispatcherTimer();
  271. source._delayTimer.Tick += source.PopulateDropDown;
  272. }
  273. // Set the new tick interval
  274. if (newValue > 0 && source._delayTimer != null)
  275. {
  276. source._delayTimer.Interval = TimeSpan.FromMilliseconds(newValue);
  277. }
  278. }
  279. #endregion public int MinimumPopulateDelay
  280. #region public bool IsTextCompletionEnabled
  281. /// <summary>
  282. /// Gets or sets a value indicating whether the first possible match
  283. /// found during the filtering process will be displayed automatically
  284. /// in the text box.
  285. /// </summary>
  286. /// <value>
  287. /// True if the first possible match found will be displayed
  288. /// automatically in the text box; otherwise, false. The default is
  289. /// false.
  290. /// </value>
  291. public bool IsTextCompletionEnabled
  292. {
  293. get { return (bool)GetValue(IsTextCompletionEnabledProperty); }
  294. set { SetValue(IsTextCompletionEnabledProperty, value); }
  295. }
  296. /// <summary>
  297. /// Identifies the
  298. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.IsTextCompletionEnabled" />
  299. /// dependency property.
  300. /// </summary>
  301. /// <value>The identifier for the
  302. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.IsTextCompletionEnabled" />
  303. /// dependency property.</value>
  304. public static readonly DependencyProperty IsTextCompletionEnabledProperty =
  305. DependencyProperty.Register(
  306. "IsTextCompletionEnabled",
  307. typeof(bool),
  308. typeof(AutoCompleteBox),
  309. new PropertyMetadata(false, null));
  310. #endregion public bool IsTextCompletionEnabled
  311. #region public DataTemplate ItemTemplate
  312. /// <summary>
  313. /// Gets or sets the <see cref="T:System.Windows.DataTemplate" /> used
  314. /// to display each item in the drop-down portion of the control.
  315. /// </summary>
  316. /// <value>The <see cref="T:System.Windows.DataTemplate" /> used to
  317. /// display each item in the drop-down. The default is null.</value>
  318. /// <remarks>
  319. /// You use the ItemTemplate property to specify the visualization
  320. /// of the data objects in the drop-down portion of the AutoCompleteBox
  321. /// control. If your AutoCompleteBox is bound to a collection and you
  322. /// do not provide specific display instructions by using a
  323. /// DataTemplate, the resulting UI of each item is a string
  324. /// representation of each object in the underlying collection.
  325. /// </remarks>
  326. public DataTemplate ItemTemplate
  327. {
  328. get { return GetValue(ItemTemplateProperty) as DataTemplate; }
  329. set { SetValue(ItemTemplateProperty, value); }
  330. }
  331. /// <summary>
  332. /// Identifies the
  333. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.ItemTemplate" />
  334. /// dependency property.
  335. /// </summary>
  336. /// <value>The identifier for the
  337. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.ItemTemplate" />
  338. /// dependency property.</value>
  339. public static readonly DependencyProperty ItemTemplateProperty =
  340. DependencyProperty.Register(
  341. "ItemTemplate",
  342. typeof(DataTemplate),
  343. typeof(AutoCompleteBox),
  344. new PropertyMetadata(null));
  345. #endregion public DataTemplate ItemTemplate
  346. #region public Style ItemContainerStyle
  347. /// <summary>
  348. /// Gets or sets the <see cref="T:System.Windows.Style" /> that is
  349. /// applied to the selection adapter contained in the drop-down portion
  350. /// of the <see cref="T:System.Windows.Controls.AutoCompleteBox" />
  351. /// control.
  352. /// </summary>
  353. /// <value>The <see cref="T:System.Windows.Style" /> applied to the
  354. /// selection adapter contained in the drop-down portion of the
  355. /// <see cref="T:System.Windows.Controls.AutoCompleteBox" /> control.
  356. /// The default is null.</value>
  357. /// <remarks>
  358. /// The default selection adapter contained in the drop-down is a
  359. /// ListBox control.
  360. /// </remarks>
  361. public Style ItemContainerStyle
  362. {
  363. get { return GetValue(ItemContainerStyleProperty) as Style; }
  364. set { SetValue(ItemContainerStyleProperty, value); }
  365. }
  366. /// <summary>
  367. /// Identifies the
  368. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.ItemContainerStyle" />
  369. /// dependency property.
  370. /// </summary>
  371. /// <value>The identifier for the
  372. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.ItemContainerStyle" />
  373. /// dependency property.</value>
  374. public static readonly DependencyProperty ItemContainerStyleProperty =
  375. DependencyProperty.Register(
  376. ElementItemContainerStyle,
  377. typeof(Style),
  378. typeof(AutoCompleteBox),
  379. new PropertyMetadata(null, null));
  380. #endregion public Style ItemContainerStyle
  381. #region public Style TextBoxStyle
  382. /// <summary>
  383. /// Gets or sets the <see cref="T:System.Windows.Style" /> applied to
  384. /// the text box portion of the
  385. /// <see cref="T:System.Windows.Controls.AutoCompleteBox" /> control.
  386. /// </summary>
  387. /// <value>The <see cref="T:System.Windows.Style" /> applied to the text
  388. /// box portion of the
  389. /// <see cref="T:System.Windows.Controls.AutoCompleteBox" /> control.
  390. /// The default is null.</value>
  391. public Style TextBoxStyle
  392. {
  393. get { return GetValue(TextBoxStyleProperty) as Style; }
  394. set { SetValue(TextBoxStyleProperty, value); }
  395. }
  396. /// <summary>
  397. /// Identifies the
  398. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.TextBoxStyle" />
  399. /// dependency property.
  400. /// </summary>
  401. /// <value>The identifier for the
  402. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.TextBoxStyle" />
  403. /// dependency property.</value>
  404. public static readonly DependencyProperty TextBoxStyleProperty =
  405. DependencyProperty.Register(
  406. ElementTextBoxStyle,
  407. typeof(Style),
  408. typeof(AutoCompleteBox),
  409. new PropertyMetadata(null));
  410. #endregion public Style TextBoxStyle
  411. #region public double MaxDropDownHeight
  412. /// <summary>
  413. /// Gets or sets the maximum height of the drop-down portion of the
  414. /// <see cref="T:System.Windows.Controls.AutoCompleteBox" /> control.
  415. /// </summary>
  416. /// <value>The maximum height of the drop-down portion of the
  417. /// <see cref="T:System.Windows.Controls.AutoCompleteBox" /> control.
  418. /// The default is <see cref="F:System.Double.PositiveInfinity" />.</value>
  419. /// <exception cref="T:System.ArgumentException">The specified value is less than 0.</exception>
  420. public double MaxDropDownHeight
  421. {
  422. get { return (double)GetValue(MaxDropDownHeightProperty); }
  423. set { SetValue(MaxDropDownHeightProperty, value); }
  424. }
  425. /// <summary>
  426. /// Identifies the
  427. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.MaxDropDownHeight" />
  428. /// dependency property.
  429. /// </summary>
  430. /// <value>The identifier for the
  431. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.MaxDropDownHeight" />
  432. /// dependency property.</value>
  433. public static readonly DependencyProperty MaxDropDownHeightProperty =
  434. DependencyProperty.Register(
  435. "MaxDropDownHeight",
  436. typeof(double),
  437. typeof(AutoCompleteBox),
  438. new PropertyMetadata(double.PositiveInfinity, OnMaxDropDownHeightPropertyChanged));
  439. /// <summary>
  440. /// MaxDropDownHeightProperty property changed handler.
  441. /// </summary>
  442. /// <param name="d">AutoCompleteTextBox that changed its MaxDropDownHeight.</param>
  443. /// <param name="e">Event arguments.</param>
  444. [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly", Justification = "The exception will be called through a CLR setter in most cases.")]
  445. private static void OnMaxDropDownHeightPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  446. {
  447. AutoCompleteBox source = d as AutoCompleteBox;
  448. if (source._ignorePropertyChange)
  449. {
  450. source._ignorePropertyChange = false;
  451. return;
  452. }
  453. double newValue = (double)e.NewValue;
  454. // Revert to the old value if invalid (negative)
  455. if (newValue < 0)
  456. {
  457. source._ignorePropertyChange = true;
  458. source.SetValue(e.Property, e.OldValue);
  459. throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Properties.Resources.AutoComplete_OnMaxDropDownHeightPropertyChanged_InvalidValue, e.NewValue), "value");
  460. }
  461. source.OnMaxDropDownHeightChanged(newValue);
  462. }
  463. #endregion public double MaxDropDownHeight
  464. #region public bool IsDropDownOpen
  465. /// <summary>
  466. /// Gets or sets a value indicating whether the drop-down portion of
  467. /// the control is open.
  468. /// </summary>
  469. /// <value>
  470. /// True if the drop-down is open; otherwise, false. The default is
  471. /// false.
  472. /// </value>
  473. public bool IsDropDownOpen
  474. {
  475. get { return (bool)GetValue(IsDropDownOpenProperty); }
  476. set { SetValue(IsDropDownOpenProperty, value); }
  477. }
  478. /// <summary>
  479. /// Identifies the
  480. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.IsDropDownOpen" />
  481. /// dependency property.
  482. /// </summary>
  483. /// <value>The identifier for the
  484. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.IsDropDownOpen" />
  485. /// dependency property.</value>
  486. public static readonly DependencyProperty IsDropDownOpenProperty =
  487. DependencyProperty.Register(
  488. "IsDropDownOpen",
  489. typeof(bool),
  490. typeof(AutoCompleteBox),
  491. new PropertyMetadata(false, OnIsDropDownOpenPropertyChanged));
  492. /// <summary>
  493. /// IsDropDownOpenProperty property changed handler.
  494. /// </summary>
  495. /// <param name="d">AutoCompleteTextBox that changed its IsDropDownOpen.</param>
  496. /// <param name="e">Event arguments.</param>
  497. private static void OnIsDropDownOpenPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  498. {
  499. AutoCompleteBox source = d as AutoCompleteBox;
  500. // Ignore the change if requested
  501. if (source._ignorePropertyChange)
  502. {
  503. source._ignorePropertyChange = false;
  504. return;
  505. }
  506. bool oldValue = (bool)e.OldValue;
  507. bool newValue = (bool)e.NewValue;
  508. if (newValue)
  509. {
  510. source.TextUpdated(source.Text, true);
  511. }
  512. else
  513. {
  514. source.ClosingDropDown(oldValue);
  515. }
  516. source.UpdateVisualState(true);
  517. }
  518. #endregion public bool IsDropDownOpen
  519. #region public IEnumerable ItemsSource
  520. /// <summary>
  521. /// Gets or sets a collection that is used to generate the items for the
  522. /// drop-down portion of the
  523. /// <see cref="T:System.Windows.Controls.AutoCompleteBox" /> control.
  524. /// </summary>
  525. /// <value>The collection that is used to generate the items of the
  526. /// drop-down portion of the
  527. /// <see cref="T:System.Windows.Controls.AutoCompleteBox" /> control.</value>
  528. public IEnumerable ItemsSource
  529. {
  530. get { return GetValue(ItemsSourceProperty) as IEnumerable; }
  531. set { SetValue(ItemsSourceProperty, value); }
  532. }
  533. /// <summary>
  534. /// Identifies the
  535. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.ItemsSource" />
  536. /// dependency property.
  537. /// </summary>
  538. /// <value>The identifier for the
  539. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.ItemsSource" />
  540. /// dependency property.</value>
  541. public static readonly DependencyProperty ItemsSourceProperty =
  542. DependencyProperty.Register(
  543. "ItemsSource",
  544. typeof(IEnumerable),
  545. typeof(AutoCompleteBox),
  546. new PropertyMetadata(OnItemsSourcePropertyChanged));
  547. /// <summary>
  548. /// ItemsSourceProperty property changed handler.
  549. /// </summary>
  550. /// <param name="d">AutoCompleteBox that changed its ItemsSource.</param>
  551. /// <param name="e">Event arguments.</param>
  552. private static void OnItemsSourcePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  553. {
  554. AutoCompleteBox autoComplete = d as AutoCompleteBox;
  555. autoComplete.OnItemsSourceChanged((IEnumerable)e.OldValue, (IEnumerable)e.NewValue);
  556. }
  557. #endregion public IEnumerable ItemsSource
  558. #region public object SelectedItem
  559. /// <summary>
  560. /// Gets or sets the selected item in the drop-down.
  561. /// </summary>
  562. /// <value>The selected item in the drop-down.</value>
  563. /// <remarks>
  564. /// If the IsTextCompletionEnabled property is true and text typed by
  565. /// the user matches an item in the ItemsSource collection, which is
  566. /// then displayed in the text box, the SelectedItem property will be
  567. /// a null reference.
  568. /// </remarks>
  569. public object SelectedItem
  570. {
  571. get { return GetValue(SelectedItemProperty) as object; }
  572. set { SetValue(SelectedItemProperty, value); }
  573. }
  574. /// <summary>
  575. /// Identifies the
  576. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.SelectedItem" />
  577. /// dependency property.
  578. /// </summary>
  579. /// <value>The identifier the
  580. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.SelectedItem" />
  581. /// dependency property.</value>
  582. public static readonly DependencyProperty SelectedItemProperty =
  583. DependencyProperty.Register(
  584. "SelectedItem",
  585. typeof(object),
  586. typeof(AutoCompleteBox),
  587. new PropertyMetadata(OnSelectedItemPropertyChanged));
  588. /// <summary>
  589. /// SelectedItemProperty property changed handler. Fires the
  590. /// SelectionChanged event. The event data will contain any non-null
  591. /// removed items and non-null additions.
  592. /// </summary>
  593. /// <param name="d">AutoCompleteBox that changed its SelectedItem.</param>
  594. /// <param name="e">Event arguments.</param>
  595. private static void OnSelectedItemPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  596. {
  597. AutoCompleteBox source = d as AutoCompleteBox;
  598. if (source._ignorePropertyChange)
  599. {
  600. source._ignorePropertyChange = false;
  601. return;
  602. }
  603. // Update the text display
  604. if (source._skipSelectedItemTextUpdate)
  605. {
  606. source._skipSelectedItemTextUpdate = false;
  607. }
  608. else
  609. {
  610. source.OnSelectedItemChanged(e.NewValue);
  611. }
  612. // Fire the SelectionChanged event
  613. List<object> removed = new List<object>();
  614. if (e.OldValue != null)
  615. {
  616. removed.Add(e.OldValue);
  617. }
  618. List<object> added = new List<object>();
  619. if (e.NewValue != null)
  620. {
  621. added.Add(e.NewValue);
  622. }
  623. source.OnSelectionChanged(new SelectionChangedEventArgs(
  624. #if !SILVERLIGHT
  625. SelectionChangedEvent,
  626. #endif
  627. removed,
  628. added));
  629. }
  630. /// <summary>
  631. /// Called when the selected item is changed, updates the text value
  632. /// that is displayed in the text box part.
  633. /// </summary>
  634. /// <param name="newItem">The new item.</param>
  635. private void OnSelectedItemChanged(object newItem)
  636. {
  637. string text;
  638. if (newItem == null)
  639. {
  640. text = SearchText;
  641. }
  642. else
  643. {
  644. text = FormatValue(newItem, true);
  645. }
  646. // Update the Text property and the TextBox values
  647. UpdateTextValue(text);
  648. // Move the caret to the end of the text box
  649. if (TextBox != null && Text != null)
  650. {
  651. TextBox.SelectionStart = Text.Length;
  652. }
  653. }
  654. #endregion public object SelectedItem
  655. #region public string Text
  656. /// <summary>
  657. /// Gets or sets the text in the text box portion of the
  658. /// <see cref="T:System.Windows.Controls.AutoCompleteBox" /> control.
  659. /// </summary>
  660. /// <value>The text in the text box portion of the
  661. /// <see cref="T:System.Windows.Controls.AutoCompleteBox" /> control.</value>
  662. public string Text
  663. {
  664. get { return GetValue(TextProperty) as string; }
  665. set { SetValue(TextProperty, value); }
  666. }
  667. /// <summary>
  668. /// Identifies the
  669. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.Text" />
  670. /// dependency property.
  671. /// </summary>
  672. /// <value>The identifier for the
  673. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.Text" />
  674. /// dependency property.</value>
  675. public static readonly DependencyProperty TextProperty =
  676. DependencyProperty.Register(
  677. "Text",
  678. typeof(string),
  679. typeof(AutoCompleteBox),
  680. new PropertyMetadata(string.Empty, OnTextPropertyChanged));
  681. /// <summary>
  682. /// TextProperty property changed handler.
  683. /// </summary>
  684. /// <param name="d">AutoCompleteBox that changed its Text.</param>
  685. /// <param name="e">Event arguments.</param>
  686. private static void OnTextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  687. {
  688. AutoCompleteBox source = d as AutoCompleteBox;
  689. source.TextUpdated((string)e.NewValue, false);
  690. }
  691. #endregion public string Text
  692. #region public string SearchText
  693. /// <summary>
  694. /// Gets the text that is used to filter items in the
  695. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.ItemsSource" />
  696. /// item collection.
  697. /// </summary>
  698. /// <value>The text that is used to filter items in the
  699. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.ItemsSource" />
  700. /// item collection.</value>
  701. /// <remarks>
  702. /// The SearchText value is typically the same as the
  703. /// Text property, but is set after the TextChanged event occurs
  704. /// and before the Populating event.
  705. /// </remarks>
  706. public string SearchText
  707. {
  708. get { return (string)GetValue(SearchTextProperty); }
  709. private set
  710. {
  711. try
  712. {
  713. _allowWrite = true;
  714. SetValue(SearchTextProperty, value);
  715. }
  716. finally
  717. {
  718. _allowWrite = false;
  719. }
  720. }
  721. }
  722. /// <summary>
  723. /// Identifies the
  724. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.SearchText" />
  725. /// dependency property.
  726. /// </summary>
  727. /// <value>The identifier for the
  728. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.SearchText" />
  729. /// dependency property.</value>
  730. public static readonly DependencyProperty SearchTextProperty =
  731. DependencyProperty.Register(
  732. "SearchText",
  733. typeof(string),
  734. typeof(AutoCompleteBox),
  735. new PropertyMetadata(string.Empty, OnSearchTextPropertyChanged));
  736. /// <summary>
  737. /// OnSearchTextProperty property changed handler.
  738. /// </summary>
  739. /// <param name="d">AutoCompleteBox that changed its SearchText.</param>
  740. /// <param name="e">Event arguments.</param>
  741. private static void OnSearchTextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  742. {
  743. AutoCompleteBox source = d as AutoCompleteBox;
  744. if (source._ignorePropertyChange)
  745. {
  746. source._ignorePropertyChange = false;
  747. return;
  748. }
  749. // Ensure the property is only written when expected
  750. if (!source._allowWrite)
  751. {
  752. // Reset the old value before it was incorrectly written
  753. source._ignorePropertyChange = true;
  754. source.SetValue(e.Property, e.OldValue);
  755. throw new InvalidOperationException(Properties.Resources.AutoComplete_OnSearchTextPropertyChanged_InvalidWrite);
  756. }
  757. }
  758. #endregion public string SearchText
  759. #region public AutoCompleteFilterMode FilterMode
  760. /// <summary>
  761. /// Gets or sets how the text in the text box is used to filter items
  762. /// specified by the
  763. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.ItemsSource" />
  764. /// property for display in the drop-down.
  765. /// </summary>
  766. /// <value>One of the
  767. /// <see cref="T:System.Windows.Controls.AutoCompleteFilterMode" />
  768. /// values The default is
  769. /// <see cref="F:System.Windows.Controls.AutoCompleteFilterMode.StartsWith" />.</value>
  770. /// <exception cref="T:System.ArgumentException">The specified value is
  771. /// not a valid
  772. /// <see cref="T:System.Windows.Controls.AutoCompleteFilterMode" />.</exception>
  773. /// <remarks>
  774. /// Use the FilterMode property to specify how possible matches are
  775. /// filtered. For example, possible matches can be filtered in a
  776. /// predefined or custom way. The search mode is automatically set to
  777. /// Custom if you set the ItemFilter property.
  778. /// </remarks>
  779. public AutoCompleteFilterMode FilterMode
  780. {
  781. get { return (AutoCompleteFilterMode)GetValue(FilterModeProperty); }
  782. set { SetValue(FilterModeProperty, value); }
  783. }
  784. /// <summary>
  785. /// Gets the identifier for the
  786. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.FilterMode" />
  787. /// dependency property.
  788. /// </summary>
  789. public static readonly DependencyProperty FilterModeProperty =
  790. DependencyProperty.Register(
  791. "FilterMode",
  792. typeof(AutoCompleteFilterMode),
  793. typeof(AutoCompleteBox),
  794. new PropertyMetadata(AutoCompleteFilterMode.StartsWith, OnFilterModePropertyChanged));
  795. /// <summary>
  796. /// FilterModeProperty property changed handler.
  797. /// </summary>
  798. /// <param name="d">AutoCompleteBox that changed its FilterMode.</param>
  799. /// <param name="e">Event arguments.</param>
  800. [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly", Justification = "The exception will be thrown when the CLR setter is used in most situations.")]
  801. private static void OnFilterModePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  802. {
  803. AutoCompleteBox source = d as AutoCompleteBox;
  804. AutoCompleteFilterMode mode = (AutoCompleteFilterMode)e.NewValue;
  805. if (mode != AutoCompleteFilterMode.Contains &&
  806. mode != AutoCompleteFilterMode.ContainsCaseSensitive &&
  807. mode != AutoCompleteFilterMode.ContainsOrdinal &&
  808. mode != AutoCompleteFilterMode.ContainsOrdinalCaseSensitive &&
  809. mode != AutoCompleteFilterMode.Custom &&
  810. mode != AutoCompleteFilterMode.Equals &&
  811. mode != AutoCompleteFilterMode.EqualsCaseSensitive &&
  812. mode != AutoCompleteFilterMode.EqualsOrdinal &&
  813. mode != AutoCompleteFilterMode.EqualsOrdinalCaseSensitive &&
  814. mode != AutoCompleteFilterMode.None &&
  815. mode != AutoCompleteFilterMode.StartsWith &&
  816. mode != AutoCompleteFilterMode.StartsWithCaseSensitive &&
  817. mode != AutoCompleteFilterMode.StartsWithOrdinal &&
  818. mode != AutoCompleteFilterMode.StartsWithOrdinalCaseSensitive)
  819. {
  820. source.SetValue(e.Property, e.OldValue);
  821. throw new ArgumentException(Properties.Resources.AutoComplete_OnFilterModePropertyChanged_InvalidValue, "value");
  822. }
  823. // Sets the filter predicate for the new value
  824. AutoCompleteFilterMode newValue = (AutoCompleteFilterMode)e.NewValue;
  825. source.TextFilter = AutoCompleteSearch.GetFilter(newValue);
  826. }
  827. #endregion public AutoCompleteFilterMode FilterMode
  828. #region public AutoCompleteFilterPredicate ItemFilter
  829. /// <summary>
  830. /// Gets or sets the custom method that uses user-entered text to filter
  831. /// the items specified by the
  832. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.ItemsSource" />
  833. /// property for display in the drop-down.
  834. /// </summary>
  835. /// <value>The custom method that uses the user-entered text to filter
  836. /// the items specified by the
  837. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.ItemsSource" />
  838. /// property. The default is null.</value>
  839. /// <remarks>
  840. /// The filter mode is automatically set to Custom if you set the
  841. /// ItemFilter property.
  842. /// </remarks>
  843. public AutoCompleteFilterPredicate<object> ItemFilter
  844. {
  845. get { return GetValue(ItemFilterProperty) as AutoCompleteFilterPredicate<object>; }
  846. set { SetValue(ItemFilterProperty, value); }
  847. }
  848. /// <summary>
  849. /// Identifies the
  850. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.ItemFilter" />
  851. /// dependency property.
  852. /// </summary>
  853. /// <value>The identifier for the
  854. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.ItemFilter" />
  855. /// dependency property.</value>
  856. public static readonly DependencyProperty ItemFilterProperty =
  857. DependencyProperty.Register(
  858. "ItemFilter",
  859. typeof(AutoCompleteFilterPredicate<object>),
  860. typeof(AutoCompleteBox),
  861. new PropertyMetadata(OnItemFilterPropertyChanged));
  862. /// <summary>
  863. /// ItemFilterProperty property changed handler.
  864. /// </summary>
  865. /// <param name="d">AutoCompleteBox that changed its ItemFilter.</param>
  866. /// <param name="e">Event arguments.</param>
  867. private static void OnItemFilterPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  868. {
  869. AutoCompleteBox source = d as AutoCompleteBox;
  870. AutoCompleteFilterPredicate<object> value = e.NewValue as AutoCompleteFilterPredicate<object>;
  871. // If null, revert to the "None" predicate
  872. if (value == null)
  873. {
  874. source.FilterMode = AutoCompleteFilterMode.None;
  875. }
  876. else
  877. {
  878. source.FilterMode = AutoCompleteFilterMode.Custom;
  879. source.TextFilter = null;
  880. }
  881. }
  882. #endregion public AutoCompleteFilterPredicate ItemFilter
  883. #region public AutoCompleteStringFilterPredicate TextFilter
  884. /// <summary>
  885. /// Gets or sets the custom method that uses the user-entered text to
  886. /// filter items specified by the
  887. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.ItemsSource" />
  888. /// property in a text-based way for display in the drop-down.
  889. /// </summary>
  890. /// <value>The custom method that uses the user-entered text to filter
  891. /// items specified by the
  892. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.ItemsSource" />
  893. /// property in a text-based way for display in the drop-down.</value>
  894. /// <remarks>
  895. /// The search mode is automatically set to Custom if you set the
  896. /// TextFilter property.
  897. /// </remarks>
  898. public AutoCompleteFilterPredicate<string> TextFilter
  899. {
  900. get { return GetValue(TextFilterProperty) as AutoCompleteFilterPredicate<string>; }
  901. set { SetValue(TextFilterProperty, value); }
  902. }
  903. /// <summary>
  904. /// Identifies the
  905. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.TextFilter" />
  906. /// dependency property.
  907. /// </summary>
  908. /// <value>The identifier for the
  909. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.TextFilter" />
  910. /// dependency property.</value>
  911. public static readonly DependencyProperty TextFilterProperty =
  912. DependencyProperty.Register(
  913. "TextFilter",
  914. typeof(AutoCompleteFilterPredicate<string>),
  915. typeof(AutoCompleteBox),
  916. new PropertyMetadata(AutoCompleteSearch.GetFilter(AutoCompleteFilterMode.StartsWith)));
  917. #endregion public AutoCompleteStringFilterPredicate TextFilter
  918. #region Template parts
  919. /// <summary>
  920. /// Gets or sets the drop down popup control.
  921. /// </summary>
  922. private PopupHelper DropDownPopup { get; set; }
  923. /// <summary>
  924. /// The TextBox template part.
  925. /// </summary>
  926. private TextBox _text;
  927. /// <summary>
  928. /// The SelectionAdapter.
  929. /// </summary>
  930. private ISelectionAdapter _adapter;
  931. /// <summary>
  932. /// Gets or sets the Text template part.
  933. /// </summary>
  934. internal TextBox TextBox
  935. {
  936. get { return _text; }
  937. set
  938. {
  939. // Detach existing handlers
  940. if (_text != null)
  941. {
  942. _text.SelectionChanged -= OnTextBoxSelectionChanged;
  943. _text.TextChanged -= OnTextBoxTextChanged;
  944. }
  945. _text = value;
  946. // Attach handlers
  947. if (_text != null)
  948. {
  949. _text.SelectionChanged += OnTextBoxSelectionChanged;
  950. _text.TextChanged += OnTextBoxTextChanged;
  951. if (Text != null)
  952. {
  953. UpdateTextValue(Text);
  954. }
  955. }
  956. }
  957. }
  958. /// <summary>
  959. /// Gets or sets the selection adapter used to populate the drop-down
  960. /// with a list of selectable items.
  961. /// </summary>
  962. /// <value>The selection adapter used to populate the drop-down with a
  963. /// list of selectable items.</value>
  964. /// <remarks>
  965. /// You can use this property when you create an automation peer to
  966. /// use with AutoCompleteBox or deriving from AutoCompleteBox to
  967. /// create a custom control.
  968. /// </remarks>
  969. protected internal ISelectionAdapter SelectionAdapter
  970. {
  971. get { return _adapter; }
  972. set
  973. {
  974. if (_adapter != null)
  975. {
  976. _adapter.SelectionChanged -= OnAdapterSelectionChanged;
  977. _adapter.Commit -= OnAdapterSelectionComplete;
  978. _adapter.Cancel -= OnAdapterSelectionCanceled;
  979. _adapter.Cancel -= OnAdapterSelectionComplete;
  980. _adapter.ItemsSource = null;
  981. }
  982. _adapter = value;
  983. if (_adapter != null)
  984. {
  985. _adapter.SelectionChanged += OnAdapterSelectionChanged;
  986. _adapter.Commit += OnAdapterSelectionComplete;
  987. _adapter.Cancel += OnAdapterSelectionCanceled;
  988. _adapter.Cancel += OnAdapterSelectionComplete;
  989. _adapter.ItemsSource = _view;
  990. }
  991. }
  992. }
  993. #endregion
  994. /// <summary>
  995. /// Occurs when the text in the text box portion of the
  996. /// <see cref="T:System.Windows.Controls.AutoCompleteBox" /> changes.
  997. /// </summary>
  998. #if SILVERLIGHT
  999. public event RoutedEventHandler TextChanged;
  1000. #else
  1001. public static readonly RoutedEvent TextChangedEvent = EventManager.RegisterRoutedEvent("TextChanged", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(AutoCompleteBox));
  1002. /// <summary>
  1003. /// Occurs when the text in the text box portion of the
  1004. /// <see cref="T:System.Windows.Controls.AutoCompleteBox" /> changes.
  1005. /// </summary>
  1006. public event RoutedEventHandler TextChanged
  1007. {
  1008. add { AddHandler(TextChangedEvent, value); }
  1009. remove { RemoveHandler(TextChangedEvent, value); }
  1010. }
  1011. #endif
  1012. /// <summary>
  1013. /// Occurs when the
  1014. /// <see cref="T:System.Windows.Controls.AutoCompleteBox" /> is
  1015. /// populating the drop-down with possible matches based on the
  1016. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.Text" />
  1017. /// property.
  1018. /// </summary>
  1019. /// <remarks>
  1020. /// If the event is canceled, by setting the PopulatingEventArgs.Cancel
  1021. /// property to true, the AutoCompleteBox will not automatically
  1022. /// populate the selection adapter contained in the drop-down.
  1023. /// In this case, if you want possible matches to appear, you must
  1024. /// provide the logic for populating the selection adapter.
  1025. /// </remarks>
  1026. #if SILVERLIGHT
  1027. public event PopulatingEventHandler Populating;
  1028. #else
  1029. public static readonly RoutedEvent PopulatingEvent = EventManager.RegisterRoutedEvent("Populating", RoutingStrategy.Bubble, typeof(PopulatingEventHandler), typeof(AutoCompleteBox));
  1030. /// <summary>
  1031. /// Occurs when the
  1032. /// <see cref="T:System.Windows.Controls.AutoCompleteBox" /> is
  1033. /// populating the drop-down with possible matches based on the
  1034. /// <see cref="P:System.Windows.Controls.AutoCompleteBox.Text" />
  1035. /// property.
  1036. /// </summary>
  1037. /// <remarks>
  1038. //…

Large files files are truncated, but you can click here to view the full file