如何使用mvvmcross UWP将Viewmodel中的值传递给其他ViewModel

时间:2017-08-25 08:46:14

标签: c# xamarin uwp mvvmcross

我想知道如何使用mvvcross和uwp将视图模型的值发送到另一个视图模型

有谁知道怎么做?

谢谢,

1 个答案:

答案 0 :(得分:1)

您可以使用IMvxNavigationService传递和返回对象。完整文档位于:https://www.mvvmcross.com/documentation/fundamentals/navigation?scroll=26

在您的ViewModel中,这可能如下所示:

public class MyViewModel : MvxViewModel
{
    private readonly IMvxNavigationService _navigationService;
    public MyViewModel(IMvxNavigationService navigationService)
    {
        _navigationService = navigationService;
    }

    public override void Prepare()
    {
        //Do anything before navigating to the view
    }

    public async Task SomeMethod()
    {
        _navigationService.Navigate<NextViewModel, MyObject>(new MyObject());
    }
}

public class NextViewModel : MvxViewModel<MyObject>
{
    public override void Prepare(MyObject parameter)
    {
        //Do anything before navigating to the view
        //Save the parameter to a property if you want to use it later
    }

    public override async Task Initialize()
    {
        //Do heavy work and data loading here
    }
}

使用IMvxMessenger您可以在没有连接的情况下发送值:https://www.mvvmcross.com/documentation/plugins/messenger?scroll=1446

public class LocationViewModel
    : MvxViewModel
{
    private readonly MvxSubscriptionToken _token;

    public LocationViewModel(IMvxMessenger messenger)
    {
        _token = messenger.Subscribe<LocationMessage>(OnLocationMessage);
    }

    private void OnLocationMessage(LocationMessage locationMessage)
    {
        Lat = locationMessage.Lat;
        Lng = locationMessage.Lng;
    }

    // remainder of ViewModel
}