Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the Children of a ContentPresenter?

Tags:

wpf

Using the code I can get a content presenter. I would like to locate the first textbox inside it and set the focus accordingly.

Dim obj = TerritoryListViewer.ItemContainerGenerator.ContainerFromItem(myModel)
like image 308
Jonathan Allen Avatar asked Nov 12 '10 10:11

Jonathan Allen


3 Answers

You can use VisualTreeHelper static class to crawl controls tree. This is how it can be accomplished in c# (sorry I'm VB dyslexic))

 T FindFirstChild<T>(FrameworkElement element) where T: FrameworkElement
    {
        int childrenCount = VisualTreeHelper.GetChildrenCount(element);
        var children = new FrameworkElement[childrenCount];

        for (int i = 0; i < childrenCount; i++)
        {
            var child = VisualTreeHelper.GetChild(element, i) as FrameworkElement;
            children[i] = child;
            if (child is T)
                return (T)child;
        }

        for (int i = 0; i < childrenCount; i++)
            if (children[i] != null)
            {
                var subChild = FindFirstChild<T>(children[i]);
                if (subChild != null)
                    return subChild;
            }

        return null;
    }
like image 189
alpha-mouse Avatar answered Nov 09 '22 21:11

alpha-mouse


ContentPresenter has the only child. You get the child simply by

VisualTreeHelper.GetChild(yourContentPresenterObj, 0);

If you need to go deeper - down to a first found TextBox, then, yes, you use the more comprehensive approach suggested by @alpha-mouse.

like image 16
epox Avatar answered Nov 09 '22 21:11

epox


Dim myContentPresenter = CType(obj, ContentPresenter)
Dim myDataTemplate = myContentPresenter.ContentTemplate
Dim target = CType(myDataTemplate.FindName("txtQuantity", myContentPresenter), TextBox)
like image 3
Jonathan Allen Avatar answered Nov 09 '22 20:11

Jonathan Allen