2

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.

Sumit Gupta
  • 2,152
  • 4
  • 29
  • 46

2 Answers2

5

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;
            }
        }
Nitin
  • 18,344
  • 2
  • 36
  • 53
  • it return me a ContentPresenter Object [and just one, where as I didn't declare or use any ControlPresenter, I just have StackPanel with couple of Button and input field in my "Content" – Sumit Gupta Sep 12 '13 at 10:06
  • yes.. you have to iterate over the contentpresenter you got for the first time. all the controls are in contentpresenter. – Nitin Sep 12 '13 at 10:08
  • so it is kind a double loop right...That is fine, but can you suggest if I always get double loop like this? – Sumit Gupta Sep 12 '13 at 10:09
  • Try using the LogicalTreeHelper instead of the VisualTreeHelper. This should give you the child you want to get. – Florian Gl Sep 12 '13 at 10:10
  • LogicalTreeHelper too provide an object that I should iterate again to get my stackpanel, so I have to iterate twice seems the solution. Thanks for your help though. – Sumit Gupta Sep 12 '13 at 10:15
4

The difference between the logical and visual tree is, that the visual tree lists all elements which are used to display the control. E.g. 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.

Florian Gl
  • 5,984
  • 2
  • 17
  • 30
  • This returns the DataContext of the ContentPresenter rather than the actual control, useful in most cases unless you happen to be trying to get the contents of a PasswordBox which doesn't bind by design. – Richard Petheram Nov 26 '14 at 12:50