gpt4 book ai didi

c# - 查找所有子控件 WPF

转载 作者:可可西里 更新时间:2023-11-01 08:22:52 27 4
gpt4 key购买 nike

我想找到一个 WPF 控件中的所有控件。我看过很多示例,似乎它们都需要将名称作为参数传递,或者根本不起作用。

我有现有的代码,但它不能正常工作:

public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
if (child != null && child is T)
{
yield return (T)child;
}

foreach (T childOfChild in FindVisualChildren<T>(child))
{
yield return childOfChild;
}
}
}
}

例如,它不会在 TabItem 中获取 DataGrid

有什么建议吗?

最佳答案

你可以使用这些。

 public static List<T> GetLogicalChildCollection<T>(this DependencyObject parent) where T : DependencyObject
{
List<T> logicalCollection = new List<T>();
GetLogicalChildCollection(parent, logicalCollection);
return logicalCollection;
}

private static void GetLogicalChildCollection<T>(DependencyObject parent, List<T> logicalCollection) where T : DependencyObject
{
IEnumerable children = LogicalTreeHelper.GetChildren(parent);
foreach (object child in children)
{
if (child is DependencyObject)
{
DependencyObject depChild = child as DependencyObject;
if (child is T)
{
logicalCollection.Add(child as T);
}
GetLogicalChildCollection(depChild, logicalCollection);
}
}
}

您可以像这样在 RootGrid f.e 中获取子按钮控件:

 List<Button> button = RootGrid.GetLogicalChildCollection<Button>();

关于c# - 查找所有子控件 WPF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14875042/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com