WPF listview,如何获得项目总和

时间:2015-04-13 17:29:24

标签: c# wpf listview collectionviewsource

我定义了以下列表视图(其项目源是具有AccountName和AccountBalance属性的帐户集合):

<ListView x:Name="AccountList1" ItemsSource="{Binding Source={StaticResource GroupedAccounts}}" SelectedItem="{Binding SelectedAccount, Mode=TwoWay}" Margin="10" 
              IsSynchronizedWithCurrentItem="True" Background="LightGray">
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="AccountName"   Width="100">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <TextBlock>
                                <Hyperlink Command="{Binding DataContext.Navigate}" CommandParameter="{Binding}">
                                    <TextBlock Text="{Binding AccountName}" />
                                </Hyperlink>
                            </TextBlock>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                    <GridViewColumn Header="Balance" DisplayMemberBinding="{Binding AccountBalance}"/>
                </GridView>

            </ListView.View>

和此集合视图按类型对帐户进行分组:

  <CollectionViewSource Source="{Binding AccountList}" x:Key="GroupedAccounts" >
        <CollectionViewSource.GroupDescriptions>
            <PropertyGroupDescription PropertyName="AccountType" />
        </CollectionViewSource.GroupDescriptions>
    </CollectionViewSource>

我想显示帐户的总和: - 所有帐户的总和作为列表视图的最后一项。 - 每组账户的总和。

这样的事情:

BankAccounts

Account1 500 $

Account2 150 $


总计650美元

CashAccounts

Account3 0 $

Account4 1000 $


总计1000美元


AllTotal 1650 $

1 个答案:

答案 0 :(得分:1)

因此,有几种方法可以解决这种情况。您可以让ViewModel处理计算并将其推送到您的视图或在模型中拥有总属性。我不知道你正在使用的模式,所以我不会猜。话虽如此,有一种更可重复使用的方法,可以使用聚合转换器,例如:#/ p>

public class SumConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, 
                          System.Globalization.CultureInfo culture)
    {
        double sum = 0.0;
        Type valueType = value.GetType();

        if(valueType.Name == typeof(List<>).Name)
        {
            foreach (var item in (IList)value)
            {
                Type itemType = item.GetType();                     
                PropertyInfo itemPropertyInfo = itemType.GetProperty((string)parameter);
                double itemValue = (double)itemPropertyInfo.GetValue(item, null); 
                sum += itemValue;
            }
            return sum;
        }
        return 0.0;
    }
    public object ConvertBack(object value, Type targetType, object parameter, 
                              System.Globalization.CultureInfo culture)
    { throw new NotImplementedException();  }
}

这是基于这篇文章:

http://www.codeproject.com/Articles/28006/Using-converters-to-aggregate-a-list-in-a-ListView

它没有经过测试,但它应该足以让你入门。