יום ראשון, 10 באפריל 2011

WPF - Find Parent Control in VisualTree - Generics Methods

If you need to find parent control, but you would like to use generic method for find one, you can use
method I wrote:


public UIElement GetParent<TSource>(UIElement element, UIElement stopOn)
{
   while (element != null && !(element is TSource) && (element != stopOn))
   {
      element = VisualTreeHelper.GetParent(element) as UIElement;               
   }
   if (element == stopOn)
      return null;
   else
      return element;
}
and you can implement it like this:
UIElement expander = GetParent<Expander>(element, parent);
if ( expander != null)
     return;
P.S.
Its very helpful if you are using routed events of WPF (instance:PreviewMouseLeftButtonDown)
and you want to stop bubble events on one of control on the way.

אין תגובות:

הוסף רשומת תגובה