I can see that the constructor of the ViewModelLocator is executed first when my application starts, but how to make the constructors of my ViewModels run after that, because inside them I have a registering that I want to happen in the beggining of my app. The constructor of my CustomViewModel runs when I enter the View because of the binding. The binding is to a master class called CompositeViewModel that contains my viewModels.
CompositeViewModel:
class CompositeViewModel
{
public static CustomViewModel customViewModel { get; set; }
static CompositeViewModel()
{
customViewModel = new CustomViewModel();
}
}
Here is my ViewModelLocator
public ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
SimpleIoc.Default.Register<CustomViewModel>();
SimpleIoc.Default.Register<MainViewModel>();
}
public CustomViewModelTripTypeView
{
get
{
return ServiceLocator.Current.GetInstance<CustomViewModel>();
}
}
This is the code in my CustomViewModels constructor:
public CustomViewModel()
{
Messenger.Default.Register<ObservableCollection<MyType>>
(
this,
(action) => ReceiveMessage(action)
);
}
private void ReceiveMessage(ObservableCollection<MyType> action)
{
DispatcherHelper.CheckBeginInvokeOnUI(() =>
{
this.MyDataSource.Clear();
foreach (MyTypet mt in action)
{
this.MyDataSource.Add(mt);
}
});
}
There is an overloaded method for Register
method with bool
argument
SimpleIOC.Default.Register<MainViewModel>(true);
This statement will immediately create an instance of MainViewModel
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.