2012-04-16 61 views
2

我试图在wpf/xaml中创建一个控件,它将显示图像的水平列表。要修复的列表框的宽度(无滚动条)。添加新项目时,现有项目会减少用于容纳它的图像数量(实际图像不会仅减少显示的图像量)。该功能类似于将新列添加到具有相对宽度属性(“*”)的网格,并且该列包含具有固定宽度的图像。这是我的代码到目前为止:ListBox显示水平图像WPF

<Window.Resources> 
    <ItemsPanelTemplate x:Key="ListBox_HorizontalItems"> 
     <StackPanel Orientation="Horizontal" /> 
    </ItemsPanelTemplate> 

    <DataTemplate x:Key="ListBox_DataTemplate"> 
     <Grid> 
      <Grid.ColumnDefinitions> 
       <ColumnDefinition Width="50" /> 
      </Grid.ColumnDefinitions> 
      <Image Width="150" Source="{Binding ImageSource}" /> 
     </Grid> 
    </DataTemplate> 

    <Style x:Key="ListBox_Style_Horizontal" TargetType="ListBox"> 
     <Setter Property="Width" Value="150" />--> 
     <Setter Property="ItemTemplate" Value="{StaticResource ListBox_DataTemplate}" /> 
     <Setter Property="ItemsPanel" Value="{StaticResource ListBox_HorizontalItems}" /> 
    </Style> 
</Window.Resources> 

<Grid> 
    <ListBox Name="lbxImages" Style="{StaticResource ListBox_Style_Horizontal}" Width="250" Height="100" /> 
</Grid> 

这是非常接近我的需要!然而,我不能解决如何减少新的项目添加到列表中时显示的图像数量。当前添加新项目时会出现一个滚动条。柜面我不解释自己很好这里有一些截图显示我需要的功能:

3 Items 4 Items 5 Items

可有人告诉我如何实现这一目标?谢谢你的帮助!

回答

9

使用以下UniformGrid作为ItemsPanel:

<ItemsPanelTemplate> 
    <UniformGrid Columns="{Binding Path=Items.Count,RelativeSource={RelativeSource AncestorType={x:Type ListBox}}}"/> 
</ItemsPanelTemplate> 

禁用水平滚动:

<ListBox ScrollViewer.HorizontalScrollBarVisibility="Disabled"> 

修改的ItemTemplate:

<DataTemplate> 
    <Image Source="{Binding ImageSource}" 
      Stretch="None" 
      HorizontalAlignment="Center"/> 
</DataTemplate> 
+0

感谢这个,它的伟大工程!我从来没有使用“UniformGrid”,看起来很有用... – qu1ckdry 2012-04-16 11:30:19