Xamarin Android:如何实现ViewModelProvider工厂?

问题描述 投票:0回答:1

我正在尝试创建一个viewmodel提供程序工厂,我有点迷失了。我已经添加了必需的Nuget包,并且我的视图模型扩展了AndroidViewModel类型。现在,我想创建一个工厂,该工厂将使用autofac通过OnCreate活动方法创建所需的视图模型。创建调用如下所示:

_viewModel = (ViewModelProviders.Of(this, _viewModelFactory)
               .Get(Java.Lang.Class.FromType(typeof(MainActivityViewModel))) as JavaObjectWrapper<MainActivityViewModel>)
                .Object;

现在,工厂:

public class ViewModelFactory : ViewModelProvider.AndroidViewModelFactory {
    public ViewModelFactory(Application application) : base(application) {
    }

    public override Object Create(Class modelClass) {
        // TODO: any way to get the .NET type that was passed here?
        return base.Create(modelClass);
    }
}

我是否可以从传递给Create方法调用的Class实例中检索.NET类型(MainActivityViewModel)(从autofac容器解析该类型需要该类型)?如果有,我该怎么办?

谢谢。

xamarin.android viewmodel
1个回答
0
投票

这是我使用Unity的方法,但是该模式可用于通过ViewModel构造函数传递任何内容:

ViewModel本身

public class HomeViewModel : ViewModel
{
    IUnityContainer _unityContainer;
    public HomeViewModel(IUnityContainer unityContainer)
    {
        _unityContainer = unityContainer;
    }
}

The HomeViewModelFactory(需要默认构造函数)

public class HomeViewModelFactory : Java.Lang.Object, ViewModelProvider.IFactory 
{
    IUnityContainer _unityContainer;

    public HomeViewModelFactory()
    {

    }

    public HomeViewModelFactory(IUnityContainer unityContainer)
    {
        _unityContainer = unityContainer;
    }

    public Java.Lang.Object Create(Class p0)
    {
        return _unityContainer.Resolve<HomeViewModel>();
    }
}

片段中的用法

public override void OnActivityCreated(Bundle savedInstanceState)
    {
        base.OnActivityCreated(savedInstanceState);
        var homeViewModelFactory = _unityContainer.Resolve<HomeViewModelFactory>();
        _homeViewModel = ViewModelProviders.Of(this, homeViewModelFactory).Get(Java.Lang.Class.FromType(typeof(HomeViewModel))) as HomeViewModel;
    }
© www.soinside.com 2019 - 2024. All rights reserved.