2013-08-17 18 views
2

我試圖移植一個C#Windows應用程序到Mac,但我卡住試圖用一堆字符串填充表視圖。表視圖似乎有兩列,這對我很好,但我不知道如何訪問單元格,行,列或添加項目。在Windows中,我做了類似的操作:如何在Xamarin中填充表格視圖?

foreach(var item in items) 
{ 
    somelistbox.Items.Add(item) 
} 

我可以在Xamarin中做什麼?我需要另一個視圖添加到表視圖嗎?

回答

3

您需要爲您的表創建一個NSTableViewDataSource。通常,您將創建自己的自定義類,它繼承自NSTableViewDataSource,然後覆蓋這些方法

您將爲您的自定義Source類的實例分配給TableView的DataSource屬性。你的DataSource可能會有一些內部的數據結構(即List,或者更復雜的東西),你根據你的數據是什麼來填充它。然後,你將自定義數據源方法,基於數據的長度作出適當反應等

讓我們假設你的數據是一個簡單的String []:

// populate this in constructor, via service, setter, etc - whatever makes sense 
private string[] data; 

// how many rows are in the table 
public int NumberOfRowsInTableView(NSTableView table) 
{ 
    return data.length; 
} 

// what to draw in the table 
public NSObject ObjectValueForTableColumn (NSTableView table, NSTableColumn col, int row) 
{ 
    // assume you've setup your tableview in IB with two columns, "Index" and "Value" 

    string text = string.Empty; 

    if (col.HeaderCell.Title == "Index") { 
text = row.ToString(); 
    } else { 
    text = data [row]; 
    } 

    return new NSString (text); 
} 
+0

我假設,第一個方法返回'table.RowCount'。你能告訴我如何設置第二種方法嗎? – iwatakeshi

+0

或者它會是這樣的東西,除了在C#中嗎? [Mac桌面編程指南](https://developer.apple.com/library/mac/documentation/cocoa/Conceptual/TableView/PopulatingCellTables/PopulatingCellTables.html) – iwatakeshi

+1

我擴展了我的示例以包含一些更多細節 – Jason