【问题标题】:How do I customize the layout of a ListBox's ItemsPanelTemplate?如何自定义 ListBox 的 ItemsPanelTemplate 的布局?
【发布时间】:2012-07-11 15:49:21
【问题描述】:

我想为我的ListBox 指定多个列,但我的谷歌搜索技能在这一列上失败了。

如何修改ListBoxItemsPanelTemplate 以自定义显示的列?

编辑:忘记放我已经尝试过的内容

我试过代码

<ItemsPanelTemplate x:Key="ItemsPanelTemplate1">
        <UniformGrid Columns="3" />
    </ItemsPanelTemplate>

除了我失去垂直滚动条外,其他方法有效

【问题讨论】:

  • 您希望修改ItemsPanelTemplate 的哪些控件?
  • A ListBox,虽然只是因为这是 Blend 为我自动生成的...我想在网格中显示列表中的项目,例如不太复杂的 Zune 专辑艺术视图。
  • 您真的需要ListBox 的选择功能吗?如果没有,我建议切换到ItemsControl,我的博客上有一些ItemsControl Examples,其中包括有关设置ItemsPanelTemplate 的示例
  • 我想要选择功能,是的 - 我打算将另一个控件绑定到 ListBox.Selected 属性以显示有关所选项目的更多详细信息
  • 您能否更具体地说明您对这些列所做的工作?您是想在项目中设置多列,例如 DataGrid,还是尝试将项目本身水平布局然后垂直包装?

标签: wpf expression-blend itemspaneltemplate


【解决方案1】:

这应该不是那么困难,但这取决于 - 如果您对每个项目使用网格或类似的控件,并且您不介意列的宽度不同且其中包含可变宽度的项目,那么只需将网格添加到 ItemTemplate 就可以了。

<ItemTemplate>
    <DataTemplate>
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition>
                <ColumnDefinition>
                <ColumnDefinition>
            </Grid.ColumnDefinitions>
            <SomeControl Grid.Column="0" />
            <SomeControl Grid.Column="1" />
            <SomeControl Grid.Column="2" />
        </Grid>
    </DataTemplate>
</ItemTemplate>

唯一的问题是,如果您希望网格列的大小都相同且内容大小可变 - 在这种情况下会涉及更多内容 - 否则您可以明确设置大小,或者让内容决定通过将列宽设置为"Auto"来调整大小。

【讨论】:

    【解决方案2】:

    这是我认为您正在寻找的一个简单示例,包含 3 列、项目换行和自动垂直滚动,这将取决于周围的布局。

    <ListBox HorizontalContentAlignment="Stretch">
        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <UniformGrid Columns="3"/>
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Border MinHeight="150" Margin="5" Background="Green" CornerRadius="4">
                    <TextBlock Text="{Binding}" Foreground="White"/>
                </Border>
            </DataTemplate>
        </ListBox.ItemTemplate>
    
        <System:String>One</System:String>
        <System:String>Two</System:String>
        <System:String>Three</System:String>
        <System:String>Four</System:String>
        <System:String>Five</System:String>
        <System:String>Six</System:String>
        <System:String>Seven</System:String>
        <System:String>Eight</System:String>
        <System:String>Nine</System:String>
        <System:String>Ten</System:String>
    </ListBox>
    

    【讨论】:

      猜你喜欢
      • 2010-10-29
      • 2015-12-03
      • 2012-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-07
      相关资源
      最近更新 更多