Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Find all controls in WPF Window by type

    • 0
    • 1
    • 1
    • 1
    • 0
    • 0
    • 0
    • 0
    • 3.04k
    Comment on it

    Hi Friends!
    Often we need to loop through the controls (collection of TextBlocks in) to and find them by their types. We can find them in this way:-

    object control= LayoutRoot.FindName(txtname.Text);
    
        if (item is TextBox)
    
        {
    
            TextBox txtControl = (TextBox)item;
    
            txtControl.Text = "Yup! Got you!";
    
    
    
        }
    

    Put his code for any given control and you can find it,where we're supplying the name of the textbox through txtname.Text.
    Great idea,isn't it?
    But if you need to find it by type and I tell you that I am having approximately 100 controls over a very complex control panel designed in wpf and you need to find a list of child controls,then?

    Getting all of them using names is a repetitive and bad idea. So we can use the VisualTreeHelper class which gets the children as nodes.

    The getchild method of this class the children as Dependency Objects which is the base object of all WPF objects

    So we can use following method to get children in a WPF window:-

    public static IEnumerable<T> FindWindowChildren<T>(DependencyObject dObj) where T : DependencyObject
    {
        if (dObj!= null)
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(dObj); i++)
            {
                DependencyObject ch = VisualTreeHelper.GetChild(dObj, i);
                if (ch != null && ch is T)
                {
                    yield return (T)ch;
                }
    
                foreach (T nestedChild in FindWindowChildren<T>(ch))
                {
                    yield return nestedChild;
                }
            }
        }
    }
    

    now call the method in your constructor(after initializeComponent method) and use it like following:-

    foreach (TextBlock tblk in FindWindowChildren<TextBlock>(window))
    {
        // use tblk here for something creative
    }
    

    If you are finding that your method is returning 0 children,try running the method in Loaded event of window rather than in constructor.

    If you want invisible elements to be included,just use LogicalTreeHelper in place of VisualTreeHelper in the method.

    So you can create a helper class with this method and use it wherever you want.

    Happy Coding:-)

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: