首页 > 解决方案 > MvvmCross - 如何从 UIApplication Xamarin.iOS 对 Mvx 视图进行导航调用

问题描述

我的目标是在空闲超时后将用户重定向回登录屏幕。每次点击/触摸后,我都有此代码倒计时。它运作良好,但我目前的问题是我不知道将用户重定向回登录屏幕。由于这是 MvvmCross 4.4 项目,因此没有太多可查找的文档。如果我还可以获得 Android 的示例代码,那将非常有帮助。我会感激的。

下面是我放在 Main.cs 中的代码

public class Application{  

    static void Main(string[] args){  
        //UIApplication.Main(args, null, "AppDelegate");  
        UIApplication.Main(args, "MyApplication", "AppDelegate");  
    }  

}  

//DELEGATE  
[Register("MyApplication")]  
public class MyApplication : UIApplication {  

    public override void SendEvent(UIEvent uievent) {  
        base.SendEvent(uievent);  
        var allTouches = uievent.AllTouches;  
        if (allTouches.Count > 0) {  
            var phase = ((UITouch)allTouches.AnyObject).Phase;  
            if (phase == UITouchPhase.Began || phase == UITouchPhase.Ended)  
                ResetIdleTimer();  
        }  
    }  

    NSTimer idleTimer;  
    void ResetIdleTimer() {  
        if (idleTimer != null) {  
            idleTimer.Invalidate();  
            idleTimer.Dispose();  
        }  

        idleTimer = NSTimer.CreateScheduledTimer(TimeSpan.FromMinutes(0.5), TimerExceeded);  
    }  

    void TimerExceeded(NSTimer obj) {  

        MvxiOSToastService toastService = new MvxiOSToastService();
        toastService.DisplayMessageAndDoSomething("You are going to be timed out.","Idle time exceeded.", RedirectToLogin);  

        Console.WriteLine("idle time exceeded");  
    }  

    void RedirectToLogin() {  

        var window = UIApplication.SharedApplication.KeyWindow;  
        var vc = window.RootViewController;  

        //ERROR HERE  
        var nextVC = new LoginView();   
        vc.ShowViewController(nextVC, this);  
        //----------
    }  
}  

标签: c#xamarin.androidxamarin.iosmvvmcross

解决方案


您需要解析视图演示者的实例并从那里获取当前呈现的视图。完成后,您可以访问 ViewModel 对象并进行以下调用以使用 MvvmCross 导航。

如果您可以访问RootViewController然后

void RedirectToLogin() {  
    var window = UIApplication.SharedApplication.KeyWindow;  
    var vc = window.RootViewController;  

    var mvxView = vc as IMvxIosView;  
    var vm = mvxView.ViewModel;

    vm.ShowViewModel<TViewModel>();
}

MvvmCross 前 5

https://www.mvvmcross.com/documentation/fundamentals/view-presenters

ShowViewModel<TViewModel>()

MvvmCross 5+

解析导航服务的一个实例,并使用它对登录屏幕进行导航调用。

所以像:

Mvx.Resolve<IMvxNavigationService>().Navigate<LoginViewModel>();

推荐阅读