groupedview的可能性更简单
本文关键字:更简单 可能性 groupedview | 更新日期: 2023-09-27 18:14:14
我有一个问题。我想写一个Windows 8应用程序,并认为一个分组GridView,就像在Visual Studio中包含的样例分组项应用程序模板,将是一个很好的选择数据表示。但是我在理解这是如何工作的问题(我设法修改了包含的SampleDataSource
,以便显示我的内容)。我的问题是,有很多元素,我不能确定哪个元素导致了什么。
我的问题是:
谁能解释(或提供一个链接)我如何能从头开始构建这样一个分组GridView ?示例模板并没有那么有用,因为它有点令人困惑(一个文件中有4个类,有时结构有点奇怪)。
使用分组GridView的基本要求是:
(注意:所有类名都是任意的)
- 一个ViewModel(你正在使用Mvvm,对吗?)
- Group对象,用于保存每个组的元素。
- 一个Item对象,组将包含 的集合
- 一个显示项目的视图,包括GridView和CollectionViewSource(包括Groups和items的任何样式)
一个示例组和Item:
public class Group<T> where T : Item
{
public ObservableCollection<T> Items { get; set;}
public string Title { get; set; }
}
public class Item
{
public string Value { get; set; }
}
示例ViewModel:
public class GroupsViewModel : ViewModelBase // This implementation uses Mvvm Light's ViewModelBase, feel free to use any
{
public ObservableCollection<Group<Item>> AllGroups { get; set; }
public GroupsViewModel()
{
AllGroups = new ObservableCollection<Group<Item>>();
Group<Item> group1 = new Group<Item>();
group1.Title = "Group 1 Title";
group1.Add(new Item(){ Value = "The first value." });
AllGroups.Add(group1);
Group<Item> group2 = new Group<Item>();
group2.Title = "Group 2 Title";
group2.Add(new Item(){ Value = "The second value." });
}
}
在你的页面上,创建一个CollectionViewSource。资源:
<Page.Resources>
<CollectionViewSource Source="{Binding AllGroups}"
IsSourceGrouped=True
ItemsPath="Items"
x:Name="GroupedCollection"/>
</Page.Resources>
注意,Source被绑定到Group
s的Collection
,并且ItemsPath
告诉CollectionViewSource
,每个Group
中Item
s的集合在该属性上。
您的GridView
将引用此。像下面这样设置项目源是很重要的。一个空的{Binding}
, Source
设置为CollectionViewSource
的StaticResource
。您可以使用GroupStyle
样式GridView
中的每个组,就像这样。我把它简化成非常基本的。您已经拥有的默认示例将有一个更好的示例。
<GridView ItemsSource="{Binding Source={StaticResource GroupedCollection}}"
ItemTemplate="{StaticResource Standard250x250ItemTemplate}"
>
<GridView.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</GridView.ItemsPanel>
<GridView.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<Grid Margin="1,0,0,6">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Title}" Margin="3,-7,10,10" Style="{StaticResource GroupHeaderTextStyle}" />
<TextBlock Text="{StaticResource ChevronGlyph}" FontFamily="Segoe UI Symbol" Margin="0,-7,0,10" Style="{StaticResource GroupHeaderTextStyle}"/>
</StackPanel>
</Grid>
</DataTemplate>
</GroupStyle.HeaderTemplate>
<GroupStyle.Panel>
<ItemsPanelTemplate>
<VariableSizedWrapGrid Orientation="Vertical" Margin="0,0,80,0"/>
</ItemsPanelTemplate>
</GroupStyle.Panel>
</GroupStyle>
</GridView.GroupStyle>
</GridView>
最后,您必须将Page
的DataContext
设置为ViewModel
。如果你使用Mvvm Light,它将是DataContext="{Binding GroupsVM, Source={StaticResource Locator}}"
之类的东西。显然,你需要做一些进一步的设置才能使它工作。您也可以在Page
构造函数中设置它。
public MyGridViewPage()
{
DataContext = new GroupsViewModel();
this.InitializeComponent();
}
希望这对你有帮助。编码快乐!