Find Control With Tag : DependencyProperty « Windows Presentation Foundation « C# / C Sharp






Find Control With Tag

        

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Media;

static class common
{

    public static T FindControlWithTag<T>(this DependencyObject parent, string tag) where T : UIElement
    {
        List<UIElement> elements = new List<UIElement>();

        int count = VisualTreeHelper.GetChildrenCount(parent);
        if (count > 0)
        {
            for (int i = 0; i < count; i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(parent, i);
                if (typeof(FrameworkElement).IsAssignableFrom(child.GetType())
                    && ((string)((FrameworkElement)child).Tag == tag))
                {
                    return child as T;
                }
                var item = FindControlWithTag<T>(child, tag);
                if (item != null) return item as T;
            }
        }
        return null;
    }
}

   
    
    
    
    
    
    
    
  








Related examples in the same category

1.DependencyProperty.RegisterReadOnly to create read only Dependency PropertyDependencyProperty.RegisterReadOnly to create read only Dependency Property
2.Clear locally set values and restore the default values of dependency propertiesClear locally set values and restore the default values of dependency properties
3.Find children
4.Get Children for DependencyObject