我试图通过将嵌套的Collection绑定到ListBox来说服ListBox显示分组的项目。我已经让它显示组标题,但项目没有显示。我模糊地试图跟随this tutorial,特别是第二部分,“使用数据源,其中每个项目包含一个子项集合”,但我并没有真正得到他们的方法(我可以理解两个CollectionViewSources,包含绑定到GridView的组的那个是有意义的,但是另一个(组中的项)绑定到没有名称的ListView,似乎没有在任何地方使用......什么?)。我试图以最小的方式做到这一点(没有花哨的造型和groupheaderselectors,我可以稍后添加,现在我只需要显示项目),到目前为止,我是不成功的。
我知道这是一个配方不合理的问题,但我仍然在努力应对所有的WPF概念,所以我无法提出更好的要求。下面是我当前的代码,显示组,但不是他们的项目,任何人都可以帮助和解释为什么它不起作用,并显示如何修改它,所以它的工作原理?我需要它来使用嵌套集合方法,我需要它尽可能简单,谢谢。
MainPage.xaml中:
<Page
x:Class="Bulsitpokusy.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Bulsitpokusy"
xmlns:dt="using:Bulsitpokusy.Data"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006">
<Page.DataContext>
<dt:MpViewmodel></dt:MpViewmodel>
</Page.DataContext>
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<ListBox ItemsSource="{Binding ListItemsView.View}">
<ListBox.GroupStyle>
<GroupStyle HidesIfEmpty="False">
<GroupStyle.ContainerStyle>
<Style TargetType="GroupItem">
<Setter Property="MinWidth" Value="600"/>
<Setter Property="BorderBrush" Value="DarkGray"/>
<Setter Property="BorderThickness" Value="2"/>
<Setter Property="Margin" Value="3,0"/>
</Style>
</GroupStyle.ContainerStyle>
<GroupStyle.Panel>
<ItemsPanelTemplate>
<VariableSizedWrapGrid/>
</ItemsPanelTemplate>
</GroupStyle.Panel>
</GroupStyle>
</ListBox.GroupStyle>
</ListBox>
</Grid>
</Page>
MpViewmodel.cs:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml.Data;
namespace Bulsitpokusy.Data
{
public class MpGroup
{
public string Title;
public ObservableCollection<string> ChildItems;
public override string ToString()
{
return Title;
}
}
public class MpViewmodel : INotifyPropertyChanged
{
private ObservableCollection<MpGroup> listItems = new ObservableCollection<MpGroup>()
{
new MpGroup(){Title="Grupa 1", ChildItems=new ObservableCollection<string>{
"G1.I1", "G1.I2", "G1.I3"
}},
new MpGroup(){Title="Grupa 2", ChildItems=new ObservableCollection<string>{
"G2.I1", "G2.I2", "G2.I3"
}}
};
public CollectionViewSource ListItemsView
{
get;
set;
}
public MpViewmodel()
{
ListItemsView = new CollectionViewSource() { Source = listItems, IsSourceGrouped=true, ItemsPath=new Windows.UI.Xaml.PropertyPath("ChildItems") };
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
其他所有内容都是默认的 - 由“Windows应用商店 - &gt;空白应用(XAML)”模板生成。 感谢您提供任何有用的建议。
答案 0 :(得分:0)
您不使用grouping。你要做的是显示子项目,为此你需要用ItemTemplate
创建ItemsControl
,这将显示你的子项目,默认情况下它只会调用{{1} }在每个项目上显示
ToString()
还会将字段更改为属性,因为您无法绑定到字段:
<ListBox>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Title}"/>
<ItemsControl ItemsSource="{Binding ChildItems}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>