Tuesday, 29 July 2008

Efficient way to find specific WPF elements further up the Visual Tree ...

Implement a search method like this:

        public static T FindFirstVisualTreeParentByType<T>(DependencyObject initial) where T : DependencyObject
        {
            DependencyObject current = initial;
            while (current != null)
            {
                if (current is Visual || current is Visual3D) { current = VisualTreeHelper.GetParent(current); }
                else { current = LogicalTreeHelper.GetParent(current); }
                if (current is T) return (T)current;
            }
            return null;
        }

And use it like this:

Global.FindFirstVisualTreeParentByType<YourType>(this).YourTypesProperty = value;

;-)




No comments:

Post a Comment