我有2个集合要绑定到ListView中的单独GridViewColumn:
public class EffectView : INotifyPropertyChanged { ObservableCollection<Effect> effects; public ObservableCollection<Effect> Effects { get { return this.effects; } set { this.effects = value; this.RaisePropertyChanged ( "Effects" ); } } ObservableCollection<EffectDescription> descriptions; public ObservableCollection<EffectDescription> Descriptions { get { return this.descriptions; } set { this.descriptions = value; this.RaisePropertyChanged ( "Descriptions" ); } } }
我可以做这个:
<ListView ItemsSource="{Binding EffectView.Effects}"> <ListView.View> <GridView> <GridViewColumn Width="Auto" DisplayMemberBinding="{Binding Name}" Header="Name" /> <GridViewColumn Width="Auto" DisplayMemberBinding="{Binding Opacity}" Header="Opacity" /> <GridViewColumn Width="Auto" DisplayMemberBinding="{Binding ?}" Header="Description" /> </GridView> </ListView.View> </ListView>
但是后来所有内容都限定在EffectView.Effects中,但我希望默认范围是EffectView,这样我就可以轻松地将多个集合分配给ListView.
就像是:
<ListView ItemsSource="{Binding EffectView}"> <ListView.View> <GridView> <GridViewColumn Width="Auto" DisplayMemberBinding="{Binding Effects Path=Name}" Header="Name" /> <GridViewColumn Width="Auto" DisplayMemberBinding="{Binding Effects Path=Opacity}" Header="Opacity" /> <GridViewColumn Width="Auto" DisplayMemberBinding="{Binding Descriptions Path=Usage}" Header="Description" /> </GridView> </ListView.View> </ListView>
有没有办法实现这个目标?
解决方法
ListView的ItemsSource是其项目将出现在列表中的集合.那么想一想你要求ListView做什么:
>作为源集合,使用不是集合但包含它们的东西
>对于列表中的每一行,显示一个集合中的项目和另一个集合中的项目
注意第二点:每行必须显示Events集合中的一些项目和Descriptions集合中的一些项目.
从每个项目中选择哪个项目?这两个系列中的项目之间有什么关系?
看来你真正需要的是一个包含Event和Description的对象集合.然后,您可以绑定到该集合以显示两个实体的元素.粗略地,这样的事情:
public class EffectView : INotifyPropertyChanged { ObservableCollection<EffectsAndDescriptions> effects; public ObservableCollection<EffectAndDescriptions> Effects { get { return this.effects; } set { this.effects = value; this.RaisePropertyChanged ( "EffectsAndDescriptions" ); } } } internal class EffectsAndDescriptions { public Effect Effect { get; set; } public Description Description { get; set; } }
现在您可以绑定到EffectsAndDescriptions集合(请注意,这假设ListView的父级的DataContext是EffectView)
<ListView ItemsSource="{Binding EffectsAndDescriptions}"> <ListView.View> <GridView> <GridViewColumn Width="Auto" DisplayMemberBinding="{Binding Effect.Name}" Header="Name" /> <GridViewColumn Width="Auto" DisplayMemberBinding="{Binding Effect.Opacity}" Header="Opacity" /> <GridViewColumn Width="Auto" DisplayMemberBinding="{Binding Description.Usage}" Header="Description" /> </GridView> </ListView.View> </ListView>