I am writing a small application to learn WPF/MVVM and I have sort of run into a conundrum, I have a viewmodel object ready to go, but I don’t know where to instance it.
The viewmodel represents a single windows data(some sliders values, a progressbar value and a few textstrings. Some of these are directly attached to the model which is exposed, others are in the viewmodel to avoid adding new functionality to the model.)
I will only ever need 1 of these objects at a time(per window, but I am only allowing 1 window), although it really isn’t a singleton. It will exist for the lifetime of the window though(is that normal?)
So my question is this: Should I instance the viewmodel as a static resource in the App.Xaml, as a member of the App.xaml.cs class in the code behind(inside of an overridden “OnStartup” method) or as a resource in the Window.xaml, or as an object in the Window.xaml.cs.
I have seen people put it as a local resource and as a global object in the startup, but to me it seems like it shouldn’t be in the code behind(all I am doing is throwing it up in the air, once it’s in existance it can take care of everything else. That’s the whole point of it, actually).
So thoughts on where the viewmodel should be instanced?
It’s completely normal for a window’s view model to exist only for the lifetime of its window. Creating it can be as simple as putting:
in the constructor for
MainWindow. That’s how I do it in the absence of a compelling reason not to. (If the window’s going to need to interoperate with the view model in its event handlers, which it sometimes does, I’ll create a private field for the object so that I don’t have to keep castingDataContextin all the event handlers.)Usually, the view model needs to interoperate with one or more domain objects. The challenge in that case is coming up with a way of telling the view model about that object without coupling the domain object to the window that’s creating the view model. This is where you start screwing around with services and service locators and mockable objects and the like.
But even when you do this, you can still create the view model simply in the window’s constructor, e.g.:
The only time I don’t create a window’s view model in the window’s constructor is when the some other object – like a command in another window – is creating the window and setting its
DataContext.