简体   繁体   中英

How to bind data and fill/display to DataGrid or UniformGrid from ListBox selected items (SelectionMode=Multiple)

As to my question(Title), I can already bind selected items from my listBox to my uniformGrid. BUT even if I already selected many items the UniformGrid only shows 1 item.

Could you please tell me how to do this?

or is it possible to fill the UniformGrid with the ListBox items selected?

or What are the other options to transfer(bind) and show my selected items out from my ListBox?

or I'll just go and walk through the code if you have similar examples.

To be exact, my ListBox items are images BUT doesnt need to be images only. I just want to know how to bind selected items to a Grid or anything that will display my ListBox selected items.

Thank You

XAML:

<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"
x:Class="SampleBinding.MainWindow"
x:Name="Window"
Title="MainWindow"
Width="640" Height="480">
<Window.Resources>
    <DataTemplate x:Key="ItemTemplate">
        <StackPanel>
            <Image Source="{Binding myImages}" HorizontalAlignment="Left" Height="64" Width="64"/>
        </StackPanel>
    </DataTemplate>
</Window.Resources>

<Grid x:Name="LayoutRoot" DataContext="{Binding Source={StaticResource SampleDataSource}}">
    <ListBox x:Name="listBox" HorizontalAlignment="Left" ItemTemplate="{DynamicResource ItemTemplate}" ItemsSource="{Binding Collection}" Margin="19,40,0,102" Width="200" SelectionMode="Multiple"/>
    <UniformGrid x:Name="uGrid" DataContext="{Binding SelectedItem, ElementName=listBox}" Margin="273,40,78,132" d:DataContext="{Binding Collection[0]}" Grid.Row="2" Grid.Column="2">
        <Image x:Name="imageItem" Source="{Binding myImages}" HorizontalAlignment="Left" VerticalAlignment="Top" Width="100" Height="100"/>
    </UniformGrid>
</Grid>

I see that you bind grids DataContext to ListBox SelectedItem, which is always one. That's why you see only one item in grid. ( I guess it's always the last selected). To resolve this in more accurate MVVM way I, personally, would add a new observable collection ListBoxSelecetedItems, bind it to DataGrid, and on every ListBox selection add new selecteditem to that collection. If you unselect an item from list box, remove it from collection.

Hope this helps.

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