我的ListBox中的项之间的差距

Ras*_*sto 27 .net wpf listview listbox wpf-controls

当我ListBox使用水平项目创建时,例如:

<DockPanel>
    <ListBox>
        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <VirtualizingStackPanel Orientation="Horizontal" />
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
        <ListBoxItem>
            <Button Content="Hello" />
        </ListBoxItem>
        <ListBoxItem>
            <Button Content="Hello" />
        </ListBoxItem>
    </ListBox>
</DockPanel>
Run Code Online (Sandbox Code Playgroud)

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

图片显示差距

我怎么能摆脱这些差距呢?我需要ListBox彼此相邻的物品.我试图改变ItemTemplateListBox,但它并没有帮助.

Job*_*Joy 40

这是因为ListBoxItem的默认ItemContainerStyle中的填充.要删除它,您可以覆盖ItemContainerStyle.例如,只需在ListBox中尝试以下Empty ItemContainerStyle,就可以看到边距不再存在.

    <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>
Run Code Online (Sandbox Code Playgroud)

  • 这样做可以删除空间btw项目,但它完全删除了选择功能.我没有像上面接受的答案中那样触及ContentPresenter,而是通过将填充和边距都设置为0来解决我的问题.另外,我注意到只设置一个如下所示的某些内容是行不通的.所以,我只是做了<Setter Property ="Padding"Value ="0"/>;而不是改变上面的Template属性.<Setter Property ="Margin"Value ="0"/>.这删除了空间btw项目和我的选择仍然有效. (5认同)
  • 中断ListBox的选择处理。 (2认同)

H.B*_*.B. 28

这些差距是里面ControlTemplateListViewItems,你必须重写恐怕...

编辑:在某些平台上,你甚至不需要弄乱它Template来摆脱项目之间的差距:

    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="Padding" Value="0"/>
        </Style>
    </ListBox.ItemContainerStyle>
Run Code Online (Sandbox Code Playgroud)

为了摆脱最侧面的空白,你实际上需要更改ListBox ControlTemplate本身,这不是项目的问题.在默认的Aero模板中,有一个边框Padding = 1