I have a ViewModel that needs to show a modal window (using ShowDialog()
) on a button click. The ViewModel catches the click command, but I don't want to do window.ShowDialog()
within my ViewModel. I know there is a DialogMessage
in MVVM Light, but that is used to show message boxes, not WPF modal windows.
Any ideas on how to do this?
For all of you who want a really simple solution and are okay with not-100%-clean-MVVM:
I wanted to open a connect dialog from my main window and did the following
First i gave my MainWindow a name:
Then i created a Command in my MainWindowViewModel:
I bound my Button on the MainWindow to the Command and passed the window itself (the parent window for the dialog):
That's all.
Only caveat: Getting return values from the Viewmodel of the Dialog could be difficult. I don't need that feature.
This is what I use for custom dialogs with the MVVM-Light Toolkit.
First, define these four classes somewhere in your application. The MessageBase class is part of the toolkit.
Second, you need a "child" window control. Create a XAML file with the following content:
Then add the following to the code-behind of this XAML file:
Third, add the following to the code-behind of your MainWindow.xaml file:
Fourth, define the following view model:
Fifth, you create XAML files and view models for the content you want to display in your custom dialog. In this example, my content view models were named SomeContent and SomeOtherContent. You would replace these with what ever you want, of course.
Finally, in order for this to work you must bind your content view models to their respective XAML files by adding the following to your application resources:
Now, once you get all this set up it is very easy to add new content (XAML and view models) that can be displayed in your child window. To display the content, simply call the appropriate message using the Messenger class:
Let me know if I need to clarify any part of this for you.
You can define an interface and its implementation as follows. And ofcourse with dependency injection container, you have to do someting like this.
Your ViewModel will look something like this.
Your click command execute method would be as follows.
using System.Windows;
You should use
Messenger
class. On theView
register a message to show window and then when you need to show it callSend
method ofMessenger
class.You can do something like this: