How do I get the Children of a ContentPresenter?

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;
    }

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.


Dim myContentPresenter = CType(obj, ContentPresenter)
Dim myDataTemplate = myContentPresenter.ContentTemplate
Dim target = CType(myDataTemplate.FindName("txtQuantity", myContentPresenter), TextBox)

Tags:

Wpf