Skip to main content
 首页 » 编程设计

c#之水平列表框项目拉伸(stretch)

2024年02月06日15mayingbao

我的 WPF 列表框有问题。首先,我有一个带有自定义 ItemTemplate 的水平列表框。现在,我想拉伸(stretch)项目,以便项目适合 ListBox 的整个宽度。我尝试了将 Horizo​​ntalContentAlignment 设置为 Stretch 之类的方法,但这仍然无效。

这是我的ItemTemplate:

<DataTemplate x:Key="ListViewStepTemplate"> 
    <Grid VerticalAlignment="Stretch"> 
        <TextBlock Text="{Binding Path=Title}"  
                   FontSize="15" 
                   HorizontalAlignment="Center"  
                   VerticalAlignment="Center" /> 
 
        <Image Height="16"  
               Width="16" 
               HorizontalAlignment="Right" 
               VerticalAlignment="Bottom" 
               Source="/images/Content/check_16x16.png" 
               Visibility="{Binding Path=IsDone, Converter={StaticResource BooleantoVisibilityConverter}, UpdateSourceTrigger=PropertyChanged}" /> 
    </Grid> 
</DataTemplate> 


这是我的 ListBox:

<ListBox DockPanel.Dock="Top"  
         ItemsSource="{Binding AllItemsList}"  
         SelectedItem="{Binding CurrentItem}"  
         ItemTemplate="{StaticResource ListViewStepTemplate}"  
         Height="60"  
         HorizontalContentAlignment="Stretch"> 
 
    <ListBox.ItemsPanel> 
        <ItemsPanelTemplate> 
            <StackPanel Orientation="Horizontal" /> 
        </ItemsPanelTemplate> 
    </ListBox.ItemsPanel> 
 
    <ListBox.ItemContainerStyle> 
        <Style TargetType="{x:Type ListBoxItem}"> 
            <Setter Property="IsEnabled" Value="{Binding IsEnabled, UpdateSourceTrigger=PropertyChanged}" /> 
            <Setter Property="HorizontalContentAlignment" Value="Stretch" /> 
            <Setter Property="Padding" Value="30 0" /> 
        </Style> 
    </ListBox.ItemContainerStyle> 
</ListBox> 

如果有 4 个项目,每个项目的宽度应为 25%。如果有 5 个项目,则每个项目的宽度应为 20%,依此类推。

是否可以做我想做的事?我现在尝试了很多东西,但从来没有奏效。

请您参考如下方法:

而不是使用 StackPanel 使用 UniformGrid

Provides a way to arrange content in a grid where all the cells in the grid have the same size.

并将列数绑定(bind)到列表中的项目数并禁用水平滚动功能。

<ListBox  
   ... 
   ItemsSource="{Binding AllItemsList}"  
   ScrollViewer.HorizontalScrollBarVisibility="Disabled"  
   ScrollViewer.VerticalScrollBarVisibility="Disabled" > 
   <ListBox.ItemsPanel> 
      <ItemsPanelTemplate> 
         <UniformGrid Rows="1" Columns="{Binding AllItemsList.Count}"/> 
      </ItemsPanelTemplate> 
   </ListBox.ItemsPanel> 
   <ListBox.ItemContainerStyle> 
      <Style TargetType="{x:Type ListBoxItem}"> 
         <!-- style --> 
      </Style> 
   </ListBox.ItemContainerStyle> 
</ListBox>