动态ViewModel导航

时间:2017-11-30 15:59:02

标签: xamarin mvvmcross

我正在尝试找到一种方法,可以从View设置到我必须导航的ViewModel。这是为了能够在不改变核心项目的情况下改变导航流程。

我认为更简单的方法是创建一个界面,在那里设置目标ViewModel并将界面注入ViewModel然后执行导航。

public interface IModelMapping
{
    MvxViewModel ViewModelToNavigate();
}

public class MyViewModel : MvxViewModel
{

    readonly IMvxNavigationService navigationService;
    readonly IModelMapping modelMapping;

    public MyViewModel(IMvxNavigationService navigationService, IModelMapping modelMapping)
    {
        this.navigationService = navigationService;
        this.modelMapping = modelMapping;
    }

    public IMvxAsyncCommand GoContent
    {
        get
        {
            IMvxViewModel vm = modelMapping.ViewModelToNavigate();
            IMvxAsyncCommand navigateCommand = new MvxAsyncCommand(() => navigationService.Navigate<vm>());

            return navigteCommand;
        }
    }
}

此代码的问题是我在设置navigationService.Navigate()时遇到错误。错误是'vm是一个变量,但它像一个类型'

一样使用

1 个答案:

答案 0 :(得分:1)

如何将URI导航与外观一起使用?另请参阅https://www.mvvmcross.com/documentation/fundamentals/navigation#uri-navigation

假设您正在构建一个任务应用程序,并根据您要显示不同视图的任务类型。这就是NavigationFacades派上用场的地方(只有那么多正则表达式可以为你做)。

mvx://task/?id=00 <– this task is done, show read-only view (ViewModelA)

mvx://task/?id=01 <– this task isn’t, go straight to edit view (ViewModelB)

[assembly: MvxRouting(typeof(SimpleNavigationFacade), @"mvx://task/\?id=(?<id>[A-Z0-9]{32})$")]
namespace *.NavigationFacades
{
    public class SimpleNavigationFacade
        : IMvxNavigationFacade
    {
        public Task<MvxViewModelRequest> BuildViewModelRequest(string url,
            IDictionary<string, string> currentParameters, MvxRequestedBy requestedBy)
        {
            // you can load data from a database etc.
            // try not to do a lot of work here, as the user is waiting for the UI to do something ;)
            var viewModelType = currentParameters["id"] == Guid.Empty.ToString("N") ? typeof(ViewModelA) : typeof(ViewModelB);

            return Task.FromResult(new MvxViewModelRequest(viewModelType, new MvxBundle(), null, requestedBy));
        }
    }
}