11

是否有标准/最佳方式来分隔 WPF 中的项目ListBox,以便连续项目之间有空间,但不高于第一个或低于最后一个?

对我来说,添加间距最明显的方法是修改ItemTemplate以在每个项目的上方、下方或上方和下方包含空间。当然,这意味着在第一个和/或最后一个项目或单个项目的上方/下方也会有空间。

我可以使用触发器为第一个、最后一个、中间项目选择不同的模板,但想知道是否有一些更简单的东西我错过了——似乎控制间距是一个常见的要求。

谢谢。

注意:我在 WPF 中工作,但假设这在 Silverlight XAML 中是相似的(如果不相同)。

4

2 回答 2

11

我要做的是,在 ListBox 控件模板上给予负边距,并为 DataTemplate/ItemContainerStyle 提供相同的边距。这使得第一个和最后一个项目的空间。检查以下 XAML。相反,我在 DataTemplate 中设置了 Button(ListBoxItem) 本身的边距。

   <Windows.Resources> 
     <ControlTemplate x:Key="ListBoxControlTemplate1" TargetType="{x:Type ListBox}">
        <Grid Background="{TemplateBinding Background}">
            <ItemsPresenter Margin="0,-5"/>
        </Grid>
       </ControlTemplate>
   </Window.Resources>


  <ListBox HorizontalAlignment="Center" VerticalAlignment="Center" Template="{DynamicResource ListBoxControlTemplate1}" Background="#FFAB0000">
        <Button Content="Button" Width="88" Margin="0,5"/>
        <Button Content="Button" Width="88" Margin="0,5"/>
        <Button Content="Button" Width="88" Margin="0,5"/>
        <Button Content="Button" Width="88" Margin="0,5"/>
        <Button Content="Button" Width="88" Margin="0,5"/>
    </ListBox>
于 2010-03-22T17:04:25.183 回答
2

您可以使用 aStyleSelector并将其分配给该ItemContainerStyleSelector属性。在样式选择器中,您只需根据项目是第一个、最后一个还是其他来选择不同的样式

于 2010-03-22T17:11:04.317 回答