Dot-Net

我的 ListBox 中的項目之間的差距

  • January 16, 2011

當我ListBox使用水平項目排序創建時,例如:

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

我在列表中的按鈕之間有小間隙,如下圖的箭頭所示:

顯示間隙的圖片

請問我怎樣才能擺脫這些差距?我需要將物品放在ListBox彼此旁邊。我試過改變ItemTemplateListBox但沒有幫助。

這是因為 ListBoxItem 的預設 ItemContainerStyle 內的填充。要刪除它,您可以覆蓋 ItemContainerStyle。例如,只需將下面的 Empty 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>

引用自:https://stackoverflow.com/questions/4704009