NickGames NickGames - 1 month ago 13
C# Question

How to programatically expand all expanders in window

I've got a window with some expanders in it.
When you open a expander there is some information inside it.

What i need to do is to open all expanders with one button so everything inside them becomes visible.
When everything is visible i want to print the full page.

This is my code for expanding all expanders now:

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


The lines i use to iterate through my controls:

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


Now to the point:

The code above works in most cases.
The only problem i have is that sometimes there are some expanders WITHIN expanders.
The parent expanders do expand when the above code executes, The child expanders however remain unexpanded.

I hope someone can teach me how to expand those child expanders too.

EDIT

I forgot to mention that the child-expanders are not direct childs of the main expanders..

They are children of children of children of the main expanders.

My controll-tree goes something like this:

-Stackpanel

---List item

-----Grid

-------Expander (Main expanders)

---------Grid

-----------Textblock

-------------Expander

So i need to expand all expanders in this tree.

Answer

Okay, I found my anwser in this post

The anwser on this question is what I used to solve my problem.

Here's the function I used:

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

In my code I used these lines to append what I needed to my expanders:

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

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