gpt4 book ai didi

c# - WPF:ListView 中列表属性的总和

转载 作者:太空宇宙 更新时间:2023-11-03 13:17:51 25 4
gpt4 key购买 nike

我有一个对象列表,列表中的每个对象都包含第二个对象列表作为属性。我想在我的 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>

最佳答案

您可以使用值转换器:

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>

未经测试,但您明白了。

关于c# - WPF:ListView 中列表属性的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25453701/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com