// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Windows; using System.Windows.Automation; using System.Windows.Automation.Peers; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Input; using System.Windows.Media; using System.Windows.Threading; namespace Microsoft.Management.UI.Internal { /// /// Defines a method which will be called when /// a condition is met. /// /// The type of the item. /// The parameter to pass to the method. [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] internal delegate void RetryActionCallback(T item); /// /// Provides common WPF methods for use in the library. /// [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] internal static class WpfHelp { #region RetryActionAfterLoaded private static Dictionary retryActionData = new Dictionary(); /// /// Calls a method when the Loaded event is fired on a FrameworkElement. /// /// The type of the parameter to pass to the callback method. /// The element whose Loaded state we are interested in. /// The method we will call if element.IsLoaded is false. /// The parameter to pass to the callback method. /// /// Returns true if the element is not loaded and the callback will be called /// when the element is loaded, false otherwise. /// public static bool RetryActionAfterLoaded(FrameworkElement element, RetryActionCallback callback, T parameter) { if (element.IsLoaded) { return false; } RetryActionAfterLoadedDataQueue data; if (!retryActionData.TryGetValue(element, out data)) { data = new RetryActionAfterLoadedDataQueue(); retryActionData.Add(element, data); } data.Enqueue(callback, parameter); element.Loaded += Element_Loaded; element.ApplyTemplate(); return true; } private static void Element_Loaded(object sender, RoutedEventArgs e) { FrameworkElement element = (FrameworkElement)sender; element.Loaded -= Element_Loaded; RetryActionAfterLoadedDataQueue data; if (!retryActionData.TryGetValue(element, out data) || data.IsEmpty) { throw new InvalidOperationException("Event loaded callback data expected."); } Delegate callback; object parameter; data.Dequeue(out callback, out parameter); if (data.IsEmpty) { retryActionData.Remove(element); } callback.DynamicInvoke(parameter); } private class RetryActionAfterLoadedDataQueue { private Queue callbacks = new Queue(); private Queue parameters = new Queue(); /// /// Adds a callback with its associated parameter to the collection. /// /// The callback to invoke. /// The parameter to pass to the callback. public void Enqueue(Delegate callback, object parameter) { this.callbacks.Enqueue(callback); this.parameters.Enqueue(parameter); } /// /// Removes a callback with its associated parameter from the head of /// the collection. /// /// The callback to invoke. /// The parameter to pass to the callback. public void Dequeue(out Delegate callback, out object parameter) { callback = null; parameter = null; if (this.callbacks.Count < 1) { throw new InvalidOperationException("Trying to remove when there is no data"); } callback = this.callbacks.Dequeue(); parameter = this.parameters.Dequeue(); } /// /// Gets whether there is any callback data available. /// public bool IsEmpty { get { return this.callbacks.Count == 0; } } } #endregion RetryActionAfterLoaded #region RemoveFromParent/AddChild /// /// Removes the specified element from its parent. /// /// The element to remove. /// The specified value is a null reference. /// The specified value does not have a parent that supports removal. public static void RemoveFromParent(FrameworkElement element) { ArgumentNullException.ThrowIfNull(element); // If the element has already been detached, do nothing \\ if (element.Parent == null) { return; } ContentControl parentContentControl = element.Parent as ContentControl; if (parentContentControl != null) { parentContentControl.Content = null; return; } var parentDecorator = element.Parent as Decorator; if (parentDecorator != null) { parentDecorator.Child = null; return; } ItemsControl parentItemsControl = element.Parent as ItemsControl; if (parentItemsControl != null) { parentItemsControl.Items.Remove(element); return; } Panel parentPanel = element.Parent as Panel; if (parentPanel != null) { parentPanel.Children.Remove(element); return; } var parentAdorner = element.Parent as UIElementAdorner; if (parentAdorner != null) { parentAdorner.Child = null; return; } throw new NotSupportedException("The specified value does not have a parent that supports removal."); } /// /// Removes the specified element from its parent. /// /// The parent element. /// The element to add. /// The specified value does not have a parent that supports removal. public static void AddChild(FrameworkElement parent, FrameworkElement element) { ArgumentNullException.ThrowIfNull(element); ArgumentNullException.ThrowIfNull(parent, nameof(element)); ContentControl parentContentControl = parent as ContentControl; if (parentContentControl != null) { parentContentControl.Content = element; return; } var parentDecorator = parent as Decorator; if (parentDecorator != null) { parentDecorator.Child = element; return; } ItemsControl parentItemsControl = parent as ItemsControl; if (parentItemsControl != null) { parentItemsControl.Items.Add(element); return; } Panel parentPanel = parent as Panel; if (parentPanel != null) { parentPanel.Children.Add(element); return; } throw new NotSupportedException("The specified parent doesn't support children."); } #endregion RemoveFromParent/AddChild #region VisualChild /// /// Returns the first visual child that matches the type T. /// Performs a breadth-first search. /// /// The type of the child to find. /// The object with a visual tree. /// Returns an object of type T if found, otherwise null. public static T GetVisualChild(DependencyObject obj) where T : DependencyObject { if (obj == null) { return null; } var elementQueue = new Queue(); elementQueue.Enqueue(obj); while (elementQueue.Count > 0) { var element = elementQueue.Dequeue(); T item = element as T; if (item != null) { return item; } for (int i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++) { var child = VisualTreeHelper.GetChild(element, i); elementQueue.Enqueue(child); } } return null; } /// /// Finds all children of type within the specified object's visual tree. /// /// The type of the child to find. /// The object with a visual tree. /// All children of the specified object matching the specified type. /// The specified value is a null reference. public static List FindVisualChildren(DependencyObject obj) where T : DependencyObject { Debug.Assert(obj != null, "obj is null"); ArgumentNullException.ThrowIfNull(obj); List childrenOfType = new List(); // Recursively loop through children looking for children of type within their trees \\ for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++) { DependencyObject childObj = VisualTreeHelper.GetChild(obj, i); T child = childObj as T; if (child != null) { childrenOfType.Add(child); } else { // Recurse \\ childrenOfType.AddRange(FindVisualChildren(childObj)); } } return childrenOfType; } #endregion VisualChild /// /// Searches ancestors for data of the specified type. /// /// The type of the data to find. /// The visual whose ancestors are searched. /// The data of the specified type; or if not found, null. /// The specified value is a null reference. public static T FindVisualAncestorData(this DependencyObject obj) where T : class { ArgumentNullException.ThrowIfNull(obj); FrameworkElement parent = obj.FindVisualAncestor(); if (parent != null) { T data = parent.DataContext as T; if (data != null) { return data; } else { return parent.FindVisualAncestorData(); } } return null; } /// /// Walks up the visual tree looking for an ancestor of a given type. /// /// The type to look for. /// The object to start from. /// The parent of the right type, or null. /// The specified value is a null reference. public static T FindVisualAncestor(this DependencyObject @object) where T : class { ArgumentNullException.ThrowIfNull(@object, nameof(@object)); DependencyObject parent = VisualTreeHelper.GetParent(@object); if (parent != null) { T parentObj = parent as T; if (parentObj != null) { return parentObj; } return parent.FindVisualAncestor(); } return null; } /// /// Executes the on the current command target if it is allowed. /// /// The routed command. /// A user defined data type. /// The command target. /// true if the command could execute; otherwise, false. /// The specified value is a null reference. public static bool TryExecute(this RoutedCommand command, object parameter, IInputElement target) { ArgumentNullException.ThrowIfNull(command); if (command.CanExecute(parameter, target)) { command.Execute(parameter, target); return true; } return false; } #region TemplateChild /// /// Gets the named child of an item from a templated control. /// /// The type of the child. /// The parent of the control. /// The name of the child. /// The reference to the child, or null if the template part wasn't found. public static T GetOptionalTemplateChild(Control templateParent, string childName) where T : FrameworkElement { ArgumentNullException.ThrowIfNull(templateParent); ArgumentException.ThrowIfNullOrEmpty(childName); object templatePart = templateParent.Template.FindName(childName, templateParent); T item = templatePart as T; if (item == null && templatePart != null) { HandleWrongTemplatePartType(childName); } return item; } /// /// Gets the named child of an item from a templated control. /// /// The type of the child. /// The parent of the control. /// The name of the child. /// The reference to the child. public static T GetTemplateChild(Control templateParent, string childName) where T : FrameworkElement { T item = GetOptionalTemplateChild(templateParent, childName); if (item == null) { HandleMissingTemplatePart(childName); } return item; } /// /// Throws an exception with information about the template part with the wrong type. /// /// The type of the expected template part. /// The name of the expected template part. private static void HandleWrongTemplatePartType(string name) { throw new ApplicationException(string.Format( CultureInfo.CurrentCulture, "A template part with the name of '{0}' is not of type {1}.", name, typeof(T).Name)); } /// /// Throws an exception with information about the missing template part. /// /// The type of the expected template part. /// The name of the expected template part. public static void HandleMissingTemplatePart(string name) { throw new ApplicationException(string.Format( CultureInfo.CurrentCulture, "A template part with the name of '{0}' and type of {1} was not found.", name, typeof(T).Name)); } #endregion TemplateChild #region SetComponentResourceStyle /// /// Sets Style for control given a component resource key. /// /// Type in which Component Resource Style is Defined. /// Element whose style need to be set. /// Component Resource Key for Style. public static void SetComponentResourceStyle(FrameworkElement element, string keyName) where T : FrameworkElement { ComponentResourceKey styleKey = new ComponentResourceKey(typeof(T), keyName); element.Style = (Style)element.FindResource(styleKey); } #endregion SetComponentResourceStyle #region CreateRoutedPropertyChangedEventArgs /// /// Helper function to create a RoutedPropertyChangedEventArgs from a DependencyPropertyChangedEventArgs. /// /// The type for the RoutedPropertyChangedEventArgs. /// The DependencyPropertyChangedEventArgs data source. /// The created event args, configured from the parameter. public static RoutedPropertyChangedEventArgs CreateRoutedPropertyChangedEventArgs(DependencyPropertyChangedEventArgs propertyEventArgs) { RoutedPropertyChangedEventArgs eventArgs = new RoutedPropertyChangedEventArgs( (T)propertyEventArgs.OldValue, (T)propertyEventArgs.NewValue); return eventArgs; } /// /// Helper function to create a RoutedPropertyChangedEventArgs from a DependencyPropertyChangedEventArgs. /// /// The type for the RoutedPropertyChangedEventArgs. /// The DependencyPropertyChangedEventArgs data source. /// The routed event the property change is associated with. /// The created event args, configured from the parameter. public static RoutedPropertyChangedEventArgs CreateRoutedPropertyChangedEventArgs(DependencyPropertyChangedEventArgs propertyEventArgs, RoutedEvent routedEvent) { RoutedPropertyChangedEventArgs eventArgs = new RoutedPropertyChangedEventArgs( (T)propertyEventArgs.OldValue, (T)propertyEventArgs.NewValue, routedEvent); return eventArgs; } #endregion CreateRoutedPropertyChangedEventArgs #region ChangeIndex /// /// Moves the item in the specified collection to the specified index. /// /// The collection to move the item in. /// The item to move. /// The new index of the item. /// The specified item is not in the specified collection. /// The specified value is a null reference. /// The specified index is not valid for the specified collection. public static void ChangeIndex(ItemCollection items, object item, int newIndex) { ArgumentNullException.ThrowIfNull(items); if (!items.Contains(item)) { throw new ArgumentException("The specified item is not in the specified collection.", "item"); } if (newIndex < 0 || newIndex > items.Count) { throw new ArgumentOutOfRangeException("newIndex", "The specified index is not valid for the specified collection."); } int oldIndex = items.IndexOf(item); // If the tile isn't moving, don't do anything \\ if (newIndex == oldIndex) { return; } items.Remove(item); // If adding to the end, add instead of inserting \\ if (newIndex > items.Count) { items.Add(item); } else { items.Insert(newIndex, item); } } #endregion ChangeIndex } }