Bre*_*ent 9 wpf grouping listview mvvm listcollectionview
我正在使用MVVM设计模式创建一个WPF TimeCard应用程序,我正在尝试显示用户按天数分组的总和(总)小时数.我有一个ListView,使用以下XAML将所有TimeCard数据分组:
<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>
Run Code Online (Sandbox Code Playgroud)
这甚至可能吗?起初我以为我会创建一个CollectionViewGroup的部分类并添加我自己的属性.但我不确定这是否会奏效.也许有更好的解决方案......任何建议?
Nat*_*nAW 19
为了扩展e.tadeu所说的内容,您可以将HeaderTemplate的DataTemplate绑定到CollectionViewGroup的Items属性.这将返回当前组中的所有项目.
然后,您可以提供一个转换器,它将从该项集合中返回所需的数据.在你的情况下,你说你想要小时的总和.您可以实现一个类似于以下内容的转换器:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以在数据模板上使用此转换器:
<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>
Run Code Online (Sandbox Code Playgroud)
干杯!
| 归档时间: |
|
| 查看次数: |
9202 次 |
| 最近记录: |