Collection vs ListCollectionView index

312 views Asked by At

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?

2

There are 2 answers

0
Siva Gopal On BEST ANSWER

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;
0
mm8 On

The SourceCollection property of the ListCollectionView class returns an IEnumerable that you can for example call the ElementAt method on or create a list from:

var employees = theListCollectionView.SourceCollection.OfType<Employee>().ToList();
var employee = employees[0];
...
var employees = theListCollectionView.SourceCollection.OfType<Employee>();
var employee = employee.ElementAt(0);

You can also cast the SourceCollection to whatever type your source collection is, like for example a List:

var employees = theListCollectionView.SourceCollection as IList<Employee>;