InteractionHelper.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  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.Diagnostics;
  7. using System.Diagnostics.CodeAnalysis;
  8. using System.Windows;
  9. using System.Windows.Controls;
  10. using System.Windows.Input;
  11. namespace System.Windows.Controls
  12. {
  13. /// <summary>
  14. /// The InteractionHelper provides controls with support for all of the
  15. /// common interactions like mouse movement, mouse clicks, key presses,
  16. /// etc., and also incorporates proper event semantics when the control is
  17. /// disabled.
  18. /// </summary>
  19. internal sealed partial class InteractionHelper
  20. {
  21. // TODO: Consult with user experience experts to validate the double
  22. // click distance and time thresholds.
  23. /// <summary>
  24. /// The threshold used to determine whether two clicks are temporally
  25. /// local and considered a double click (or triple, quadruple, etc.).
  26. /// 500 milliseconds is the default double click value on Windows.
  27. /// This value would ideally be pulled form the system settings.
  28. /// </summary>
  29. private const double SequentialClickThresholdInMilliseconds = 500.0;
  30. /// <summary>
  31. /// The threshold used to determine whether two clicks are spatially
  32. /// local and considered a double click (or triple, quadruple, etc.)
  33. /// in pixels squared. We use pixels squared so that we can compare to
  34. /// the distance delta without taking a square root.
  35. /// </summary>
  36. private const double SequentialClickThresholdInPixelsSquared = 3.0 * 3.0;
  37. /// <summary>
  38. /// Gets the control the InteractionHelper is targeting.
  39. /// </summary>
  40. public Control Control { get; private set; }
  41. /// <summary>
  42. /// Gets a value indicating whether the control has focus.
  43. /// </summary>
  44. public bool IsFocused { get; private set; }
  45. /// <summary>
  46. /// Gets a value indicating whether the mouse is over the control.
  47. /// </summary>
  48. public bool IsMouseOver { get; private set; }
  49. /// <summary>
  50. /// Gets a value indicating whether the read-only property is set.
  51. /// </summary>
  52. [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Linked file.")]
  53. public bool IsReadOnly { get; private set; }
  54. /// <summary>
  55. /// Gets a value indicating whether the mouse button is pressed down
  56. /// over the control.
  57. /// </summary>
  58. public bool IsPressed { get; private set; }
  59. /// <summary>
  60. /// Gets or sets the last time the control was clicked.
  61. /// </summary>
  62. /// <remarks>
  63. /// The value is stored as Utc time because it is slightly more
  64. /// performant than converting to local time.
  65. /// </remarks>
  66. private DateTime LastClickTime { get; set; }
  67. /// <summary>
  68. /// Gets or sets the mouse position of the last click.
  69. /// </summary>
  70. /// <remarks>The value is relative to the control.</remarks>
  71. private Point LastClickPosition { get; set; }
  72. /// <summary>
  73. /// Gets the number of times the control was clicked.
  74. /// </summary>
  75. public int ClickCount { get; private set; }
  76. /// <summary>
  77. /// Reference used to call UpdateVisualState on the base class.
  78. /// </summary>
  79. private IUpdateVisualState _updateVisualState;
  80. /// <summary>
  81. /// Initializes a new instance of the InteractionHelper class.
  82. /// </summary>
  83. /// <param name="control">Control receiving interaction.</param>
  84. public InteractionHelper(Control control)
  85. {
  86. Debug.Assert(control != null, "control should not be null!");
  87. Control = control;
  88. _updateVisualState = control as IUpdateVisualState;
  89. // Wire up the event handlers for events without a virtual override
  90. control.Loaded += OnLoaded;
  91. control.IsEnabledChanged += OnIsEnabledChanged;
  92. }
  93. #region UpdateVisualState
  94. /// <summary>
  95. /// Update the visual state of the control.
  96. /// </summary>
  97. /// <param name="useTransitions">
  98. /// A value indicating whether to automatically generate transitions to
  99. /// the new state, or instantly transition to the new state.
  100. /// </param>
  101. /// <remarks>
  102. /// UpdateVisualState works differently than the rest of the injected
  103. /// functionality. Most of the other events are overridden by the
  104. /// calling class which calls Allow, does what it wants, and then calls
  105. /// Base. UpdateVisualState is the opposite because a number of the
  106. /// methods in InteractionHelper need to trigger it in the calling
  107. /// class. We do this using the IUpdateVisualState internal interface.
  108. /// </remarks>
  109. private void UpdateVisualState(bool useTransitions)
  110. {
  111. if (_updateVisualState != null)
  112. {
  113. _updateVisualState.UpdateVisualState(useTransitions);
  114. }
  115. }
  116. /// <summary>
  117. /// Update the visual state of the control.
  118. /// </summary>
  119. /// <param name="useTransitions">
  120. /// A value indicating whether to automatically generate transitions to
  121. /// the new state, or instantly transition to the new state.
  122. /// </param>
  123. public void UpdateVisualStateBase(bool useTransitions)
  124. {
  125. // Handle the Common states
  126. if (!Control.IsEnabled)
  127. {
  128. VisualStates.GoToState(Control, useTransitions, VisualStates.StateDisabled, VisualStates.StateNormal);
  129. }
  130. else if (IsReadOnly)
  131. {
  132. VisualStates.GoToState(Control, useTransitions, VisualStates.StateReadOnly, VisualStates.StateNormal);
  133. }
  134. else if (IsPressed)
  135. {
  136. VisualStates.GoToState(Control, useTransitions, VisualStates.StatePressed, VisualStates.StateMouseOver, VisualStates.StateNormal);
  137. }
  138. else if (IsMouseOver)
  139. {
  140. VisualStates.GoToState(Control, useTransitions, VisualStates.StateMouseOver, VisualStates.StateNormal);
  141. }
  142. else
  143. {
  144. VisualStates.GoToState(Control, useTransitions, VisualStates.StateNormal);
  145. }
  146. // Handle the Focused states
  147. if (IsFocused)
  148. {
  149. VisualStates.GoToState(Control, useTransitions, VisualStates.StateFocused, VisualStates.StateUnfocused);
  150. }
  151. else
  152. {
  153. VisualStates.GoToState(Control, useTransitions, VisualStates.StateUnfocused);
  154. }
  155. }
  156. #endregion UpdateVisualState
  157. /// <summary>
  158. /// Handle the control's Loaded event.
  159. /// </summary>
  160. /// <param name="sender">The control.</param>
  161. /// <param name="e">Event arguments.</param>
  162. private void OnLoaded(object sender, RoutedEventArgs e)
  163. {
  164. UpdateVisualState(false);
  165. }
  166. /// <summary>
  167. /// Handle changes to the control's IsEnabled property.
  168. /// </summary>
  169. /// <param name="sender">The control.</param>
  170. /// <param name="e">Event arguments.</param>
  171. private void OnIsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
  172. {
  173. bool enabled = (bool) e.NewValue;
  174. if (!enabled)
  175. {
  176. IsPressed = false;
  177. IsMouseOver = false;
  178. IsFocused = false;
  179. }
  180. UpdateVisualState(true);
  181. }
  182. /// <summary>
  183. /// Handles changes to the control's IsReadOnly property.
  184. /// </summary>
  185. /// <param name="value">The value of the property.</param>
  186. [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Linked file.")]
  187. public void OnIsReadOnlyChanged(bool value)
  188. {
  189. IsReadOnly = value;
  190. if (!value)
  191. {
  192. IsPressed = false;
  193. IsMouseOver = false;
  194. IsFocused = false;
  195. }
  196. UpdateVisualState(true);
  197. }
  198. /// <summary>
  199. /// Update the visual state of the control when its template is changed.
  200. /// </summary>
  201. public void OnApplyTemplateBase()
  202. {
  203. UpdateVisualState(false);
  204. }
  205. #region GotFocus
  206. /// <summary>
  207. /// Check if the control's GotFocus event should be handled.
  208. /// </summary>
  209. /// <param name="e">Event arguments.</param>
  210. /// <returns>
  211. /// A value indicating whether the event should be handled.
  212. /// </returns>
  213. public bool AllowGotFocus(RoutedEventArgs e)
  214. {
  215. if (e == null)
  216. {
  217. throw new ArgumentNullException("e");
  218. }
  219. bool enabled = Control.IsEnabled;
  220. if (enabled)
  221. {
  222. IsFocused = true;
  223. }
  224. return enabled;
  225. }
  226. /// <summary>
  227. /// Base implementation of the virtual GotFocus event handler.
  228. /// </summary>
  229. public void OnGotFocusBase()
  230. {
  231. UpdateVisualState(true);
  232. }
  233. #endregion GotFocus
  234. #region LostFocus
  235. /// <summary>
  236. /// Check if the control's LostFocus event should be handled.
  237. /// </summary>
  238. /// <param name="e">Event arguments.</param>
  239. /// <returns>
  240. /// A value indicating whether the event should be handled.
  241. /// </returns>
  242. public bool AllowLostFocus(RoutedEventArgs e)
  243. {
  244. if (e == null)
  245. {
  246. throw new ArgumentNullException("e");
  247. }
  248. bool enabled = Control.IsEnabled;
  249. if (enabled)
  250. {
  251. IsFocused = false;
  252. }
  253. return enabled;
  254. }
  255. /// <summary>
  256. /// Base implementation of the virtual LostFocus event handler.
  257. /// </summary>
  258. public void OnLostFocusBase()
  259. {
  260. IsPressed = false;
  261. UpdateVisualState(true);
  262. }
  263. #endregion LostFocus
  264. #region MouseEnter
  265. /// <summary>
  266. /// Check if the control's MouseEnter event should be handled.
  267. /// </summary>
  268. /// <param name="e">Event arguments.</param>
  269. /// <returns>
  270. /// A value indicating whether the event should be handled.
  271. /// </returns>
  272. public bool AllowMouseEnter(MouseEventArgs e)
  273. {
  274. if (e == null)
  275. {
  276. throw new ArgumentNullException("e");
  277. }
  278. bool enabled = Control.IsEnabled;
  279. if (enabled)
  280. {
  281. IsMouseOver = true;
  282. }
  283. return enabled;
  284. }
  285. /// <summary>
  286. /// Base implementation of the virtual MouseEnter event handler.
  287. /// </summary>
  288. public void OnMouseEnterBase()
  289. {
  290. UpdateVisualState(true);
  291. }
  292. #endregion MouseEnter
  293. #region MouseLeave
  294. /// <summary>
  295. /// Check if the control's MouseLeave event should be handled.
  296. /// </summary>
  297. /// <param name="e">Event arguments.</param>
  298. /// <returns>
  299. /// A value indicating whether the event should be handled.
  300. /// </returns>
  301. public bool AllowMouseLeave(MouseEventArgs e)
  302. {
  303. if (e == null)
  304. {
  305. throw new ArgumentNullException("e");
  306. }
  307. bool enabled = Control.IsEnabled;
  308. if (enabled)
  309. {
  310. IsMouseOver = false;
  311. }
  312. return enabled;
  313. }
  314. /// <summary>
  315. /// Base implementation of the virtual MouseLeave event handler.
  316. /// </summary>
  317. public void OnMouseLeaveBase()
  318. {
  319. UpdateVisualState(true);
  320. }
  321. #endregion MouseLeave
  322. #region MouseLeftButtonDown
  323. /// <summary>
  324. /// Check if the control's MouseLeftButtonDown event should be handled.
  325. /// </summary>
  326. /// <param name="e">Event arguments.</param>
  327. /// <returns>
  328. /// A value indicating whether the event should be handled.
  329. /// </returns>
  330. public bool AllowMouseLeftButtonDown(MouseButtonEventArgs e)
  331. {
  332. if (e == null)
  333. {
  334. throw new ArgumentNullException("e");
  335. }
  336. bool enabled = Control.IsEnabled;
  337. if (enabled)
  338. {
  339. // Get the current position and time
  340. DateTime now = DateTime.UtcNow;
  341. Point position = e.GetPosition(Control);
  342. // Compute the deltas from the last click
  343. double timeDelta = (now - LastClickTime).TotalMilliseconds;
  344. Point lastPosition = LastClickPosition;
  345. double dx = position.X - lastPosition.X;
  346. double dy = position.Y - lastPosition.Y;
  347. double distance = dx * dx + dy * dy;
  348. // Check if the values fall under the sequential click temporal
  349. // and spatial thresholds
  350. if (timeDelta < SequentialClickThresholdInMilliseconds &&
  351. distance < SequentialClickThresholdInPixelsSquared)
  352. {
  353. // TODO: Does each click have to be within the single time
  354. // threshold on WPF?
  355. ClickCount++;
  356. }
  357. else
  358. {
  359. ClickCount = 1;
  360. }
  361. // Set the new position and time
  362. LastClickTime = now;
  363. LastClickPosition = position;
  364. // Raise the event
  365. IsPressed = true;
  366. }
  367. else
  368. {
  369. ClickCount = 1;
  370. }
  371. return enabled;
  372. }
  373. /// <summary>
  374. /// Base implementation of the virtual MouseLeftButtonDown event
  375. /// handler.
  376. /// </summary>
  377. public void OnMouseLeftButtonDownBase()
  378. {
  379. UpdateVisualState(true);
  380. }
  381. #endregion MouseLeftButtonDown
  382. #region MouseLeftButtonUp
  383. /// <summary>
  384. /// Check if the control's MouseLeftButtonUp event should be handled.
  385. /// </summary>
  386. /// <param name="e">Event arguments.</param>
  387. /// <returns>
  388. /// A value indicating whether the event should be handled.
  389. /// </returns>
  390. public bool AllowMouseLeftButtonUp(MouseButtonEventArgs e)
  391. {
  392. if (e == null)
  393. {
  394. throw new ArgumentNullException("e");
  395. }
  396. bool enabled = Control.IsEnabled;
  397. if (enabled)
  398. {
  399. IsPressed = false;
  400. }
  401. return enabled;
  402. }
  403. /// <summary>
  404. /// Base implementation of the virtual MouseLeftButtonUp event handler.
  405. /// </summary>
  406. public void OnMouseLeftButtonUpBase()
  407. {
  408. UpdateVisualState(true);
  409. }
  410. #endregion MouseLeftButtonUp
  411. #region KeyDown
  412. /// <summary>
  413. /// Check if the control's KeyDown event should be handled.
  414. /// </summary>
  415. /// <param name="e">Event arguments.</param>
  416. /// <returns>
  417. /// A value indicating whether the event should be handled.
  418. /// </returns>
  419. public bool AllowKeyDown(KeyEventArgs e)
  420. {
  421. if (e == null)
  422. {
  423. throw new ArgumentNullException("e");
  424. }
  425. return Control.IsEnabled;
  426. }
  427. #endregion KeyDown
  428. #region KeyUp
  429. /// <summary>
  430. /// Check if the control's KeyUp event should be handled.
  431. /// </summary>
  432. /// <param name="e">Event arguments.</param>
  433. /// <returns>
  434. /// A value indicating whether the event should be handled.
  435. /// </returns>
  436. public bool AllowKeyUp(KeyEventArgs e)
  437. {
  438. if (e == null)
  439. {
  440. throw new ArgumentNullException("e");
  441. }
  442. return Control.IsEnabled;
  443. }
  444. #endregion KeyUp
  445. }
  446. }