【问题标题】:Reference of view model locator in MVVM light by using a classMVVM light中视图模型定位器使用类的引用
【发布时间】:2016-12-27 06:04:52
【问题描述】:
我正在尝试下面的代码来查找视图模型定位器的引用,但我收到一条错误消息,提示无法将对象引用设置为对象的实例:-
internal class Locator : ViewModelLocator
{
private static readonly Lazy<Locator> _locator = new Lazy<Locator>(() => new Locator(), LazyThreadSafetyMode.PublicationOnly);
public static Locator Instance => _locator.Value;
private Locator()
{
SimpleIoc.Default.Register<MainViewModel>();
SimpleIoc.Default.Register<AddStudentViewModel>();
}
}
谁能帮我解决这个问题?
【问题讨论】:
标签:
c#
xamarin.forms
mvvm-light
【解决方案1】:
我在我的项目中使用波纹管代码,您需要添加公共 get set 属性以在定位器类中定位您的视图模型:-
internal class Locator : ViewModelLocator
{
private static readonly Lazy<Locator> _locator = new Lazy<Locator>(() => new Locator(), LazyThreadSafetyMode.PublicationOnly);
public static Locator Instance => _locator.Value;
private Locator()
{
SimpleIoc.Default.Register<MainViewModel>();
SimpleIoc.Default.Register<AddStudentViewModel>();
}
public MainViewModel Main
{
get
{
return ServiceLocator.Current.GetInstance<MainViewModel>();
}
}
public AddStudentViewModel AddStudentViewModel
{
get
{
return ServiceLocator.Current.GetInstance<QuestionsViewModel>();
}
}
}
否则另一种实现方式如下:-
您可以在 app.cs 中创建 locator 的 get set 属性:-
public static ViewModelLocator Locator
{
get { return _locator ?? new ViewModelLocator(); }
}
【解决方案2】:
我希望你通过延迟加载的第一种方法,你可以找到你的定位器的参考 :)
private static readonly Lazy<Locator> _locator = new Lazy<Locator>(() => new Locator(), LazyThreadSafetyMode.PublicationOnly);
public static Locator Instance => _locator.Value;
【解决方案3】:
你需要在注册你的视图模型后创建这样的方法
public CreateAssetViewModel CreateAssetVM
{
get
{
if (!SimpleIoc.Default.IsRegistered<CreateAssetViewModel>())
{
SimpleIoc.Default.Register<CreateAssetViewModel>();
}
return ServiceLocator.Current.GetInstance<CreateAssetViewModel>();
}
}