如何在Xamarin中填充表格视图? [英] How to populate Table View in Xamarin?

查看:241
本文介绍了如何在Xamarin中填充表格视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将C#Windows应用程序移植到Mac,但是我一直试图用一堆字符串填充表格视图.表格视图似乎带有两列,这对我很有益,但是我不知道如何访问单元格,行,列或添加项目.在Windows中,我做了类似的事情:

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)
}

我在Xamarin中可以做什么?我是否需要另一个视图才能添加到表格视图?

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

推荐答案

您需要为表创建一个NSTableViewDataSource.通常,您将创建一个继承自NSTableViewDataSource的自定义类,然后覆盖这些方法

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

您将自定义Source类的实例分配给TableView的DataSource属性.您的数据源可能会具有一些内部数据结构(即列表,或更复杂的数据),您可以根据任何数据填充该内部数据结构.然后,您将自定义DataSource方法,以根据数据的长度等适当地进行响应.

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);
}

这篇关于如何在Xamarin中填充表格视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆