VisualTreeHelper找不到DependencyObject的子代,如何可靠地找到对象? [英] VisualTreeHelper not finding children of DependencyObject, How can I reliably find objects?

查看:134
本文介绍了VisualTreeHelper找不到DependencyObject的子代,如何可靠地找到对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为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 ListItems. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆