简体   繁体   中英

WPF ContentControl: Iterating over child control

I have a WPF Window, where I put a ContentControl, Later in my code I use a string to be read as Xaml using XamlReader.Load function and put that in ContentControl. This is done to make a Dyanmic UI. Now all is done, but I want to capture the Input field values from this control. on button click.

So, all I want to do is to Iterate on Child Controls of ContentControl. How can I do this, there doesn't seems a way to iterate on child of it? Any Idea. Thanks.

The difference between the logical and visual tree is, that the visual tree lists all elements which are used to display the control. Eg The visual tree of a button looks like

Button -> Border -> ContentPresenter -> TextBlock

The logical tree list just the controls itsself (as you declared in your xaml). For further details, visit this site: http://wpftutorial.net/LogicalAndVisualTree.html

So to get the children you want, LogicalTreeHelper.GetChildren(contentControl); should work.

Here, you can use VisualTreeHelper:

        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(contentControl); i++)
        {
            var child = VisualTreeHelper.GetChild(contentControl, i);
            if(child is ContentPresenter)
            {
                var contentPresenter = child as ContentPresenter;
                for (int j = 0; j < VisualTreeHelper.GetChildrenCount(contentPresenter); j++)
                {
                    var innerChild = VisualTreeHelper.GetChild(contentPresenter, j);
                }

                break;
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM