可视树 - 查找内容等于的标签(窗口上的任何位置)

时间:2012-01-09 14:41:56

标签: c# wpf visual-tree

我有许多标签作为许多不同堆栈面板的子项,它们都是列表框的子项,我需要引用其中一个标签是Content.toString()==“criteria”。换句话说,在WPF中遍历可视化树将是一个球疼,因为有许多父/子方法要运行。有没有办法在我的窗口上找到这些标签之一而没有它的名字,并假设我不知道它在树上的“向下”有多远?也许在窗口中有一个项目集合(没有heirarchy),我可以运行一些LINQ反对??

如果您想知道为什么我没有标签的名称 - 这是因为它们是由数据模板生成的。

非常感谢,

4 个答案:

答案 0 :(得分:2)

看起来像您正在寻找的内容:Find DataTemplate-Generated Elements

答案 1 :(得分:1)

我不知道这是否有帮助:

如果您要在listBox中的每个堆栈面板中查找特定标签,那么您可以查找具有其特定名称的特定标签并比较内容。

答案 2 :(得分:1)

我认为此代码可能对您有用:

        foreach (Control control in this.Controls)
        {
            if (control.GetType() == typeof(Label))
                if (control.Text == "yourText")
                {
                    // do your stuff
                }
        }

我使用This question作为我的基础

答案 3 :(得分:1)

我对@anatoliiG链接的代码稍作修改,以便返回指定类型(而不是第一个)的所有子控件:

private IEnumerable<childItem> FindVisualChildren<childItem>(DependencyObject obj)
    where childItem : DependencyObject
{
    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
    {
        DependencyObject child = VisualTreeHelper.GetChild(obj, i);

        if (child != null && child is childItem)
            yield return (childItem)child;

        foreach (var childOfChild in FindVisualChildren<childItem>(child))
            yield return childOfChild;
    }
}

使用此功能,您可以执行以下操作:

var criteriaLabels =
    from cl in FindVisualChildren<Label>(myListBox)
    where cl.Content.ToString() == "criteria"
    select cl;

foreach (var criteriaLabel in criteriaLabels)
{
    // do stuff...
}