2012-10-10 39 views
2

我有一個WPF ListBox與幾個標題。我來達到的這個通過具有GroupStyle我在其中定義的每個報頭的外觀:刪除WPF ListBoxItem的左填充與爲其ListBox定義的GroupStyle

<ListBox DataContext="{StaticResource MyGroups}" ItemsSource="{Binding}"> 
    <ListBox.GroupStyle> 
     <GroupStyle> 
      <GroupStyle.HeaderTemplate> 
       <DataTemplate> 
        <!-- my header stuff --> 
       </DataTemplate> 
      </GroupStyle.HeaderTemplate> 
     </GroupStyle> 
    </ListBox.GroupStyle> 

    <!-- ListBox.ItemTemplate.. not shown --> 
</ListBox> 

不知何故,這將導致個體ListBoxItems稍微「縮進」各自的報頭下(卸下GroupStyle去除壓痕,沿着儘管所有的標題)。

我看到他們爲什麼會希望他們默認縮進,但有無論如何刪除那個小左填充?我試圖爲ListBoxItem定義一個樣式來設置Padding = 0,但結果是一樣的。

+0

你可以在GroupStyle中設置填充嗎? – Jay

+0

嗯我沒有看到在GroupStyle中設置填充的好地方。我嘗試在GroupStyle.ContainerStyle中設置樣式(使用TargetType = ListBoxItem和Padding = 0),但顯然導致崩潰。 –

+0

您可以在資源中設置GroupStyle,然後在控件中設置縮進? IIRC控制級別屬性定義應始終覆蓋資源級別。 – Jay

回答

4

我可以刪除縮進的唯一途徑是介紹我自己的控制模板GroupItemGroupStyle.ContainerStyle。該模板由兩個網格行組成,其中1個用於標題,1個用於組項目。

<ListBox.GroupStyle> 
    <GroupStyle> 
     <GroupStyle.ContainerStyle> 
      <Style TargetType="GroupItem"> 
       <Setter Property="Template"> 
        <Setter.Value> 
         <ControlTemplate TargetType="GroupItem"> 
          <Grid> 
           <Grid.RowDefinitions> 
            <RowDefinition/> 
            <RowDefinition/> 
           </Grid.RowDefinitions> 

           <TextBlock Grid.Row="0" Text="{Binding MyHeaderText}"/> 
           <ItemsPresenter Grid.Row="1"/> 
          </Grid> 
         </ControlTemplat> 
        </Setter.Value> 
       </Setter> 
      </Style> 
     </GroupStyle.ContainerStyle> 
    </GroupStyle> 
</ListBox.GroupStyle> 
1

放置在-20的左邊距然後在(+)20列表框項目。這些都會影響結果嗎?

如果根據需要調整到合適的尺寸。

1

謝謝你的回答,kentoh!只是想補充一點,如果你需要在一個組頭顯示自定義模板,那麼你可能想使用這樣的事:

<ControlTemplate TargetType="GroupItem"> 
    <StackPanel> 
     <ContentPresenter 
      Content="{TemplateBinding Content}" 
      ContentTemplate="{TemplateBinding ContentTemplate}" 
     /> 
     <ItemsPresenter /> 
    </StackPanel> 
</ControlTemplate> 
+0

你也可以在模板中放一個空的'',事情就會自動得到連接。就像你使用''一樣。 – Grx70

0

我取得了一些成功否定ItemsPresenter邊距:

<ListBox> 
... 
    <ListBox.Resources> 
    <Style TargetType="{x:Type ListBoxItem}"> 
     <Setter Property="Margin" Value="-5,0,0,0"></Setter> 
    </Style> 
    </ListBox.Resources> 
</ListBox> 

但它不完全是優雅的。