How to populate Table View in Xamarin?

你说的曾经没有我的故事 提交于 2019-12-11 01:18:34

问题


I'm trying to port a C# Windows application to Mac but I'm stuck trying to populate a table view with a bunch of strings. The table view seems to come with two columns which is good for me but I don't know how to access the cells, rows, columns or add items. In Windows, I did something like:

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

What could I do in Xamarin? Do I need another view to add to table view?


回答1:


You need to create a NSTableViewDataSource for your table. Typically you will create your own custom class that inherits from NSTableViewDataSource, then override these methods

You will assign an instance of your custom Source class to the DataSource property of the TableView. Your DataSource will probably have some internal data structure (ie, a List, or something more complex) that you populate based on whatever your data is. Then you will customize the DataSource methods to respond appropriately based on the length of your data, etc.

Let's assume that your data is a simple 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);
}


来源:https://stackoverflow.com/questions/18293613/how-to-populate-table-view-in-xamarin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!