2010-02-06 51 views
9

我正在使用MVVM設計模式創建WPF TimeCard應用程序,並且我試圖顯示用戶按每天分組計時的總和(總)小時數。我有一個列表視圖與所有的TimeCard數據分解成使用以下XAML組:在ListView中顯示分組項目的總和

<ListView.GroupStyle> 
    <GroupStyle ContainerStyle="{StaticResource GroupItemStyle}"> 
     <GroupStyle.HeaderTemplate> 
      <DataTemplate> 
       <StackPanel Orientation="Horizontal"> 
        <TextBlock Text="{Binding Path=Name, StringFormat=\{0:D\}}" FontWeight="Bold"/> 
        <TextBlock Text=" (" FontWeight="Bold"/> 
        <!-- This needs to display the sum of the hours --> 
        <TextBlock Text="{Binding ???}" FontWeight="Bold"/> 
        <TextBlock Text=" hours)" FontWeight="Bold"/> 
       </StackPanel> 
      </DataTemplate> 
     </GroupStyle.HeaderTemplate> 
    </GroupStyle> 
</ListView.GroupStyle> 

這甚至可能嗎?起初我以爲我會創建一個CollectionViewGroup的部分類並添加我自己的屬性。但我不確定這將會起作用。也許有更好的解決方案...有什麼建議嗎?

回答

17

要展開什麼e.tadeu說,你可以綁定你HeaderTemplate中的DataTemplate中來的物品屬性CollectionViewGroup。這會返回當前組中所有的項目。

然後,您可以提供一個轉換器,它將從該項目集合中返回所需的數據。在你的情況下,你說你想要的時間總和。你可以實現一個轉換器,做喜歡的事:

public class GroupHoursConverter : IValueConverter 
{ 

    public object Convert(object value, System.Type targetType, 
          object parameter, 
          System.Globalization.CultureInfo culture) 
    { 
     if (null == value) 
      return "null"; 

     ReadOnlyObservableCollection<object> items = 
       (ReadOnlyObservableCollection<object>)value; 

     var hours = (from i in items 
        select ((TimeCard)i).Hours).Sum(); 

     return "Total Hours: " + hours.ToString(); 
    } 

    public object ConvertBack(object value, System.Type targetType, 
           object parameter, 
           System.Globalization.CultureInfo culture) 
    { 
     throw new System.NotImplementedException(); 
    } 
} 

然後,你可以使用此轉換您的數據模板:

<Window.Resources> 
     <local:GroupHoursConverter x:Key="myConverter" /> 
    </Window.Resources> 

    <ListView.GroupStyle> 
     <GroupStyle ContainerStyle="{StaticResource GroupItemStyle}"> 
      <GroupStyle.HeaderTemplate> 
       <DataTemplate> 
        <StackPanel Orientation="Horizontal"> 
         <TextBlock Text="{Binding Path=Name, 
                StringFormat=\{0:D\}}" 
            FontWeight="Bold"/> 
         <TextBlock Text=" (" FontWeight="Bold"/> 
         <!-- This needs to display the sum of the hours --> 
         <TextBlock Text="{Binding Path=Items, 
             Converter={StaticResource myConverter}}" 
            FontWeight="Bold"/> 
         <TextBlock Text=" hours)" FontWeight="Bold"/> 
        </StackPanel> 
       </DataTemplate> 
      </GroupStyle.HeaderTemplate> 
     </GroupStyle> 
    </ListView.GroupStyle> 

乾杯!

+0

謝謝!我總是會忘記你可以用ValueConverters做的所有事情。感謝您的示例代碼。 – Brent 2010-02-12 04:36:53

+0

如果值改變,這將不起作用。 – 2011-08-10 19:15:46