65.9K
CodeProject 正在变化。 阅读更多。
Home

WPF ListView 中的空组

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.44/5 (5投票s)

2009年3月8日

CPOL
viewsIcon

56052

downloadIcon

1699

如何向 WPF ListView 控件添加空分组。

EmptyClusters.png

引言

WPF 具有 ListView 控件,该控件使用 CollectionView 类进行排序和分组。MSDN 提供了一个 示例,说明如何使用该类从项目列表中派生分组。但是,没有示例说明如何添加无法从项目列表中派生的空分组。

考虑一个示例场景 - 用户必须呈现服务器列表,按集群分组。可以使用 ListView 显示服务器(主要信息)并按集群分组(次要信息)。用户必须能够添加一个新集群来填充服务器。添加新集群后,由于没有服务器引用该新集群,因此它不会显示。

使用代码

可以使用 GroupDescription.GroupNames 属性添加分组。

using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Data;

namespace EmptyGroups
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();

            var clusters = new[]
            {
                new Cluster { Name = "Front end" },
                new Cluster { Name = "Middle end" },
                new Cluster { Name = "Back end" },
            };

            var collectionView = new ListCollectionView(new[]
            {
                new Server { Cluster = clusters[0], Name = "webshop1" },
                new Server { Cluster = clusters[0], Name = "webshop2" },
                new Server { Cluster = clusters[0], Name = "webshop3" },
                new Server { Cluster = clusters[0], Name = "webshop4" },
                new Server { Cluster = clusters[0], Name = "webshop5" },
                new Server { Cluster = clusters[0], Name = "webshop6" },
                new Server { Cluster = clusters[2], Name = "sql1" },
                new Server { Cluster = clusters[2], Name = "sql2" },
            });

            var groupDescription = new PropertyGroupDescription("Cluster.Name");

            // this foreach must at least add clusters that can't be
            // derived from items - i.e. groups with no items in them
            foreach (var cluster in clusters)
                groupDescription.GroupNames.Add(cluster.Name);

            collectionView.GroupDescriptions.Add(groupDescription);
            ServersList.ItemsSource = collectionView;
            Clusters = groupDescription.GroupNames;
        }

        readonly ObservableCollection<object> Clusters;

        void AddNewCluster_Click(object sender, RoutedEventArgs e)
        {
            Clusters.Add(NewClusterName.Text);
        }
    }

    class Cluster
    {
        public string Name { get; set; }
    }

    class Server
    {
        public Cluster Cluster { get; set; }
        public string Name { get; set; }
    }
}
© . All rights reserved.