Question

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?

Was it helpful?

Solution

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);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top