-1

我有一个 ValueConverter,它构建了一个曾经有 observableCollection 的数据透视表

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

在这个转换器中,我将绑定设置为:

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 ) )
  } );
}

现在我的问题是绑定以前可以正常工作,路径如下所示:

EmployeesCol[1].Name

但是我已经将 ObservableCollection 更改为 ListCollectionView 所以这个:

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

变成了这样:

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

现在这不再起作用了:

EmployeesCol[1].Name

您不能像这样在 ListCollectionView 上使用索引(索引器),但是如何使用 Indexer 然后在 ListCollectionView 上绑定到正确的项目?

4

2 回答 2

1

ListCollectionView提供一种方法object GetItemAt(Int32)来索引集合。

只是一个基于注释的伪代码供您理解(当然需要进行空引用检查等!!):

var result = (EmployeesCol.GetItemAt(1) as Employee).Name;
于 2017-09-07T09:12:23.080 回答
0

类的SourceCollection属性ListCollectionView返回一个IEnumerable,例如,您可以调用该ElementAt方法或从以下位置创建一个列表:

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

您还可以将其SourceCollection转换为您的源集合的任何类型,例如 List:

var employees = theListCollectionView.SourceCollection as IList<Employee>;
于 2017-09-07T09:57:07.223 回答