Xamarin IOS Navigation with TableView



我相信这可能是一个非常简单的解决方案,但我对xamarin和c#一般来说都很陌生。我创建了一个表视图,当按下该视图中的一个单元格时,我希望它导航到一个新视图,名为SecondViewController()。我的ViewController.cs 中有以下类

     public void changeview()
    {
           SecondViewController controller = this.Storyboard.InstantiateViewController("SecondViewController") as SecondViewController;
        this.NavigationController.PushViewController(controller, true);
    }

然后在我的TableSource.cs类中,我有以下代码来调用changeview()

   public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
    {
        ViewController view = new ViewController();
        view.changeview();
        tableView.DeselectRow(indexPath, true);
    }

当它编译时,我没有得到任何错误,但当它运行时,我在以下代码上得到了一个错误

   SecondViewController controller = this.Storyboard.InstantiateViewController("SecondViewController") as SecondViewController;

它读取

  System.NullReferenceException: Object reference not set to an instance of an object

为什么这不起作用?如果我在按钮类中使用相同的代码,效果会很好,为了测试以确保我正确调用了该类,我将changeview()中的代码更改为UIAlertView,当按下单元格时,alertview会工作。我不知道该怎么办,可能有更好的方法可以改变观点吗?非常感谢您的帮助!

       SecondViewController controller = this.Storyboard.InstantiateViewController("SecondViewController") as SecondViewController;

您是否将情节提要Id用于"SecondViewController"。如果没有转到故事板,请将故事板Id添加到SecondViewController

您需要全局引用或访问应用程序的当前活动导航控制器才能进行推送。

您可以创建一个AppDelegate的实例,并将Navigation Controller设置为一个变量。

在您的AppDelegate.cs 中

[Register ("AppDelegate")]
public partial class AppDelegate : UIApplicationDelegate
{
    //application layer declarations
    public UINavigationController navCtrl { get; set; }
    /*
    .
    .  the rest of the codes
    .
    .*/
}

在ViewController.cs(第一视图)或实例化导航控制器的根视图控制器中:

public override void ViewDidLoad() {
    AppDelegate appD = UIApplication.SharedApplication.Delegate as AppDelegate;
    // assign the UINavigationController to the variable being used to push
    // assuming that you have already initialised or instantiated a UINavigationController
    appD.navCtrl = this.NavigationController; // Your UINavigation controller should be here
    /*
    .
    . the rest of the codes
    .
    */
}

在TableSource.cs类中。

private AppDelegate appD = UIApplication.SharedApplication.Delegate as AppDelegate;
public override void RowSelected (UITableView tableView, NSIndexPath indexPath){
    SecondViewController secondView = UIStoryboard.FromName ("Main", null).InstantiateViewController ("SecondViewController") as SecondViewController;
    appD.navCtrl.PushViewController (secondView, true);
}

这应该能够做你想做的事。

您应该在TableSource.cs类中保留ViewController的引用作为

public ViewController ParentController{ get; set;}

初始化数据源时,

tableClassObject.ParentController = this;

在所选行中,应为

public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
    {
        tableView.DeselectRow(indexPath, true);
        ParentController.changeview();
    }

这是最简单的解决方案。

最新更新