2011-07-07 31 views
1

我有對象的集合看起來像這樣綁定:WPF,沒有重複

List<MyObject> objects = new List<MyObject>(); 
objects.Add(new MyObject("Stapler", "Office")); 
objects.Add(new MyObject("Pen", "Office")); 
objects.Add(new MyObject("Mouse", "Computer")); 
objects.Add(new MyObject("Keyboard", "Computer")); 
objects.Add(new MyObject("CPU", "Computer")); 

class MyObject{ 

    public string name; 
    public string category; 

    public MyObject(string n, string c){ 
    name=n; 
    category=c; 
    } 

} 

能否在收集綁定到WPF列表,並將它顯示的對象的類別(不重複) ? (也許連同對象的計數這是該類別)

例如,我想在列表中只顯示兩個項目,「辦公室」,你可以做「計算機」

回答

1

使用CollectionViewSourcePropertyGroupDescription

在你Resources,添加以下內容:

<Window.Resources> 
    <CollectionViewSource x:Key="MyCollectionViewSource" Source="{Binding Path=CollectionPropertyOnViewModel}"> 
     <CollectionViewSource.GroupDescriptions> 
      <PropertyGroupDescription PropertyName="Category"/> 
     </CollectionViewSource.GroupDescriptions> 
    </CollectionViewSource> 
</Window.Resources> 

然後,您ItemsControl,設置ItemsSource{Binding Source={StaticResource MyCollectionViewSource}}

要設置標題模板的樣式,請設置ItemsControl.GroupStyle屬性。還要爲物品創建一個DataTemplate

從Bea Stollnitz here閱讀優秀的博客文章。

+0

很多人用'LINQ'回答這個問題。我覺得他們甚至沒有閱讀你的問題,只是讀到你不想重複。 – Dennis

0

任何宥想,那是WPF的美麗。

進行查詢恢復你想格式你想模型視圖層,並將結果結合到查看什麼。儘量使上你的PROGRAMM的最複雜的東西上模式層,並留下「虛」的東西到最後的結合,就像它可能很明顯,導致模型和模型視圖的東西會更容易調試修復錯誤未來

希望這會有所幫助。

1

你可以使用LINQ做到這一點,如:

public class AggregateCount 
{ 
    public string Name { get; private set; } 

    public int Count { get; private set; } 

    public AggregateCount(string name, int count) 
    { 
     this.Name = name; 
     this.Count = count; 
    } 
} 

var aggregateCounts = objects.GroupBy(o => o.category).Select(g => new AggregateCount(g.Key, g.Count())); 
ObservableCollection<AggregateCount> categoryCounts = new ObservableCollection<AggregateCount>(aggregateCounts); 
0

我會使用Linq:

List<MyObject> distinctObj = (from o in objects select o).Distinct().ToList(); 
0

如果你不想使用Linq:

private List<MyObject> objects = new List<MyObject>(); 
public ObservableCollection<String> Groups 
{ 
    get 
    { 
    ObservableCollection<String> temp = new ObservableCollection<String>(); 
    foreach (MyObject mo in objects) 
    { 
     if (!temp.Contains(mo.category)) 
     temp.Add(mo.category) 
    } 
    return temp; 
    } 
    set 
    { 
    objects = value; 
    RaisePropertyChanged("Groups"); 
    } 
}