Search code examples
c#wpflistcollectionview

Collection vs ListCollectionView index


I have a ValueConverter that builds a PivotTable that used to have a observableCollection

 var employees = values[0] as ObservableCollection<Employee>;

And in this converter I set my binding like this:

foreach( var employee in employees) {
  int indexer = periods.IndexOf( period );

  var tb = new TextBlock( ) {
    TextAlignment = TextAlignment.Center,
  };

  tb.SetBinding( TextBlock.TextProperty, new Binding( ) {
    ElementName = "root",
    Path = new PropertyPath( "EmployeesCol[" + indexer.ToString( ) + "]." + Extensions.GetPropertyName( ( ) => employee.Name ) )
  } );
}

Now my problem is that the binding used to work fine, the path looked like this:

EmployeesCol[1].Name

But I since have changed the ObservableCollection to a ListCollectionView So this:

var employees = values[0] as ObservableCollection<Employee>;

Became this:

var employees( (ListCollectionView) values[0] ).Cast<Employee>( ).ToList( );

Now this does not work anymore:

EmployeesCol[1].Name

You cant use the index (indexer) on a ListCollectionView like this, but how can I use the Indexer then on a ListCollectionView to bind to the correct item?


Solution

  • ListCollectionView provide a method object GetItemAt(Int32) to index the collection.

    Just a pseudo code based on comments for your understanding would be (of course null reference checks etc. need to be done!!) :

    var result = (EmployeesCol.GetItemAt(1) as Employee).Name;