WPF Merge ItemsSource Lists

I work with 2 lists in a base class. Each list is a different type. I would like to present the user with one list (containing the union of both lists), of which when an item is selected, the item data is displayed in this list.

The code will look something like this:

My base class looks something like this:

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

My xaml looks something like this

 <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> 

Any suggestions?

+4
source share
3 answers

I found a blog entry here that delivered me most of the way. I used the authors of AggregateCollection along with a multicurrency converter to get the job done.

0
source

You can use CompositeCollection for this . Look at the question .

+8
source

I do not understand why you are not just opening such a property in your ViewModel:

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

and then in your xaml you do the following:

 <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:

If you need to manipulate your model differently, follow these steps:

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

This is just an example. But if you modify the above to suit your needs, this may lead to your goal.

+2
source

Source: https://habr.com/ru/post/1315696/


All Articles