Wpf 查找包含隐藏节点和折叠节点的逻辑子节点
我试着找到这个问题的答案,在每一篇文章中,我都能找到一个递归查找孩子的答案,但没有一个能解决隐藏或崩溃的孩子 在每一篇帖子中都有人问这是否可行,但没有人回答,所以我开始认为这是不可能的 如果有人能做到这一点,我将永远感激 我的函数如下所示:Wpf 查找包含隐藏节点和折叠节点的逻辑子节点,wpf,xaml,recursion,logical-tree,Wpf,Xaml,Recursion,Logical Tree,我试着找到这个问题的答案,在每一篇文章中,我都能找到一个递归查找孩子的答案,但没有一个能解决隐藏或崩溃的孩子 在每一篇帖子中都有人问这是否可行,但没有人回答,所以我开始认为这是不可能的 如果有人能做到这一点,我将永远感激 我的函数如下所示: public static DependencyObject FindLogicalDescendentByName(this DependencyObject source, string name) { Depen
public static DependencyObject FindLogicalDescendentByName(this DependencyObject source, string name)
{
DependencyObject result = null;
IEnumerable children = LogicalTreeHelper.GetChildren(source);
foreach (var child in children)
{
if (child is DependencyObject)
{
if (child is FrameworkElement)
{
if ((child as FrameworkElement).Name.Equals(name))
result = (DependencyObject)child;
else
result = (child as DependencyObject).FindLogicalDescendentByName(name);
}
else
{
result = (child as DependencyObject).FindLogicalDescendentByName(name);
}
if (result != null)
return result;
}
}
return result;
}
-编辑
所以
我意识到我的问题是我试图在物品创建之前找到它
我绑定到xaml中的一个属性,该属性将启动并查找具有给定名称的项目,但该项目当时未创建,如果我在xaml中重新排序该项目,它将工作,并且该项目已找到。。。啊 这是我的代码,如果您指定X:Name和类型,它就会工作 呼叫示例:
System.Windows.Controls.Image myImage = FindChild<System.Windows.Controls.Image>(this (or parent), "ImageName");
/// <summary>
/// Find specific child (name and type) from parent
/// </summary>
public static T FindChild<T>(DependencyObject parent, string childName) where T : DependencyObject
{
// Confirm parent and childName are valid.
if (parent == null) return null;
T foundChild = null;
int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < childrenCount; i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
// If the child is not of the request child type child
T childType = child as T;
if (childType == null)
{
// recursively drill down the tree
foundChild = FindChild<T>(child, childName);
// If the child is found, break so we do not overwrite the found child.
if (foundChild != null) break;
}
else if (!string.IsNullOrEmpty(childName))
{
var frameworkElement = child as FrameworkElement;
// If the child's name is set for search
if (frameworkElement != null && frameworkElement.Name == childName)
{
// if the child's name is of the request name
foundChild = (T)child;
break;
}
}
else
{
// child element found.
foundChild = (T)child;
break;
}
}
return foundChild;
}
System.Windows.Controls.Image myImage=FindChild(此(或父级),“ImageName”);
///
///从父级查找特定子级(名称和类型)
///
公共静态T FindChild(DependencyObject父对象,字符串childName),其中T:DependencyObject
{
//确认父项和子项名称有效。
if(parent==null)返回null;
T foundChild=null;
int childrenCount=visualtreeheloper.GetChildrenCount(父级);
for(int i=0;i
这似乎仍然不起作用,我有两个可能的扳手要插入。1.我的控件位于第三方面板中,该面板似乎没有任何可视树元素,但具有逻辑树元素,因此使用逻辑树。2.第三方面板和其中的所有控件都在一个资源字典中,并用作模板。因此,我在我希望找到的两个控件周围添加了一个小堆栈面板,我已经仔细阅读了您的代码,当我到达堆栈面板时,childrenCount从VisualTreeHelper返回,其值为1,这是可见的控件,不可见的控件仍然丢失。。。它们的类型相同,并且都有x:Name属性setI。我发现我做错了什么。谢谢你的回复