C# 列表视图分组和选择
我有一个绑定到对象集合的ListView。根据用户的选择,对象按其属性分组 例如,我有水果的基本收藏(种类、数量、产地): 变成,按水果种类分组:C# 列表视图分组和选择,c#,wpf,C#,Wpf,我有一个绑定到对象集合的ListView。根据用户的选择,对象按其属性分组 例如,我有水果的基本收藏(种类、数量、产地): 变成,按水果种类分组: Banana Banana, 10, Africa Banana, 40, Africa Apple Apple, 2, France Pear Pear, 30, France 对于每个对象和组头,我在XAML中添加了一个复选框以供选择。通过组标题中的复选框,我想选择整个组。 对于上面的示例,如果我选中标题“B
Banana
Banana, 10, Africa
Banana, 40, Africa
Apple
Apple, 2, France
Pear
Pear, 30, France
对于每个对象和组头,我在XAML中添加了一个复选框以供选择。通过组标题中的复选框,我想选择整个组。
对于上面的示例,如果我选中标题“Banana”,则会选中同一组中下面的两行
这是我的ListView的XAML:
<ListView Name="MyCollectionView" ItemsSource="{Binding}" SelectionMode="Multiple">
<ListView.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox Name="SelectAllGroup" />
<TextBlock Text="{Binding Name}" Margin="10,0,0,0" />
</StackPanel>
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</ListView.GroupStyle>
<ListView.View>
<GridView>
<GridViewColumn Width="Auto" Header="Sélection" >
<GridViewColumn.CellTemplate>
<DataTemplate>
<CheckBox Margin="0" VerticalAlignment="Center" IsChecked="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListViewItem}}, Path=IsSelected}"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Width="Auto" Header="N°" DisplayMemberBinding="{Binding Path=Numero}"/>
<GridViewColumn Width="Auto" Header="Nom" DisplayMemberBinding="{Binding Path=Nom}" />
<GridViewColumn Width="Auto" Header="Responsable" DisplayMemberBinding="{Binding Path=Responsable}" />
<GridViewColumn Width="Auto" Header="Détail" DisplayMemberBinding="{Binding Path=Detail}" />
<GridViewColumn Width="Auto" Header="Calibre" DisplayMemberBinding="{Binding Path=Calibre}" />
</GridView>
</ListView.View>
</ListView>
我该怎么做
提前感谢。我做了一些非常类似的事情,在标题的复选框中添加了一个命令 然后在命令方法中,类似以下内容:
private void UpdateSelectedFruitGroup()
{
MyFruitCollection.Where(f => f.Variety == "Banana").ForEach(f => f.IsSelected = true);
}
为了完成ForEach,您需要将此扩展放入一个静态类中:
public static void ForEach<T>(this IEnumerable<T> enumerable, Action<T> action)
{
if (enumerable == null)
throw new ArgumentNullException("enumerable");
if (action == null)
throw new ArgumentNullException("action");
foreach (var e in enumerable)
{
action(e);
}
}
publicstaticvoidforeach(此IEnumerable可枚举,操作)
{
if(可枚举==null)
抛出新ArgumentNullException(“可枚举”);
if(action==null)
抛出新的异常(“操作”);
foreach(可枚举中的变量e)
{
行动(e);
}
}
基本上,它只是遍历集合中的每个项并对其执行操作。在本例中,它设置IsSelected属性。但我如何知道标题中的复选框是“香蕉”或其他任何内容?我想这取决于您如何设置组,当我这样做时,您必须先选择组,然后才能切换复选框,所以我所要做的就是将“香蕉”更改为所选组。嗯。。。不知道为什么,但我无法选择任何组。在我的列表视图中,我可以选择项目,但不能选择组
public static void ForEach<T>(this IEnumerable<T> enumerable, Action<T> action)
{
if (enumerable == null)
throw new ArgumentNullException("enumerable");
if (action == null)
throw new ArgumentNullException("action");
foreach (var e in enumerable)
{
action(e);
}
}