2015-02-09 90 views
0

我有我的列表框在WPF中的問題。首先,我有一個帶自定義ItemTemplate的水平ListBox。現在,我想拉伸項目,以便項目適合ListBox的完整寬度。我嘗試了將HorizontalContentAlignment設置爲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 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%,依此類推。

是否可以做我想做的事情?我現在嘗試了很多東西,但它永遠不會工作。

回答

2

而不是使用StackPanel使用UniformGrid

提供了一個方式來安排在網格中的內容,其中網格中的所有單元格的大小相同。

並將列數綁定到列表中的項數和禁用水平滾動功能。

<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> 
+1

感謝您的回答。它的工作原理是我想要的。 – 2015-02-09 13:23:26

1

請勿使用StackPanel,請改爲使用UniformGrid

<ItemsPanelTemplate> 
    <UniformGrid Rows="1" Columns="{Binding DataContext.Count, RelativeSource={RelativeSource Self}}"/> 
</ItemsPanelTemplate>