Reputation: 11
I am trying code bellow to find reference of view model locator but I am getting an error saying object reference can not be set to instance of an object :-
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>();
}
}
Can any one help me in that, To solve this?
Upvotes: 1
Views: 526
Reputation: 452
I would prefer you first method by lazy loading you can find reference of your locator :)
private static readonly Lazy<Locator> _locator = new Lazy<Locator>(() => new Locator(), LazyThreadSafetyMode.PublicationOnly);
public static Locator Instance => _locator.Value;
Upvotes: 1
Reputation: 452
I am using bellow code in my project, you need to add public get set property for locating your view model in the locator class:-
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>();
}
}
}
or else another way of implementing the same is as bellow :- you can create a get set property of locator in app.cs :-
public static ViewModelLocator Locator
{
get { return _locator ?? new ViewModelLocator(); }
}
Upvotes: 3
Reputation: 305
you need to create method like this after registering your viewmodel
public CreateAssetViewModel CreateAssetVM
{
get
{
if (!SimpleIoc.Default.IsRegistered<CreateAssetViewModel>())
{
SimpleIoc.Default.Register<CreateAssetViewModel>();
}
return ServiceLocator.Current.GetInstance<CreateAssetViewModel>();
}
}
Upvotes: 0