【问题标题】:Change ItemsControl grouping dynamically动态更改 ItemsControl 分组
【发布时间】:2014-07-09 14:59:12
【问题描述】:

我在互联网上搜索动态更改 ItemsControl,但没有运气(也许我的查询不够好),所以我在这里问。任何人都可以帮助我为可以动态更改组类型的 ItemsControl 创建分组功能。 例如,我有一组具有以下属性的歌曲:名称、艺术家、歌手、专辑。然后我有 3 个单选按钮,其属性用于对那里的歌曲进行分组。 我曾考虑过创建多个 CollectionView,但我认为还有另一种更好的方法。 (我是WPF的新手,请您提供更详细的答案。谢谢:))

【问题讨论】:

  • 清除GroupDescriptionsICollectionView 集合并将新的GroupDescription 添加到该集合中。
  • 我不这么认为,这是您对ICollectionView 进行分组的方式,它在内部为您进行分组,我也不确定它在内部做什么,但它应该像可能的。通常(自己实现分组)分组确实是一项繁重的任务。
  • 非常感谢!请您重新发布您的评论作为答案,以便我接受吗?
  • 不,我其实什么都不做,只是一个基础知识。如果您关心性能,您可能想尝试创建3个不同的CollectionViews,每个视图按不同的属性分组,然后您只需将ItemsSource切换到相应的视图,也可以尝试添加更多线程的东西可能提高响应能力。
  • 感谢您的回复。我会努力的!

标签: wpf grouping itemscontrol


【解决方案1】:

这是我能想到的 MVVM 风格的最小示例。

视图模型:

enum GroupBy
{
    Name,
    Artist
}

class Song
{
    public string Name { get; set; }
    public string Artist { get; set; }
}

class SonglistViewModel : ViewModelBase
{
     private GroupBy groupBy;

     public GroupBy GroupBy
     {
          get => this.groupBy;
          set 
          {
               if(this.groupBy == value)
               {
                    return;
               }

               this.groupBy = value;
               this.UpdateGrouping(value);
               this.OnPropertyChanged(); 
          }
     }

     public ObservableCollection<Song> Songs { get; } = new ObservableCollection<Song>();

     private void UpdateGrouping(GroupBy value)
     {
        var servicesView = CollectionViewSource.GetDefaultView(this.Services);
        servicesView.GroupDescriptions.Clear();
        switch (value)
        {
            case GroupBy.Name:
                servicesView.GroupDescriptions.Add(
                    new PropertyGroupDescription(nameof(Song.Name)));
                break;

            case GroupBy.Artist:
                servicesView.GroupDescriptions.Add(
                    new PropertyGroupDescription(nameof(Song.Artist)));
                break;
        }
    }         
}

观点:

<ListView ItemsSource="{Binding Songs}">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}" />
            <GridViewColumn Header="Artist" DisplayMemberBinding="{Binding Artist}" />
        </GridView>
    </ListView.View>
    <ListView.GroupStyle>
         <GroupStyle>
             <GroupStyle.HeaderTemplate>
                  <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding Name}" />
                        <TextBlock Text="{Binding ItemCount, StringFormat={}({0})}" />
                    </StackPanel>
                </DataTemplate>
            </GroupStyle.HeaderTemplate>
        </GroupStyle>
    </ListViewGroupStyle>
</ListView>    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-10
    • 1970-01-01
    • 2018-03-06
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多