Open Window, Dialog or Message Box from a ViewModel – part 1

March 25, 2011


Saying that a view-model belongs to the Application layer, and the Application layer doesn’t references upper layers, and must not create or use visual objects, how can I open a Window, Dialog or any kind of Message Box on-the-fly, based on some logic triggered by the view or view-model?

Well, there are several options doing that, one is using kind of service which encapsulates that, providing an interface, so the view-model don’t really work directly with the upper layer or WPF.

This solution is somehow problematic since the service should be implemented in the Presentation layer and somehow should be exposed to the view-model.

Having DI container is possible but still a bit tricky.


What other options we’ve got?

Say that you have a view-model contains list of email messages and the view renders it as an ItemsControl. Now you want displaying the email message details in a separate window triggered by:

  1. The View – Double clicking or selecting an email and then press Enter same way as Outlook does.
  2. The View-model – Property of a view-model changes, for example: ShowMessageDetails.

Before discussing my solution, I would like to say something about these two options.

– Opening a window triggered by the view when Routed event is raised or Routed command is executed is quite simple, in that case you should have a OpenWindowAction, triggered by event or command.

– Opening a window triggered by the view or view-model based on property change may be trickier, since property is a state, and it may by synchronized with the window state: Opened or Closed. In that case, changing the property should open or close the window, also closing the window should update the property.


Considering the fact that the window may be opened by the view or the view-model, based on event, command or property change, I propose two options: Custom Action and Behavior.

In this post I’ll cover the custom Action solution, and in the next post I’ll cover the Behavior solution which is a bit trickier.


Say that you’ve got: MessageListViewModel, MessageListView for the email messages view and MessageDetailsViewModel, MessageDetailsView for the email details view should be presented inside a window, lets say MessageDetailsDialog.

Having a SelectedMessage property in MessageListViewModel, lets look at the MessageListView:

Code Snippet
  1. <UserControl x:Class="WPFOutlook.PresentationLayer.Views.MessageListView"
  2.              xmlns=""
  3.              xmlns:x=""
  4.              xmlns:viewmodels=""
  5.              xmlns:views="clr-namespace:WPFOutlook.PresentationLayer.Views"
  6.              xmlns:behaviors="clr-namespace:WPFOutlook.PresentationLayer.Behaviors"
  7.              xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
  8.              xmlns:mc=""
  9.              xmlns:d=""
  10.              mc:Ignorable="d"
  11.              d:DesignHeight="300" d:DesignWidth="300">
  13.     <UserControl.DataContext>
  14.         <viewmodels:MessageListViewModel />
  15.     </UserControl.DataContext>
  17.     <Grid>
  18.         <DataGrid ItemsSource="{Binding Messages}"
  19.                   SelectedItem="{Binding SelectedMessage}"
  20.                   AutoGenerateColumns="False"
  21.                   CanUserAddRows="False"
  22.                   CanUserDeleteRows="False">
  24.             <DataGrid.Columns>
  25.                 <DataGridTextColumn Header="From" Binding="{Binding From}" IsReadOnly="True" />
  26.                 <DataGridTextColumn Header="Subject" Binding="{Binding Subject}" IsReadOnly="True" />
  27.                 <DataGridTextColumn Header="Received" Binding="{Binding Received}" IsReadOnly="True" />
  28.                 <DataGridTextColumn Header="Size" Binding="{Binding Size}" IsReadOnly="True" />
  29.             </DataGrid.Columns>
  31.             <i:Interaction.Triggers>
  32.                 <i:EventTrigger EventName="MouseDoubleClick">
  33.                     <behaviors:OpenWindowAction WindowUri="/Dialogs/MessageDetailsDialog.xaml"
  34.                                                 IsModal="True"
  35.                                                 Owner="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}"
  36.                                                 DataContext="{Binding SelectedMessage}"
  37.                                                 CloseCommand="{Binding CloseMessageDetailsCommand}" />
  38.                 </i:EventTrigger>
  39.             </i:Interaction.Triggers>
  41.         </DataGrid>
  42.     </Grid>
  43. </UserControl>

As you can see in line 30, I’ve attached the DataGrid with a Blend trigger, listening on MouseDoubleClick routed event. Whenever this event is raised, the custom OpenWindowAction is invoked which currently displays our window.

The OpenWindowAction action has the following properties:

  1. WindowUri – a simple Uri points to the XAML file defines our window.
  2. IsModal – true to open the window as modal, false as modeless.
  3. Owner – the owner of our window in case that we want opening it relative to the owner for example.
  4. DataContext – view-model to set in our new window data context, in our case the message details view-model retrieved by the MessageListViewModel.SelectedMessage.
  5. CloseCommand – a command notifying that the window is about to be closed, and also if it possible.

Of course you can add additional properties such as: The type of the window instead or in addition to the WindowUri, a property saying that the view-model should be displayed in a popup instead of a window, etc.

Running this sample and double clicking on the single email, you’ll notice the following:


Now lets look at the OpenWindowAction:

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Windows;
  6. using System.Windows.Interactivity;
  7. using System.ComponentModel;
  8. using System.Windows.Input;
  9. using WPFOutlook.ApplicationLayer.Common;
  10. using System.Windows.Threading;
  11. using System.Diagnostics;
  13. namespace WPFOutlook.PresentationLayer.Behaviors
  14. {
  15.     public class OpenWindowAction : TriggerAction<DependencyObject>
  16.     {        
  17.         protected override void Invoke(object parameter)
  18.         {
  19.             Assert(CloseCommandProperty.Name, CloseCommand, null);
  20.             Assert(WindowUriProperty.Name, WindowUri, null);
  22.             if (DataContext == null)
  23.             {
  24.                 return;
  25.             }
  27.             if (_isOpen)
  28.             {
  29.                 return;
  30.             }
  32.             var window = (Window)Application.LoadComponent(WindowUri);
  33.             window.Owner = Owner;
  34.             window.DataContext = DataContext;
  35.             window.Closing += window_Closing;
  37.             if (IsModal)
  38.             {
  39.                 window.Show();                
  40.             }
  41.             else
  42.             {
  43.                 window.ShowDialog();
  44.             }
  46.             _isOpen = true;
  47.         }
  49.         private void window_Closing(object sender, CancelEventArgs e)
  50.         {
  51.             var window = sender as Window;
  52.             bool canClose = CloseCommand.CanExecute(window.DialogResult);
  53.             if (canClose)
  54.             {
  55.                 CloseCommand.Execute(window.DialogResult);
  56.                 _isOpen = false;
  57.             }
  59.             e.Cancel = !canClose;
  60.         }
  61.     }
  62. }

As you can see, the Invoke override checks the properties, creates a window from the given window URI, then displays the window.

Whenever the window is trying to close, the CloseCommand is queried by calling the CanExecute method. If everything fine, the window closes.


You can download the code from here.

Next time I’ll show how to implement the open window Behavior.

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>



  1. David GalvanNovember 2, 2012 ב 21:41

    How can add this example with MEF?, and pass the view to the MessageDetailsDialog as a parameter

  2. DexJune 28, 2013 ב 12:53

    In the Invoke() the IsModel check appears to be flipped as you want the child window blocking via the ShowDialog when IsModel == true. And in the event that you want blocking, the “_isOpen = true” statement may cause problems as well since it will be set too late. In other words, depending on the Event which has triggered your TriggerAction, it’s possible for a second event to fire while the current child window is already open.