代码之家  ›  专栏  ›  技术社区  ›  Gus

WPF合并项资源列表

  •  4
  • Gus  · 技术社区  · 15 年前

    我在后台类中使用2个列表。每个列表都是不同的类型。希望向用户显示一个列表(包含两个列表的并集),当选中此列表中的某个项目时,将显示该项目的详细信息。

    我的后端类看起来像这样

    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>
    

    有什么建议吗?

    3 回复  |  直到 15 年前
        1
  •  8
  •   Community Mohan Dere    9 年前

    你可以使用 CompositeCollection 为了这个。看看这个 question

        2
  •  2
  •   Jose    15 年前

    我不明白为什么不在ViewModel中公开这样的属性:

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

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

    这只是一个例子。但是如果你修改上面的内容来满足你的需要,它可能会让你达到你的目标

        3
  •  0
  •   Gus    15 年前

    我找到一篇博文 here

    推荐文章