2010-07-14 38 views
4

我正在使用後端類中的2個列表。每個列表都是不同的類型。想要向用戶呈現單個列表(包含兩個列表的聯合),其中當該列表中的項目被選擇時,該項目的細節出現。WPF合併項目源列表

的代碼看起來是這樣的:

我的後端類看起來有些事情是這樣

public ObservableCollection<Person> People {get;} 
public ObservableCollection<Product> Products {get;} 

我的XAML看起來像這樣

<ListBox x:Name="TheListBox" ItemsSource={Some Expression to merge People and Products}> 
    <ListBox.Resources> 
     People and Product Data Templates 
    </ListBox.Resources> 
</ListBox> 
     ... 
<ContentControl Content={Binding ElementName=TheListBox, Path=SelectedItem }> 
    <ContentControl.Resources> 
     Data Templates for showing People and Product details 
    </ContentControl.Resources> 
</ContentControl> 

有什麼建議?

+0

我正在尋找類似的東西,我可以直接使用標記,並且不污染我的視圖模型界面。它應該基本上解決視圖模型提供的項目之間的不匹配問題,這可能是多個集合或幾個獨立的屬性,以及WPF所期望的,這是一個單一的枚舉。理想情況下,我甚至想直接在標記中添加項目,這甚至不對應於視圖模型中的任何內容,但合併到同一個列表中。 – Christo 2011-02-14 07:26:41

回答

0

我發現了一篇博客文章here,它讓我獲得了最多的感受。我使用作者AggregateCollection和多值轉換器來完成工作。

2

我不明白爲什麼你不只是在你的ViewModel揭露這樣一個屬性:

ObservableCollection<object> Items 
{ 
    get 
    { 
    var list = new ObservableCollection<object>(People); 
    list.Add(Product); 
    return list; 
    } 
} 

,然後在你的XAML你這樣做:

<ListBox x:Name="TheListBox" ItemsSource={Binding Items}> 
    <ListBox.Resources> 
     People and Product Data Templates 
    </ListBox.Resources> 
</ListBox> 
     ... 
<ContentControl Content={Binding ElementName=TheListBox, Path=SelectedItem }> 
    <ContentControl.Resources> 
     Data Templates for showing People and Product details 
    </ContentControl.Resources> 
</ContentControl> 

UPDATE :

如果您需要以不同方式操作模型,請執行以下操作:

ObservableCollection<object> _Items 
ObservableCollection<object> Items 
{ 
    get 
    { 
    if (_Items == null) 
    { 
     _Items = new ObservableCollection<object>(); 
     _Items.CollectionChanged += EventHandler(Changed); 
    } 
    return _Items; 
    } 
    set 
    { 
    _Items = value; 
    _Items.CollectionChanged += new CollectionChangedEventHandler(Changed); 
    } 
} 

void Changed(object sender,CollectionChangedEventArgs e) 
{ 
    foreach(var item in e.NewValues) 
    { 
    if (item is Person) 
     Persons.Add((Person)item); 
    else if (item is Product) 
     Products.Add((Product)item); 
    } 
} 

這只是一個例子。但是,如果您修改上述內容以滿足您的需求,則可能會使您達到目標

+0

我認爲這樣做的方式類似於你的建議。我的場景複雜的是我需要有一種方法來通過UI添加和刪除列表中的項目。 – Gus 2010-07-21 15:53:58

+0

檢查更新 – Jose 2010-07-21 16:53:13

8

您可以使用CompositeCollection來達到此目的。看看這個question

+1

輕鬆最佳選擇 – metao 2011-12-08 06:26:36

+0

以下是示例:https://msdn.microsoft.com/en-us/library/ms742405(v=vs.110).aspx – parfilko 2017-05-03 18:02:52