我有许多标签作为许多不同堆栈面板的子级,它们都是列表框的子级,我需要引用其中一个标签是 Content.toString() == "criteria"。换句话说,在 WPF 中遍历可视化树会很痛苦,因为要运行许多父/子方法。有没有办法在我的窗口上找到这些标签中的一个而没有它的名字并假设我不知道它在树中“向下”多远?也许有一个窗口中所有东西的项目集合(没有层次结构),我可以运行一些 LINQ?
如果您想知道为什么我没有标签的名称 - 这是因为它们是由数据模板生成的。
非常感谢,
担
我有许多标签作为许多不同堆栈面板的子级,它们都是列表框的子级,我需要引用其中一个标签是 Content.toString() == "criteria"。换句话说,在 WPF 中遍历可视化树会很痛苦,因为要运行许多父/子方法。有没有办法在我的窗口上找到这些标签中的一个而没有它的名字并假设我不知道它在树中“向下”多远?也许有一个窗口中所有东西的项目集合(没有层次结构),我可以运行一些 LINQ?
如果您想知道为什么我没有标签的名称 - 这是因为它们是由数据模板生成的。
非常感谢,
担
看起来像你在找什么:Find DataTemplate-Generated Elements
我不知道这是否会有所帮助:
如果您在 listBox 的每个堆栈面板中查找特定标签,则只需查找具有特定名称的特定标签并比较内容。
我认为这段代码可能对你有用:
foreach (Control control in this.Controls)
{
if (control.GetType() == typeof(Label))
if (control.Text == "yourText")
{
// do your stuff
}
}
我用这个问题作为我的基础
为了返回指定类型的所有子控件(而不是第一个),我对@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...
}