Rolodium
Rolodium

Reputation: 343

Wpf Multiple listview's bound to the same collection with different sort descriptions

I have an application that allows the user to create multiple instances of the same user control that contains a listview which is bound to an ObservableCollection of a custom data type. Upon the user clicking the header I have the listview sorting correctly however it sorts all the views bound to the ObservableCollection.

My question is, is there any way to implement sorting on the view separate of the ObservableCollection, or is there another way to clone the contents of the ObservableCollection (Note: The ObservableCollection is constantly being added to by a service in the background which must be displayed in real-time).

I am sorting the collection as follows:

ICollectionView dataView = CollectionViewSource.GetDefaultView(sourceList.ItemsSource);
dataView.SortDescriptions.Clear();
SortDescription sd = new SortDescription(sortBy, direction);
dataView.SortDescriptions.Add(sd);

My list view's item source is set as follows:

myListView.ItemsSource = ServiceManager.Instance.ActiveObjects; 

I would prefer not maintaining multiple instances of the same ObservableCollection. It is a requirement that the user be capable of having multiple instances of this user control so unfortunately I cannot get around this the easy way and limit them to a single instance.

Any help on this would be much appreciated, Thanks in advance.

Upvotes: 5

Views: 1153

Answers (1)

Sheridan
Sheridan

Reputation: 69979

Your mistake is setting the ItemsSource property directly to the ServiceManager.Instance.ActiveObjects property:

myListView.ItemsSource = ServiceManager.Instance.ActiveObjects; 

Instead, you should create a separate ICollectionView instance from the data collection for each ListView. This example was adapted from the page linked below:

private ICollectionView _customerView;

public ICollectionView Customers
{
    get { return _customerView; }
}

public CustomerViewModel()
{
    IList<YourClass> customers = ServiceManager.Instance.ActiveObjects;
    _customerView = CollectionViewSource.GetDefaultView(customers);
}

...

<ListBox ItemsSource="{Binding Customers}" />

You can find out further details from the How to Navigate, Group, Sort and Filter Data in WPF page on the WPF Tutorial.NET website.

Upvotes: 4

Related Questions