I’m starting on my first WPF project using MVVM and Castle Windsor. I’m following the fairly standard approach of injecting a view model into its view’s constructor, which then sets its DataContext to the view model. What I’m not clear on is how/where to perform any UI “initialisation” that I want to happen right after the window has loaded (in my case I want to instantiate a number of user control “widgets” and put them on the window’s canvas).
Presumably I can’t do this in the constructor of the window’s view model, as it will have been called prior to the view’s InitialiseComponent being called. Besides, how would I even reference the canvas from the view model, which should have no knowledge of the view?
As part of trying to solve this, I created a “DesktopManager” component responsible for adding user controls to the canvas, but I’m getting circular references:-
- the view obviously has a dependency on the view model
- the DesktopManager has a dependency on the view (it needs to access the Canvas),
- the view model has a dependency on the DesktopManager (so it can tell the DesktopManager to create the widgets).
The DesktopManager still won’t help me though – referring back to my earlier question I don’t know how/where to call it to create the widgets. I’m clearly going about all this the wrong way, and perhaps answering my earlier question will solve this one too!
Any suggestions appreciated.
Andrew
If you are looking for a way to execute code in your view model once the view has been loaded, I would suggest that you bind the Loaded event of the view to a command in your view model.
Look here for one way to bind events to commands:
http://www.danharman.net/2011/08/05/binding-wpf-events-to-mvvm-viewmodel-commands/