VisualTreeHelper找不到DependencyObject的子代,如何可靠地找到对象? [英] VisualTreeHelper not finding children of DependencyObject, How can I reliably find objects?
问题描述
我有一个名为ZoneContainer
的UserControl.它具有一个包含ListBox
的属性,该ListBox
包含许多ListItem
.每个ListItem都包含一个DockPanel
.
I have a UserControl called ZoneContainer
. This has a property that which contains a ListBox
containing a number of ListItem
s. Each ListItem contains a DockPanel
.
我正在尝试使用以下代码查找ZoneContainer
内部存在的子代,但childrenCount
每次都是0.
I'm trying to use a the following code to find the children that exist inside ZoneContainer
but childrenCount
is 0 every time.
var parent = this as DependencyObject; // I can see that this is populated.
int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
还有另一种方法可以在对象列表中找到特定的子对象吗?最终,我试图找到DockPanel,但是即使我知道他们在对象中,也没有找到任何孩子.
Is there another way to find a specific child object inside a list of objects? Ultimately I'm trying to find the DockPanel, but it's not finding any children even though I know they're in the object.
推荐答案
我通过查询对象而不是对可视树进行爬网来解决了此问题.
I resolved this issue by querying the objects rather than crawling the visual tree.
var header = container.ListBox.Items.Cast<ListBoxItem>()
.Select(item => (MyType) item.Content)
.FirstOrDefault(myType => myType.dpHeader.Name == "whatever").dpHeader;
这篇关于VisualTreeHelper找不到DependencyObject的子代,如何可靠地找到对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!