5

我正在使用后端类中的 2 个列表。每个列表都是不同的类型。Would like to present the user with a single list (containing a union of both lists) of which when an item in this list is selected the item's details appear.

代码将类似于:

我的后端类看起来像这样

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>

有什么建议么?

4

3 回答 3

10

您可以为此使用CompositeCollection 。看看这个问题

于 2011-02-14T07:31:11.507 回答
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>

更新:

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

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);
  }
}

这只是一个例子。但是,如果您修改上述内容以满足您的需求,它可能会让您达到您的目标

于 2010-07-15T12:42:35.573 回答
0

我在这里找到了一篇博文,大部分时间都让我受益匪浅。我使用作者 AggregateCollection 和一个多值转换器来完成工作。

于 2010-07-14T20:58:13.110 回答