Which executes the first code or view model

Based on my previous question Accessing variables from XAML and an object from ViewModel using Code Behind : How do I know what is executing first?

Is this code or ViewModel?
I just want to make sure my code behind is running before the ViewModel

-1
source share
1 answer

View and ViewModel are regular classes that receive an instance. This is done by calling the constructor, as in any other class. So, as a simple answer to your question: set a breakpoint in each constructor and see which one gets first.

There is no general answer to your question, because it depends on your architecture and usage. Often, some control is bound to the ViewModel property of that parent, which changes at some point. At this point, your view already exists, and you do not know how long the value for which the property was set has already been set. In other cases, your View is created for a specific ViewModel and takes it as a constructor parameter.

The only way to ensure that the ViewModel exists before the view is to pass the ViewModel as a constructor parameter. The idea of โ€‹โ€‹constructor parameters is to express: โ€œThis class needs existing instances of type xy to be created,โ€ which is what you are asking for. However, since you set it as the Views DataContext in the constructor and how the DataContext can change after the view is created, you cannot be sure that the View will not receive the new ViewModel assigned after creation. Worse, you can no longer use your control in XAML because it no longer has a default constructor.

According to your first question, it is not clear why the ViewModel must exist before the view. If you need to read the value of a resource from your view and assign it to a property in the ViewModel, would I expect it to be the other way around? Or are you accessing the view in your ViewModel (not necessary!)?

The question is why you should ask this question first. There is something rather wrong in your concept (or your bosses): View and ViewModel are two entities that should really work, not knowing about each other. The idea is to create applications that could work without a single view, only getting / setting values โ€‹โ€‹in ViewModels and having views that would compile any mode perfectly, without ViewModels, just without any manifestations or actions ... If If you try to crack this approach, you better not use MVVM at all.

+4
source

All Articles