如何让列表框项目填充整个空间?

本文关键字:空间 填充 项目 列表 | 更新日期: 2023-09-27 18:12:32

嗨,我看到有很多关于ListBox和填充DataTemplate的整个空间的问题,但我仍然无法得到任何工作。我所拥有的是一个列表框和DataTemplate有一个UserControl。我如何让我的UserControl拉伸数据来填充空间?

MainWindow XAML片段:

<ListBox x:Name="ConfiguredItemsList">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <local:ConfiguredItem DataContext="{Binding}" HorizontalContentAlignment="Stretch" />
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

UserControl XAML片段:

<UserControl.Resources>
    <local:ImagePathConverter x:Key="ImagePathConverter"/>
</UserControl.Resources>
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="75" />
    </Grid.ColumnDefinitions>
    <Grid Grid.Column="0">
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="100" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <TextBlock Grid.Row="0" Grid.Column="0" x:Name="NameLabel" Text="Name:" />
        <TextBlock Grid.Row="0" Grid.Column="1" x:Name="tbName" Text="{Binding Path=Name}" />
        <TextBlock Grid.Row="1" Grid.Column="0" x:Name="DescriptionLabel" Text="Description: " />
        <TextBlock Grid.Row="1" Grid.Column="1" x:Name="Description" Text="{Binding Path=Description}" />
        <TextBlock Grid.Row="2" Grid.Column="0" x:Name="TimeLabel" Text="Time:" />
        <TextBlock Grid.Row="2" Grid.Column="1" x:Name="Time" Text="{Binding Path=ChangeTime, StringFormat={}{0:h:mm tt}}" />            
    </Grid>
    <Border Grid.Column="1" BorderThickness="1" BorderBrush="Black">
        <Image Source="{Binding Path=WallpaperInfo, Converter={StaticResource ImagePathConverter}}" />
    </Border>
</Grid>

如何让列表框项目填充整个空间?

您是否尝试将HorizontalContentAlignment设置为在列表框级别上拉伸?

<ListBox x:Name="ConfiguredItemsList"  HorizontalContentAlignment="Stretch">
      <ListBox.ItemTemplate>
            <DataTemplate>
                <local:ConfiguredItem DataContext="{Binding}"/>
            </DataTemplate>
        </ListBox.ItemTemplate>
</ListBox>

注意:我设置了ListBoxHorizontalContentAlignment属性,而不是Item