如何以编程方式扩展 window 中的所有扩展器

How to programatically expand all expanders in window

我有一个 window,里面有一些扩展器。 当你打开扩展器时,里面有一些信息。

我需要做的是一键打开所有扩展器,让里面的所有内容都可见。 当一切都可见时,我想打印整页。

这是我现在展开所有扩展器的代码:

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

我用来遍历控件的代码行:

foreach (Expander exp in FindVisualChildren<Expander>(printpage))
{
    exp.IsExpanded = true;
}

进入正题:

上面的代码在大多数情况下都有效。 我遇到的唯一问题是有时在扩展器中有一些扩展器。 当上述代码执行时,parent 扩展器确实扩展了,但是 child 扩展器保持未扩展。

我希望有人能教我如何扩展那些 child 扩展器。

编辑
我忘了提到 child-expanders 不是主扩展器的直接 childs..
他们是 children of children of children of the main expanders.

我的 controll-tree 是这样的:

-堆栈面板
---列表项
-----网格
--------Expander(主要扩展器)
----------网格
----------文本块
--------------扩展器

所以我需要展开这棵树中的所有扩展器。

你的代码已经很复杂了。如果你调用,yield 是绝对没有必要的,你真的应该以递归的方式执行你的方法。

当在您的方法中遇到带子控件的控件时,您调用相同的方法但使用新的可视根,这将是您刚刚找到的带子控件的控件。

这应该对你有用(可能有一些语法错误,但我确定你是否可以修复它们)

foreach (Expander exp in FindVisualChildren<Expander>(printpage))
{
    exp.IsExpanded = true;
    for(int i =0;i<exp.Children.Count;i++)
    {
        if(exp.Children[i] is Expander)
        {
             expandChildren(exp.Children[i]);
        }
    }
}

private expandChildren(Expander exp)
{
    exp.IsExpanded = true;
    for(int i =0;i<exp.Children.Count;i++)
    {
        if(exp.Children[i] is Expander)
        {
             expandChildren(exp.Children[i]);
        }
    }       
}

好的,我在这个 post

中找到了答案

这个问题的答案是我用来解决问题的。

这是我使用的函数:

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

在我的代码中,我使用这些行将我需要的内容附加到我的扩展器中:

List<Expander> exp = GetLogicalChildCollection<Expander>(printpage.StackPanelPrinting);

foreach (Expander exp in expander)
{
    exp.IsExpanded = true;
    exp.FontWeight = FontWeights.Bold;
    exp.Background = Brushes.LightBlue;
}