我有一个 ListView 控件绑定(bind)到 ListCollectionView
在 View 模型中。
我想尝试对这些项目进行分组,但遇到了一些问题。
我将 VM 中的属性分组设置为开头,然后添加了 GroupStyle
.
C#:
ListCollectionView.GroupDescriptions.Add(new PropertyGroupDescription("Category"));
XAML:
<ListView.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Name}"/>
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</ListView.GroupStyle>
但是列表现在只是类别名称,无法查看项目本身。
我并没有完全理解这里发生了什么。当我为
GroupStyle
创建模板时我真正绑定(bind)的是什么?除了Name
还有其他楼盘吗? ?我刚刚添加了
GroupStyle
到我已经创建的 ListView 中,例如包含 ItemTemplate
.是不是弄乱了 GroupStyle
?如果列表中的项目属于另一个类,我不想根据它们所属的类的实例进行分组(它有一个 ID)。然后,我会将组名作为该父类的属性。那可能吗?
部分解决方案:
问题出在 ListView 上应用的样式。我不知道这种风格是什么意思。
完整解决方案
我没有使用
ItemsPresenter
在我的列表框中ControlTemplate
选择使用带有 IsItemsHost
的面板设置为 true
.似乎必须使用 ItemsPresenter 才能使 GroupStyling 正常工作。
最佳答案
我认为错误在您的代码中的其他地方。
通常,您在 ViewModel 上公开一组模型
namespace Derp
{
public sealed class ViewModel
{
public ObservableCollection<Model> Items {get;set;}
// initialization code not shown
}
public sealed class Model
{
public string GroupName {get;set;}
public string ModelName {get;set;}
}
}
在您的 View 中,您绑定(bind)了 收藏查看源 到这个集合:
<Window.DataContext>
<ViewModel xmlns="clr-namespace:Derp" />
</Window.DataContext>
<Window.Resources>
<CollectionViewSource
Source="{Binding Items}"
x:Key="GroupedItems">
<CollectionViewSource.GroupDescriptions>
<PropertyGroupDescription
PropertyName="GroupName" />
</CollectionViewSource.GroupDescriptions>
</CollectionViewSource>
</Window.Resources>
接下来,我们将列表控件绑定(bind)到这个 收藏查看源 (在本例中使用组合):
<ComboBox
ItemsSource="{Binding Source={StaticResource GroupedItems}}"
DisplayMemberPath="ModelName">
<ComboBox.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<TextBlock
Text="{Binding Name}" />
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</ComboBox.GroupStyle>
</ComboBox>
令人困惑的地方在于,在 群风 ,您没有绑定(bind)您的模型,您绑定(bind)的是模型集合,该集合在(在这种情况下)属性“ GroupName ”上分组。 收藏查看源 将您的模型分组到扩展 CollectionViewGroup 的集合中.这些组有一个名为
Name
的属性。 ,其中包含模型分组的共同值(GroupName
属性的值)。所以,在 页眉模板 ,您正在绑定(bind)到 CollectionViewGroup.Name .
关于wpf - GroupStyles 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6110966/