2
votes

I have a method that adds multiple expanders in wpf, from the input of a combobox. After the combobox item is selected, a OpenFileDialog opens, and gets a filename. This happens more than once, and I seem to be overwriting my Content for the expander. Code below

private void comboBox_SetFileNames(object sender, SelectionChangedEventArgs e)
{
    var selectedItem = combobox.SelectedItem as ComboBoxItem;
    if (selectedItem != null)
        string name = selectedItem.Name;
        Expander expander = new Expander {Header = name};

        Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
        dlg.DefaultExt = ".txt";
        dlg.Filter = "Text File (*.txt) | *.txt";
        Nullable<bool> result = dlg.ShowDialog();

        if (result == true)
        {
            expander.Content = new TextBlock() { Text = System.IO.Path.GetFileName(dlg.FileName) };
        }

        dlg.Filter = "Excel Files (*.xlsx) | *.xlsx";
        Nullable<bool> result2 = dlg.ShowDialog();

        if (result2 == true)
        {
            expander.Content = new TextBlock() { Text = System.IO.Path.GetFileName(dlg.FileName) };
        }
        dock.Children.Add(expander);
    }
} 

Any way to have each of these file names listed below one another? so something like below

ExpanderName
|
------FileName1.txt
|
------FileName2.xlsx

Right now with it getting overwritten it looks like this:

ExpanderName
|
------FileName2.xlsx
1
Set your expander.Content to a StackPanel, and add your TextBlocks to the StackPanel. The Content property can only be set to a single value, while a StackPanel can contain multiple controls.Rachel
Thanks for the info. If you'd like to put that as an answer, and give a small example if you'd like, I'll accept it as an answer. Thanks again!trueCamelType

1 Answers

3
votes

Set your expander.Content to a panel like a StackPanel, and add your TextBlocks to it instead.

The Content property can only be set to a single value, while a panel like the StackPanel can contain multiple controls.

Something like this:

Expander expander = new Expander {Header = name};
StackPanel panel = new StackPanel();

var dlg = new Microsoft.Win32.OpenFileDialog();
dlg.DefaultExt = ".txt";
dlg.Filter = "Text File (*.txt) | *.txt";
Nullable<bool> result = dlg.ShowDialog();

if (result == true)
    panel.Children.Add(new TextBlock() { Text = dlg.SafeFileName });

dlg.Filter = "Excel Files (*.xlsx) | *.xlsx";
Nullable<bool> result2 = dlg.ShowDialog();

if (result2 == true)
    panel.Children.Add(new TextBlock() { Text = dlg.SafeFileName });

expander.Content = panel;
dock.Children.Add(expander);