WPF-Stackpanel中有多个扩展器的问题

问题描述 投票:1回答:1

我在扩展器上遇到了一些麻烦。我还是WPF的新手,也许我缺少一些重要的东西,但是我不知道是什么。所以我想做的是以编程方式将Expanders添加到Stackpanel,然后将其添加到Scrollviewer,然后再添加到另一个Stackpanel。扩展器有4个TextBlock,每个内容都是动态的。一切正常,除了我单击的第一个扩展器显示数据。当我扩展另一个扩展器时,内容与第一个扩展器中的内容相同。当我折叠先前的扩展时,我也只能在扩展的扩展器中看到数据。

这是我的代码:

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

我的问题:

  • 扩展多个扩展器时,扩展器的行为很奇怪(参见上文)
  • Expander TextBlocks仅显示第一个扩展的Expander中的内容

究竟是什么导致这种行为?还是您有其他方法可以避免这种行为?我将不胜感激。

编辑:

我已经尝试创建一个扩展器数组,但是在向每个扩展器添加内容时得到了NullReferenceExceptions。我也尝试只使用一次该函数,然后在循环中调用该函数,并添加了FileInfo file作为参数,但这使情况变得更糟。

c# wpf stackpanel expander
1个回答
0
投票

替换

textBlockPanel.Children.Clear();

with

textBlockPanel = new StackPanel();
© www.soinside.com 2019 - 2024. All rights reserved.