PageRenderTime 39ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/V2.2/trunk/RI/Desktop/StockTraderRI.Infrastructure/TreeHelper.cs

#
C# | 61 lines | 30 code | 3 blank | 28 comment | 5 complexity | 55c7bf51a849365a7d76b3609952cab2 MD5 | raw file
  1. //===================================================================================
  2. // Microsoft patterns & practices
  3. // Composite Application Guidance for Windows Presentation Foundation and Silverlight
  4. //===================================================================================
  5. // Copyright (c) Microsoft Corporation. All rights reserved.
  6. // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
  7. // OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
  8. // LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  9. // FITNESS FOR A PARTICULAR PURPOSE.
  10. //===================================================================================
  11. // The example companies, organizations, products, domain names,
  12. // e-mail addresses, logos, people, places, and events depicted
  13. // herein are fictitious. No association with any real company,
  14. // organization, product, domain name, email address, logo, person,
  15. // places, or events is intended or should be inferred.
  16. //===================================================================================
  17. using System;
  18. using System.Windows;
  19. namespace StockTraderRI.Infrastructure
  20. {
  21. /// <summary>
  22. /// Helper class used to traverse the Visual Tree.
  23. /// </summary>
  24. public static class TreeHelper
  25. {
  26. /// <summary>
  27. /// Traverses the Visual Tree upwards looking for the ancestor that satisfies the <paramref name="predicate"/>.
  28. /// </summary>
  29. /// <param name="dependencyObject">The element for which the ancestor is being looked for.</param>
  30. /// <param name="predicate">The predicate that evaluates if an element is the ancestor that is being looked for.</param>
  31. /// <returns>
  32. /// The ancestor element that matches the <paramref name="predicate"/> or <see langword="null"/>
  33. /// if the ancestor was not found.
  34. /// </returns>
  35. public static DependencyObject FindAncestor(DependencyObject dependencyObject, Func<DependencyObject, bool> predicate)
  36. {
  37. if (predicate(dependencyObject))
  38. {
  39. return dependencyObject;
  40. }
  41. DependencyObject parent = null;
  42. #if SILVERLIGHT
  43. FrameworkElement frameworkElement = dependencyObject as FrameworkElement;
  44. if (frameworkElement != null)
  45. {
  46. parent = frameworkElement.Parent ?? System.Windows.Media.VisualTreeHelper.GetParent(frameworkElement);
  47. }
  48. #else
  49. parent = LogicalTreeHelper.GetParent(dependencyObject);
  50. #endif
  51. if (parent != null)
  52. {
  53. return FindAncestor(parent, predicate);
  54. }
  55. return null;
  56. }
  57. }
  58. }