gpt4 book ai didi

c# - WPF - 获取页面上给定类型的所有控件的集合?

转载 作者:行者123 更新时间:2023-11-30 19:20:10 28 4
gpt4 key购买 nike

我试图获取给定页面上给定类型的所有控件的列表,但我遇到了问题。似乎 VisualTreeHelper 可能只返回已加载的控件?我尝试关闭虚拟化,但这似乎没有帮助。任何人都可以想出另一种方法来获得所有控制权或者强制加载 UI 以便以下方法起作用吗?

我从 MSDN 借来的:

 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;
}
}
}
}

最佳答案

请参阅以下主题:Finding all controls of a given type across a TabControl

梁涛的回答很好解释

The reason is that the WPF designer want to optimize the performance of TabControl. Suppose there are 5 TabItems, and each TabItem contains alot of children. If WPF program have to construct and render all the children, it will be very slow. But if TabControl only handle the children just in the current selected TabItem, much memory will be saved.

您可以试试逻辑树。
这是一个示例实现,看看它是否更适合您

像这样使用它..

List<Button> buttons = GetLogicalChildCollection<Button>(yourPage);

GetLogicalChildCollection

public static List<T> GetLogicalChildCollection<T>(object parent) where T : DependencyObject
{
List<T> logicalCollection = new List<T>();
GetLogicalChildCollection(parent as DependencyObject, 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);
}
}
}

关于c# - WPF - 获取页面上给定类型的所有控件的集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7153248/

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