在WPF / Silverlight ListBox中的项目之间添加空格,而不是在第一个或最后一个之上的空格

时间:2010-03-22 16:43:47

标签: .net wpf silverlight xaml listbox

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

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

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

感谢。

注意:我在WPF中工作,但假设在Silverlight XAML中这是相似的。

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分:2)

您可以使用StyleSelector并将其分配给ItemContainerStyleSelector媒体资源。在样式选择器中,您只需根据项目是第一个,最后一个还是其他

来选择不同的样式