如何将多个项目添加到 ItemsSource WPF 多集合绑定中?

how to add multiple items into ItemsSource WPF multiple collection binding?

我已将单个项目添加到 ItemsSource 中,这是一个文件夹路径,所有图像都将添加到 ListBox 中,但我想使用相同的方法将更多项目添加到现有 ListBoxItemsSource如何做到这一点?

List<string> folders = new List<string>();
    private void ComboBox1_Loaded(object sender, RoutedEventArgs e)
    {
folders.AddRange(Directory.EnumerateFiles(@"C:\Users\images1", "*.*").ToList());
        imageItems.ItemsSource = folders;            
    } 

    private void ComboBox2_Loaded(object sender, RoutedEventArgs e)
    {
folders.AddRange(Directory.EnumerateFiles(@"C:\Users\images2", "*.*").ToList());
        imageItems.ItemsSource = folders;        
    } 

    <ListBox x:Name="imageItems" ScrollViewer.HorizontalScrollBarVisibility="Disabled">
        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <WrapPanel IsItemsHost="True" />
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Image Source="{Binding}" Width="120" Height="120"/>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ListBox>

但只有 ComboBox2_Loaded 项被添加和显示,而不是 ComboBox1_Loaded 我怎样才能得到这两个项目?

您需要创建一个可以更改的列表,以将您的文件名存储在:

ObservableCollection<string> folders = new ObservableCollection<string>();

从那里,您可以添加和删除所需的所有项目:

imageItems.ItemsSource = folders;

foreach (string file in Directory.EnumerateFiles(@"C:\Users\images1", "*.*"))
{
    folders.Add(file);
}

foreach (string file in Directory.EnumerateFiles(@"C:\Users\images2", "*.*"))
{
    folders.Add(file);
}