2011-09-06 23 views
0

我有一個ListView綁定到一些數據,它被分組和排序。我添加了一個複選框向分組報頭,像這樣:分組列表視圖與複選框在標題

  <ListView.GroupStyle> 
      <GroupStyle> 
       <GroupStyle.ContainerStyle> 
        <Style TargetType="{x:Type GroupItem}"> 
         <Setter Property="Margin" Value="0,0,0,5"/> 
         <Setter Property="Template"> 
          <Setter.Value> 
           <ControlTemplate TargetType="{x:Type GroupItem}"> 
            <Expander IsExpanded="True" BorderBrush="#FFA4B97F" BorderThickness="0,0,0,1"> 
             <Expander.Header> 
              <DockPanel> 
               <CheckBox> 
                <StackPanel Orientation="Horizontal"> 
                 <TextBlock FontWeight="Bold" Text="{Binding Path=Name}" Margin="5,0,0,0"/> 
                 <TextBlock Text=" ("/> 
                 <TextBlock Text="{Binding Path=ItemCount}"/> 
                 <TextBlock Text=" Items)"/> 
                </StackPanel> 
               </CheckBox> 
              </DockPanel> 
             </Expander.Header> 
             <Expander.Content> 
              <ItemsPresenter /> 
             </Expander.Content> 
            </Expander> 
           </ControlTemplate> 
          </Setter.Value> 
         </Setter> 
        </Style> 
       </GroupStyle.ContainerStyle> 
      </GroupStyle> 
     </ListView.GroupStyle> 

現在我只關心並需要通過有頭檢查分組的項目的方式來循環,什麼是完成這一任務的最好方法是什麼?

回答

1

可悲的是它不是那麼簡單,因爲它需要,

請記住,一個組的頭CheckBoxDataContext這是一個特殊的對象稱爲GroupItem。在這個GroupItem中有Name屬性,它是該組所表示的值,即基於哪個分組發生的共同值。

很多人將此與組描述屬性混淆,例如假設你已經在你的員工CollectionView添加屬性EmployeeStatus一個GroupDescription,然後GroupItem.Name不是EmployeeStatus,但它實際上是在哪一組創建如PresentAbsentOnLeave

有這方面的知識,讓價值努力實現你追求什麼......

  1. 我們命名頭複選框,說 「HeaderCheckBox」

    <CheckBox x:Name="HeaderCheckBox" ...> 
    
  2. 我們在ListView級別處理Button.Click(冒泡附加事件)。

    <ListView Button.Click="HandleCheckBoxClick" ...> 
    
  3. 在處理程序HandleButtonClick我們做下面的代碼....

    private void HandleCheckBoxClick(object sender, RoutedEventArgs e) 
    { 
        var checkBox = e.OriginalSource as CheckBox; 
        if (checkBox != null && checkBox.Name == "HeaderCheckBox") 
        { 
         var groupItem = checkBox.DataContext as GroupItem; 
    
         //// Assuming MyItem is the item level class and MyGroupedProperty 
         //// is the grouped property that you have added to the grouped 
         //// description in your CollectionView. 
         foreach (MyItem item in groupItem.Items) 
         { 
          //// Place your code for the items under that particular group. 
         } 
        } 
    } 
    

可悲的是,這是實現你所追求的唯一途徑。如果您使用的是MVVM,那麼整個代碼將不得不通過附加的行爲來完成。

讓我知道這是否有幫助。

+0

是的,謝謝你,我可以把它變成一個可行的解決方案。然而,我真的只是在列表填充之後尋找一種方法來獲取包含選項框複選框的組列表。相反,不管使用你的代碼,我只需要一個帶有複選框的不可見列作爲正在顯示的類的成員,並根據哪個組已被選中來控制複選框,然後很容易找到哪些項目被檢查,哪些不是。再次感謝你! – acat13

+0

你可以得到所有組,我認爲'ListView'暴露了'Items'屬性...我想這應該有個別組....這是一個新人猜測,它可能不會贏得你的德比。 :-) –

+1

在.NET 4中,它不是GroupItem,而是CollectionViewGroup – SACO