Search code examples
c#wpfstackpanelexpander

WPF - Problem with multiple Expanders in a Stackpanel


I have some trouble with Expanders. I'm still new to WPF, maybe I'm missing something essential, but I don't know what.
So what I'm trying to do is to add Expanders programmatically to a Stackpanel, which is then added to a Scrollviewer whic is then added to another Stackpanel. The Expanders have 4 TextBlocks and each content is dynamic.
Everything works fine, except that only the first Expander I click shows the data. When I expand another Expander, the content is the same as from the first expanded. I also can only see Data in the expanded Expanders when I collapse the prior expanded.

Here is my code:

public void CreateDocuments(IcddContainerParser container)
{
    DirectoryInfo docDir = new DirectoryInfo(container.GetDocumentFolder());
    ScrollViewer scrollViewer = new ScrollViewer();
    TextBlock title = new TextBlock();
    TextBlock lastEdited = new TextBlock();
    TextBlock extension = new TextBlock();
    TextBlock size = new TextBlock();
    StackPanel textBlockPanel = new StackPanel();
    StackPanel expanderPanel = new StackPanel();

    foreach (FileInfo file in docDir.GetFiles())
    {
        Expander expander = new Expander();
        textBlockPanel.Children.Clear();
        expander.Content = null;
        expander.Header = file.Name.ToString();
        title.Text = "File Location: " + file.FullName;
        textBlockPanel.Children.Add(title);
        lastEdited.Text = "Last edited: " + file.LastWriteTime;
        textBlockPanel.Children.Add(lastEdited);
        extension.Text = "File Type: " + file.Extension;
        size.Text = "File Size: " + file.Length.ToString() + " bytes";
        textBlockPanel.Children.Add(size);
        expander.Content = textBlockPanel;
        expander.Name = System.IO.Path.GetFileNameWithoutExtension(file.Name);
        expanderPanel.Children.Add(expander);
    }
    scrollViewer.Content = expanderPanel;
    DataPanel.Children.Add(scrollViewer);
    return;
}

My Problems:

  • Expanders behave strange when expanding multiple Expanders (see above)
  • Expander TextBlocks only show Content from the first expanded Expander

What excactly is causing this behaviour? Or do you have any other approach to avoid this behaviour? I'd be grateful for any help.

EDIT:

I already tried to create an Expander Array, but then I got NullReferenceExceptions when adding content to each Expander. I also tried to use the function just once and then call the function in a loop and added a FileInfo file as parameter, but that just made it worse.


Solution

  • Replace

    textBlockPanel.Children.Clear();
    

    with

    textBlockPanel = new StackPanel();