[英]How to dynamically add multiple Contents to an expander in WPF
I have a method that adds multiple expanders in wpf, from the input of a combobox. 我有一种方法,可以从组合框的输入在wpf中添加多个扩展器。 After the combobox item is selected, a OpenFileDialog opens, and gets a filename. 选择组合框项目后,将打开一个OpenFileDialog,并获取一个文件名。 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
Set your expander.Content
to a panel like a StackPanel
, and add your TextBlocks
to it instead. 将您的expander.Content
设置到一个StackPanel
类的面板上,然后将TextBlocks
添加到其中。
The Content
property can only be set to a single value, while a panel like the StackPanel
can contain multiple controls. Content
属性只能设置为一个值,而StackPanel
类的面板可以包含多个控件。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.