我有一个对象列表,列表中的每个对象都包含第二个对象列表作为属性。我想在ListView的第二个列表中显示属性的总和。这就是我现在所拥有的。
<ListView ItemsSource="{Binding AllLineItems}" SelectedItem="{Binding CurrentLineItem}">
<ListView.View>
<GridView>
<GridViewColumn DisplayMemberBinding="{Binding LineItem}" Header="Line Item" />
<GridViewColumn DisplayMemberBinding="{Binding Description}" Header="Description" />
<GridViewColumn Header="Quantity">
<GridViewColumn.CellTemplate>
<DataTemplate>
<!-- I do not want to display a ComboBox I would like -->
<!-- to display the total of the Quantity property. -->
<ComboBox ItemsSource="{Binding ShippingHistories}" DisplayMemberPath="Quantity" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
答案 0 :(得分:1)
您可以使用值转换器:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Data;
namespace WpfApplication1
{
public class SumConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
IEnumerable enumerable = value as IEnumerable;
if (enumerable == null)
{
return DependencyProperty.UnsetValue;
}
IEnumerable<object> collection = enumerable.Cast<object>();
PropertyInfo property = null;
string propertyName = parameter as string;
if (propertyName != null && collection.Any())
{
property = collection.First().GetType().GetProperty(propertyName);
}
return collection.Select(x => System.Convert.ToInt32(property != null ? property.GetValue(x) : x)).Sum();
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
然后在你的XAML中:
xmlns:local="clr-namespace:WpfApplication1"
...
<Window.Resources>
<local:SumConverter x:Key="sumConverter"></local:SumConverter>
</Window.Resources>
...
<GridViewColumn Header="Quantity">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding ShippingHistories,Converter={StaticResource sumConverter},ConverterParameter=Quantity}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
未经测试,但您明白了。