#424 – 使ListBox 中每一项保持一致大小(Getting Data-Bound Items in a ListBox to Be a Consistent Size)

来源:互联网 发布:人民大学数据库 编辑:程序博客网 时间:2024/06/02 07:30


之前演示了如何通过数据绑定向ListBox中添加丰富的内容。

但问题是在垂直方向上各项的内容并没有对齐。我们在数据模板中使用的是StackPanel,它会自动根据内容调整大小。

我们不希望它自动调整大小,而是所有的数据中相同的列有相同的宽度。

我们可以使用Grid.IsSharedSizeScopeSharedSizeGroup属性在所有子项中共享大小。


<ListBox ItemsSource="{Binding MovieList}" SnapsToDevicePixels="True"         Grid.IsSharedSizeScope="True">    <ListBox.ItemTemplate>        <DataTemplate>            <StackPanel Orientation="Horizontal" Margin="0,0,0,5">                <Grid>                    <Grid.ColumnDefinitions>                        <ColumnDefinition SharedSizeGroup="Col1"/>                    </Grid.ColumnDefinitions>                    <Image Source="{Binding Image}" />                </Grid>                <Grid>                    <Grid.ColumnDefinitions>                        <ColumnDefinition SharedSizeGroup="Col2"/>                    </Grid.ColumnDefinitions>                    <StackPanel Orientation="Vertical">                        <Label Content="{Binding Title}" FontWeight="Bold"/>                        <Label Content="{Binding Year}"/>                    </StackPanel>                </Grid>                 <Border BorderBrush="Black" BorderThickness="0.5"/>                 <Grid>                    <Grid.ColumnDefinitions>                        <ColumnDefinition SharedSizeGroup="Col3"/>                    </Grid.ColumnDefinitions>                    <StackPanel Orientation="Vertical">                        <Label Content="Actors:"/>                        <Label Content="{Binding ActorLead}" Margin="10,0"/>                        <Label Content="{Binding ActressLead}" Margin="10,0"/>                    </StackPanel>                </Grid>                 <Border BorderBrush="Black" BorderThickness="0.5"/>                 <StackPanel Orientation="Vertical">                    <Label Content="Director:"/>                    <Label Content="{Binding Director}" Margin="10,0"/>                </StackPanel>            </StackPanel>        </DataTemplate>    </ListBox.ItemTemplate></ListBox>

原文地址:https://wpf.2000things.com/2011/11/07/424-getting-data-bound-items-in-a-listbox-to-be-a-consistent-size/


0 0