首页 > 解决方案 > How can Activity Viewmodel get data from a Fragment child ViewModel?

问题描述

I'm developing a Xamarin.Android application using MvvmCross and I'm trying to get stored data into Fragment Viewmodel from the main activity Viewmodel.

This is what I have.

enter image description here

And I'm using

So, I'm trying to access to a FragmentAViewModel.SomeProperty from ActivityViewModel object.

Is it possible?

I'm using IMvxMessenger as a workaround to "send" a notification to ActivityViewModel with the content of the property I want to acceess.

Is there any other way to achieve this?

Thanks in advance.

标签: c#xamarin.androidmvvmcross

解决方案


一种替代方法是使用依赖注入系统来创建一个单例,该单例可用作视图模型之间的共享上下文。

例子

public interface ISharedContext 
{
    string Name { get; set; }
}

public class SharedContext : MvxNotifyPropertyChanged, ISharedContext 
{
    string _name;
    public string Name
    {
        get { return _name; }
        set { SetProperty(ref _name, value); }
    }
}

SharedContext在您的 App 类中注册

Mvx.LazyConstructAndRegisterSingleton<ISharedContext, SharedContext>();

在视图模型中的使用。然后,您可以直接绑定到SharedContext或分配给它的属性并在不同的视图模型中使用。

public class FragmentAViewModel : MvxViewModel
{
    public ISharedShoppingCart SharedContext { get; }

    public FragmentAViewModel(ISharedContext sharedContext)
    {
        SharedContext = sharedContext;
    }
}

public class ActivityViewModel : MvxViewModel
{
    public ISharedShoppingCart SharedContext { get; }

    public ActivityViewModel(ISharedContext sharedContext)
    {
        SharedContext = sharedContext;
    }
}

推荐阅读