Dot-Net

帶邊距的分組 WPF ListView 樣式問題

  • August 12, 2014

在 WPF 中使用 ListView的分組功能時,樣式左側有一個很小的邊距。

具有分組問題(邊距)的 ListView 範例:

ListView,按名稱分組

沒有分組的 ListView 範例(希望分組列表中的項目樣式相同):

ListView,不分組

問題:

如何刪除邊距/填充?分組列表中的(選定)項目應填充與未分組列表中相同的空間。

更新:

           <ListView Margin="20,0,0,0" ItemsSource="{Binding ItemsView}" SelectedItem="{Binding SelectedItem}" IsSynchronizedWithCurrentItem="True"  SelectionMode="Single" BorderThickness="0" Background="Transparent">
               <ListView.GroupStyle>
                   <GroupStyle>
                       <GroupStyle.HeaderTemplate>
                           <DataTemplate DataType="data:Item">
                               <DockPanel HorizontalAlignment="Stretch">
                                   <TextBlock Text="{Binding Name}" FontWeight="Bold" Margin="0,5,5,5" />
                                   <Separator  />
                               </DockPanel>
                           </DataTemplate>
                       </GroupStyle.HeaderTemplate>
                   </GroupStyle>
               </ListView.GroupStyle>
               <ListView.ItemTemplate>
                   <DataTemplate DataType="data:Item">
                       <TextBlock Margin="10,10,10,10" Text="{Binding Name}" />
                   </DataTemplate>
               </ListView.ItemTemplate>
           </ListView>

當在 CollectionViewSource 中使用分組時(我假設您正在使用一個),Groups 將由 GroupItem 視覺化。GroupItem 的預設樣式如下所示(通過 StyleSnooper 獲得):

<Style TargetType="{x:Type GroupItem}" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
   <Setter Property="Control.Template">
       <Setter.Value>
           <ControlTemplate TargetType="{x:Type GroupItem}">
               <StackPanel>
                   <ContentPresenter Content="{TemplateBinding ContentControl.Content}" ContentTemplate="{TemplateBinding ContentControl.ContentTemplate}" ContentStringFormat="{TemplateBinding ContentControl.ContentStringFormat}" />
                   <ItemsPresenter Margin="5,0,0,0" />
               </StackPanel>
           </ControlTemplate>
       </Setter.Value>
   </Setter>
</Style>

如您所見,ItemsPresenter 上有一個 Margin。一種解決方案是為 GroupItem 創建自己的樣式,並刪除 ItemsPresenter 上的 Margin,並將 GroupStyle.ContainerStyle 設置為使用此樣式。

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