我有一个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上使用索引(索引器),但是如何在ListCollectionView上使用Indexer绑定到正确的项目?
答案 0 :(得分:1)
ListCollectionView
提供了一个方法object GetItemAt(Int32)
来索引集合。
只需基于评论的伪代码就可以了解(当然需要进行空引用检查等等):
var result = (EmployeesCol.GetItemAt(1) as Employee).Name;
答案 1 :(得分: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>;