c# - 如何从 UITableView RowSelect Event Monotouch 访问主 UIViewController?

标签 c# uitableview uiviewcontroller xamarin.ios subclass

我的主 ViewController 上有一个 UITAbleView。 Tableview 是子类,如下所示。当用户选择一行时,我想通过调用主 ViewController 上的例程来切换到新 View 。但是,我无法从子类访问我的主视图 Controller 。我该怎么办?

public class TableSource : UITableViewSource
{
    string[] tableItems;
    string cellIdentifier = "TableCell";

    public TableSource(string[] items)
    {
        tableItems = items;
    }
    public override int RowsInSection(UITableView tableview, int section)
    {
        return tableItems.Length;
    }
    public override UITableViewCell GetCell(UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath)
    {
        UITableViewCell cell = tableView.DequeueReusableCell(cellIdentifier);
        if (cell == null)
            cell = new UITableViewCell(UITableViewCellStyle.Default, cellIdentifier);
        cell.TextLabel.Text = tableItems[indexPath.Row];
        return cell;
    }

    public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
    {
        new UIAlertView("Row Selected", tableItems[indexPath.Row], null, "OK", null).Show();
        tableView.DeselectRow(indexPath, true);

        //Call routine in the main view controller to switch to a new view

    }

}

最佳答案

我在发现并评论了一篇类似的帖子后偶然发现了这篇帖子: Xamarin UITableView RowSelection

虽然将 UIViewController 的实例传递给 TableSource 是解决此问题的一种方法,但它确实有其缺点。主要是因为您已将 TableSource 与特定类型的 UIViewController 紧密耦合。

我建议改为在您的 UITableViewSource 中创建一个 EventHandler,如下所示:

public event EventHandler ItemSelected;

我还会为所选项目设置一个 getter 属性:

private selectedItem
public MyObjectType SelectedItem{
    get{
        return selectedItem;
    }

}

然后我会像这样更新 RowSelected 方法:

public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
{
    selectedItem = tableItems[indexPath.Row];
    ItemSelected(this, EventArgs.Empty);
}

您的 UIViewController 然后可以监听 ItemSelected 事件并执行所需的任何操作。这允许您将 UITableViewSource 重用于多个 View 和 View Controller 。

关于c# - 如何从 UITableView RowSelect Event Monotouch 访问主 UIViewController?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15008852/

相关文章:

c# - 处理 File.Open 或 StreamContent

ios - UIRefreshControl 不消失

ios - 通过在另一个 ViewController 中按下按钮/在另一个 ViewController 中引用 UITableView 创建 UITableViewCell

ios - prefersStatusBarHidden,Swift 3 中的 preferredStatusBarStyle 属性

c# - 在 OOP 方法重载中使用 float 会出现错误

c# - 使用 OpenXML for Word 搜索和添加评论

c# - 无法创建 MyEntities 的实例

swift - 如何在一个tableview中使用两个collectionview

ios - 关闭模态呈现的 ViewController 总是让我回到根目录

swift - 呈现 Controller 时呈现加载图像的延迟