如何从ListBox选中的项目中绑定数据并填充/显示到DataGrid或UniformGrid(SelectionMode = Multiple)

时间:2011-12-03 09:21:17

标签: c# wpf visual-studio-2010 expression-blend-4

关于我的问题(标题),我已经可以将我的listBox中的所选项绑定到我的uniformGrid。 但是即使我已经选择了很多项目,UniformGrid也只会显示1个项目。

你能告诉我怎么做吗?

是否可以使用选定的ListBox项填充UniformGrid?

从我的ListBox中转移(绑定)和显示我选择的项目有哪些其他选项?

如果你有相似的例子,我会去看看代码。

确切地说,我的ListBox项目是图像但是不需要只是图像。我只是想知道如何将所选项目绑定到网格或任何将显示我的ListBox选定项目的任何项目。

谢谢

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>

1 个答案:

答案 0 :(得分:0)

我看到你将网格DataContext绑定到ListBox SelectedItem,它总是一个。这就是为什么你只看到网格中的一个项目。 (我猜它总是最后选择的)。要以更准确的MVVM方式解决这个问题,我个人会添加一个新的可观察集合ListBoxSelecetedItems,将其绑定到DataGrid,并在每个ListBox选择中向该集合添加新的selecteditem。如果取消选择列表框中的项目,请将其从集合中删除。

希望这有帮助。