简体   繁体   English

WPF ContentControl:遍历子控件

[英]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. 我有一个WPF窗口,在其中放置了ContentControl,然后在代码中使用XamlReader.Load函数将字符串读取为Xaml,并将其放入ContentControl。 This is done to make a Dyanmic UI. 这样做是为了创建Dyanmic UI。 Now all is done, but I want to capture the Input field values from this control. 现在已经完成了所有操作,但是我想从此控件中捕获Input字段的值。 on button click. 在按钮上单击。

So, all I want to do is to Iterate on Child Controls of ContentControl. 因此,我要做的就是迭代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 按钮->边框-> ContentPresenter-> TextBlock

The logical tree list just the controls itsself (as you declared in your xaml). 逻辑树列表只是控制自身(如您在xaml中声明的那样)。 For further details, visit this site: http://wpftutorial.net/LogicalAndVisualTree.html 有关更多详细信息,请访问以下网站: http : //wpftutorial.net/LogicalAndVisualTree.html

So to get the children you want, LogicalTreeHelper.GetChildren(contentControl); 因此,要获取所需的子级, LogicalTreeHelper.GetChildren(contentControl); should work. 应该管用。

Here, you can use VisualTreeHelper: 在这里,您可以使用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;
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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