2012-01-20 73 views
0

以下是我目前用於在listview中分組的代碼。我可以對記錄進行分組,但是當用戶單擊button(AddNewCluster)以創建具有記錄集的新組時,我無法與舊記錄連接。 listview獲得新組和記錄的更新。但我需要向用戶顯示新添加的組和記錄。分組列表視圖

ListCollectionView collectionView; 

public Window1() 
{ 
    InitializeComponent(); 

    var clusters = new[] 
    { 
     new Cluster { Name = "Front end" }, 
     new Cluster { Name = "Middle end" }, 
     new Cluster { Name = "Back end" }, 
    };  
    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; 

這裏是AddNewCluster_Click方法:

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

    var clusters = new[] 
    { 
     new Cluster { Name = NewClusterName.Text }, 
    }; 

    collectionView = new ListCollectionView(new[] 
    { 
     new Server { Name = "new server data" }, 
    }); 

    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; 

} 

回答

1

這是一個有點難以閱讀的代碼,但據我可以做出來,你要創建一個新的集合圖,具有全新的集合,而不是將新項目添加到舊集合中。

您應該將新項目添加到舊集合並調用CollectionView.Refresh()。

+0

感謝您的回答!會嘗試你的步驟,但解決了我的自我感謝! – karthikdavanam