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

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=”http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;
  3.              xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml&#8221;
  4.              xmlns:viewmodels=”http://schemas.sela.co.il/advancedwpf&#8221;
  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=”http://schemas.openxmlformats.org/markup-compatibility/2006&#8243;
  9.              xmlns:d=”http://schemas.microsoft.com/expression/blend/2008&#8243;
  10.              mc:Ignorable=”d”
  11.              d:DesignHeight=”300″ d:DesignWidth=”300″>
  12.     <UserControl.DataContext>
  13.         <viewmodels:MessageListViewModel />
  14.     </UserControl.DataContext>
  15.     <Grid>
  16.         <DataGrid ItemsSource=”{Binding Messages}”
  17.                   SelectedItem=”{Binding SelectedMessage}”
  18.                   AutoGenerateColumns=”False”
  19.                   CanUserAddRows=”False”
  20.                   CanUserDeleteRows=”False”>
  21.             <DataGrid.Columns>
  22.                 <DataGridTextColumn Header=”From” Binding=”{Binding From}” IsReadOnly=”True” />
  23.                 <DataGridTextColumn Header=”Subject” Binding=”{Binding Subject}” IsReadOnly=”True” />
  24.                 <DataGridTextColumn Header=”Received” Binding=”{Binding Received}” IsReadOnly=”True” />
  25.                 <DataGridTextColumn Header=”Size” Binding=”{Binding Size}” IsReadOnly=”True” />
  26.             </DataGrid.Columns>
  27.             <i:Interaction.Triggers>
  28.                 <i:EventTrigger EventName=”MouseDoubleClick”>
  29.                     <behaviors:OpenWindowAction WindowUri=”/Dialogs/MessageDetailsDialog.xaml”
  30.                                                 IsModal=”True”
  31.                                                 Owner=”{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}”
  32.                                                 DataContext=”{Binding SelectedMessage}”
  33.                                                 CloseCommand=”{Binding CloseMessageDetailsCommand}” />
  34.                 </i:EventTrigger>
  35.             </i:Interaction.Triggers>
  36.         </DataGrid>
  37.     </Grid>
  38. </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:

imageimage

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;
  12. namespace WPFOutlook.PresentationLayer.Behaviors
  13. {
  14.     public class OpenWindowAction : TriggerAction<DependencyObject>
  15.     {
  16.         protected override void Invoke(object parameter)
  17.         {
  18.             Assert(CloseCommandProperty.Name, CloseCommand, null);
  19.             Assert(WindowUriProperty.Name, WindowUri, null);
  20.             if (DataContext == null)
  21.             {
  22.                 return;
  23.             }
  24.             if (_isOpen)
  25.             {
  26.                 return;
  27.             }
  28.             var window = (Window)Application.LoadComponent(WindowUri);
  29.             window.Owner = Owner;
  30.             window.DataContext = DataContext;
  31.             window.Closing += window_Closing;
  32.             if (IsModal)
  33.             {
  34.                 window.Show();
  35.             }
  36.             else
  37.             {
  38.                 window.ShowDialog();
  39.             }
  40.             _isOpen = true;
  41.         }
  42.         private void window_Closing(object sender, CancelEventArgs e)
  43.         {
  44.             var window = sender as Window;
  45.             bool canClose = CloseCommand.CanExecute(window.DialogResult);
  46.             if (canClose)
  47.             {
  48.                 CloseCommand.Execute(window.DialogResult);
  49.                 _isOpen = false;
  50.             }
  51.             e.Cancel = !canClose;
  52.         }
  53.     }
  54. }

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.

This entry was posted in MVC. Bookmark the permalink.

发表评论

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 更改 )

Twitter picture

You are commenting using your Twitter account. Log Out / 更改 )

Facebook photo

You are commenting using your Facebook account. Log Out / 更改 )

Google+ photo

You are commenting using your Google+ account. Log Out / 更改 )

Connecting to %s