How to bind a view to multiple ObservableCollection
I have a ModelView with multiple ObservableCollection. Is this correct and when ever a view call is viewed, the entire ObservableCollection needs to be repopulated with data and then the binding will be done again for the entire CollectionViewSource.
Also how do I call CollectionViewSource.GetDefaultView outside of the viewmodel constructor, I get an error that it can only call in the constructor.
If I create a separate ModelView for each of the CollectionViewSource, then when I bind one of the views with the ModelView, the rest of the controls will also bind with null values ββthis time, and all ModelViews will not be called.
I'm really confused about what to do, please help.
It looks like you are using MVVM. You can bind to multiple ObservableCollections. Actually the question is: do you need ? You must reserve the binding to ObserableCollections for cases when your ViewModel changes and you need to keep the updated View with the changes.
Here's an example I hacked into for you a View associated with two ObservableCollections and one List in the ViewModel. So - yes - you can get attached to whatever you want. In this example, two ObservableCollections will alternate updating. Does it help?
I've posted code for this here in case it helps get the whole project vs.
View:
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<StackPanel Orientation="Vertical">
<TextBlock>Bind to List:</TextBlock>
<ListView ItemsSource="{Binding Path=Users}" Height="20"/>
<TextBlock>Bind to ObservableCollection1:</TextBlock>
<ListView ItemsSource="{Binding Path=ObservableCollection1}"
Height="100"/>
<TextBlock>Bind to ObservableCollection2:</TextBlock>
<ListView ItemsSource="{Binding Path=ObservableCollection2}"
Height="100"/>
</StackPanel>
</Window>
ViewModel (the view is bound to this ViewModel)
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Timers;
using System.Windows;
using System.Windows.Threading;
namespace WpfApplication1
{
public class Class1
{
public List<string> Users{get;set;}
public ObservableCollection<string> ObservableCollection1 { get; set; }
public ObservableCollection<string> ObservableCollection2 { get; set; }
public Class1()
{
this.Users = new List<string>{ "bob", "mary" };
this.ObservableCollection1 = new ObservableCollection<string>();
this.ObservableCollection2 = new ObservableCollection<string>();
int counter = 0;
Timer t1 = new Timer();
t1.Enabled = true;
t1.Interval = 1000;
t1.Elapsed += delegate
{
Application.Current.Dispatcher.Invoke(
DispatcherPriority.Send, new Action(delegate
{
if(counter % 2 == 1)
this.ObservableCollection1.Add(DateTime.Now.ToString());
else
this.ObservableCollection2.Add(DateTime.Now.ToString());
++counter;
}));
};
}
}
}
a source to share