2017-09-07 28 views
-1

我有一個建立的是曾經有過的ObservableCollection收集VS ListCollectionView的指數

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

而在這個轉換器設置我結合這樣的數據透視表ValueConverter:

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綁定到正確的項目?

+0

您是否嘗試過'ListCollectionView'上的'GetItemAt(Int32)'方法? –

+0

這不會在綁定工作?因爲它實際上正在建立一個字符串,所以我會收到錯誤:BindingExpression path error:'[]'property''''ListCollectionView'(HashCode = 13293450)'找不到'。 BindingExpression:Path = EmployeeCol.GetIndex(1).Name – user1702369

+0

從你得到的異常問題很清楚,不是嗎?! 'GetItemAt(Int32)'的返回值是'System.Object'類型,您需要對預期類型進行類型轉換。例如:您的案例中的「員工」。 –

回答

1

ListCollectionView提供了一種方法object GetItemAt(Int32)來索引集合。

正是基於您的理解意見的僞代碼將是(當然空引用檢查等需要進行!):

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

ListCollectionView類的SourceCollection屬性返回一個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到任何類型的源收集,例如像列表:

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