I’m using C# WPF following the MVVM design pattern. Currently my View has a ListView which contains several columns and rows ( i.e. ListViewItems ).
The ViewModel exposes an ObservableCollection<Person> collection ( as shown below ) which the View binds to.
public ObservableCollection<Person> People
{
get
{
return _people;
}
set
{
// new value?
if( value != _people )
{
// Set
_people = value;
// Notify
OnPropertyChanged( "People" );
}
}
}
and here is the binding snippet
<ListView ItemsSource="{Binding People}" ... >
<!-- Omitted -->
</ListView>
In the View the user may click on a column header and the ListView will sort itself accordingly. The problem is that some of the logic and commands in the ViewModel are sensitive to the order of elements and when the ListView is sorted on a particular column the underlying People collection in the ViewModel doesn’t reflect the order the user is seeing.
Any clue on how to synchronize the sorted ListViewItems in the ListView with the underlying ObservableCollection<Person>?
Edit Already tried Mode=TwoWay on the ListView ItemsSource, that didn’t work.
The problem is (as you yourself stated) that some of the logic and commands in the ViewModel are sensitive to the order of elements. In short, they shouldn’t be; if the reason is actually reordering the items (just about the only one I can imagine where the order would be important), then the view shouldn’t be sortable by columns. Otherwise you need to find ways to make the order irrelevant – perhaps you could give an example of an action that depends on the order of items? That way we could suggest a real solution.
Also wanted to clarify that the order of the items in the view has no relation to their order in the source ObservableCollection. Generally the ItemsControls automatically create an ICollectionView that is sorted independently. Edit: yeah well not an actual ICollectionView, it’s a more complicated mechanism (what the ItemCollection does in conjunction with the ItemContainerGenerator) but you get the picture.