I have a window that essentially runs a timer. When the timer hits 0 I want to bring the window to the front so that it is visible and not hidden behind some other application.
From what I can gather I would simply call window.activate() to accomplish this but with mvvm my view model doesn’t have a reference to window.
You could go about it in a couple of ways – adding a reference to the window could work since the viewmodel is not coupled with the view but related to it, but I don’t really like that approach since it pretty much does couple your view to your viewmodel – which is not really the point of MVVM
A better approach may be to have your viewmodel raise an event or a command which the view can handle. This way the view gets to decide what UI action is associated with the command/event
e.g. simply
Of course how you wire this up is up to you but I’d probably try and get routed commands happening
Edit: You can’t really ‘bind’ a simple event, since it’s invoked from the viewmodel.
A simple event based example is just to add the event to the viewmodel and handle it directly … e.g. imagine the following MainWindow with a ViewModel property
Then the ViewModel can just fire the event:
The XAML would be:
So the button invokes the command, which in turn fires the event which the view (MainWindow) handles and shows a messagebox. This way the view/UI decides on the course of action based on the type of event raised. Of course it could be your timer which fired the event
You can always go down the more involved route such as some of the answers on this question…
How should the ViewModel close the form?
but to be honest, it depends if you really need it – a simple event works well – some people overcomplicate things for the sake of elegance, but at the detriment of simplicity and productivity!