我的ListBox中的项目之间有空隙

38

当我创建水平排列项目的ListBox时,例如像这样:

<DockPanel>
    <ListBox>
        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <VirtualizingStackPanel Orientation="Horizontal" />
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
        <ListBoxItem>
            <Button Content="Hello" />
        </ListBoxItem>
        <ListBoxItem>
            <Button Content="Hello" />
        </ListBoxItem>
    </ListBox>
</DockPanel>

我在列表中的按钮之间有小间隙,如下图所示:

Picture showing gaps

请问如何消除这些间隙?我需要将ListBox中的项紧挨在一起。我尝试更改ListBoxItemTemplate,但没有帮助。


当我使用传统的垂直方向的 ListBox 时,没有任何项像期望和想要的那样挨在一起... :( - Rasto
2个回答

52

这是因为ListBoxItem的默认ItemContainerStyle内部有填充。要删除它,您可以重写ItemContainerStyle。例如,只需将下面的空ItemContainerStyle应用于您的ListBox,您就会发现边距不再存在。

    <ListBox >
        <ListBox.ItemsPanel>
            <ItemsPanelTemplate >
                <VirtualizingStackPanel IsItemsHost="True" Orientation="Horizontal"/>
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
        <ListBox.ItemContainerStyle>
            <Style TargetType="{x:Type ListBoxItem}">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="{x:Type ListBoxItem}">
                            <ContentPresenter/>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </ListBox.ItemContainerStyle>
        <Button Content="hello1" Width="75"/>
        <Button Content="Hello2" Width="75"/>
    </ListBox>

太棒了,太棒了,太棒了!运行得非常好!节省了我很多时间 :) 谢谢。 - Rasto
4
破坏了 ListBox 的选择处理。 - bugged87
7
这段代码可以删除项之间的空格,但会完全删除选择功能。与之前被接受的答案中触及ContentPresenter不同,我通过将Padding和Margin都设置为0来解决我的问题。我还注意到只更改其中一个,如下面某人建议的那样是行不通的。因此,我没有更改上面的Template属性,而是只做了<Setter Property="Padding" Value="0"/>; <Setter Property="Margin" Value="0"/>。这样可以去除项之间的空格,同时保留选择功能。 - pixel

43

这些间隙位于ListViewItemsControlTemplate内部,恐怕您必须覆盖该模板...

编辑: 在某些平台上,您甚至不需要深入涉足Template即可消除项之间的间隙:

    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="Padding" Value="0"/>
        </Style>
    </ListBox.ItemContainerStyle>
为了消除边缘处的空隙,您实际上需要更改ListBox控件模板本身,这不是关于项的问题。在默认的Aero模板中,有一个带有Padding = 1的边框。

你能提供一个快速的代码示例吗?即使我使用其他控件作为ListBox的项,仍然存在相同的间隙... - Rasto
混合在ListViewItem中,已编辑,我将尝试为您提供一种摆脱它们的方法。编辑:好吧,另一个答案已经足够完整了,所以不需要这个了... - H.B.
@pixel:另外,我一开始也提供了那个解决方案,所以不要因为易用的基于Aero的替代方法在你的情况下无法工作而对我进行负评 :| - H.B.
有趣的是,我刚刚按照你上面的建议添加了Margin的Setter,并且它可以正常工作,前提是我使用与上面答案相同的ItemsPanelTemplate。谢谢。 - pixel
很好。这将保持“选择”行为。 为了完全避免间隙,您可以将Margin、Padding和BorderThickness都设为0。 - Lumo
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接