简体   繁体   中英

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

I have added single item into ItemsSource which is a folder path and all the images will be added into ListBox but I want to add more items into existing ListBox using same ItemsSource how to do this?

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>

But only ComboBox2_Loaded item gets added and displayed not ComboBox1_Loaded how can I get both the items?

You'll need to create a list that can be changed to store your file names in:

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

From there, you can add and remove all the items you want:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM