开发者

Gaps between items in my ListBox

When I create ListBox with horizontal items ordering for example like this:

<DockPanel>
    <ListBox>
        <ListBox.I开发者_JS百科temsPanel>
            <ItemsPanelTemplate>
                <VirtualizingStackPanel Orientation="Horizontal" />
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
        <ListBoxItem>
            <Button Content="Hello" />
        </ListBoxItem>
        <ListBoxItem>
            <Button Content="Hello" />
        </ListBoxItem>
    </ListBox>
</DockPanel>

I have small gaps between buttons in the list as indicated by the arrows on following picture:

Gaps between items in my ListBox

How can I get rid of those gaps please ? I need to have items in ListBox just next to each other. I have tried changing ItemTemplate of the ListBox but it did not help.


This is because of the padding inside the default ItemContainerStyle for ListBoxItem. To remove this you can override the ItemContainerStyle. For example just try the below Empty ItemContainerStyle to your ListBox and you can see the margin is no more.

    <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>


Those gaps are inside the ControlTemplate of the ListViewItems, you'd have to override that i'm afraid...

Edit: On some platforms you do not even need to mess with the Template to get rid of the gaps between items:

    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="Padding" Value="0"/>
        </Style>
    </ListBox.ItemContainerStyle>

To get rid of the gap at the very side you actually need to change the ListBox ControlTemplate itself, it's not a matter of the items. In the default Aero template there is a border with Padding = 1

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜