Taylor Drift
Taylor Drift

Reputation: 5

Updating a ObservableCollection with the Data of another ObservableCollection

I'm am currently working on a WPF/XAML project where i have the following problem:

I have a ObservableCollection which fetches it's data from a model as soon as the program starts and here is the deal.

How can i make another ObservableCollection which updates it's data on behalf of what you've chosen in the first ObservableCollection?

Upvotes: 0

Views: 315

Answers (2)

Maxim Kitsenko
Maxim Kitsenko

Reputation: 2333

  1. You should look into ObservableCollection events. MSDN
  2. it is not recommended to use ObservableCollection directly, a more straightforward way to use ObservableCollection capabilities from XAML in an application is to declare your own non-generic custom collection class that derives from ObservableCollection, and constrains it to a specific type
  3. Examples can be found here and here

Upvotes: 0

Peter
Peter

Reputation: 684

Subscribing to the CollectionChanged event and recreating the ObservableCollection should work:

public readonly ObservableCollection<string> Collection1 =
        new ObservableCollection<string>();

public readonly ObservableCollection<string> Collection2 =
        new ObservableCollection<string>();

public ViewModel() {
    Collection1.CollectionChanged += (sender, args) =>
    {
        Collection2.Clear();
        foreach (var x in Collection1) {
            Collection2.Add(x);
        }
    };
}

Upvotes: 1

Related Questions