# Tuesday, 10 March 2009

I’m building a MVVM app in WPF, and needed to show a modal dialog, but I couldn’t figure out how to make it work and still maintain the separation between ViewModels and Views.  I have been mapping Views to ViewModels using DataTemplates, so that the relationship is declarative in XAML rather than in code someplace.  What I ended up with was a new Window called Dialog that takes a type in its constructor that corresponds to a ViewModelBase-derived type.  (See Josh Smith’s WPF Apps With The Model-View-ViewModel Design Pattern article for background on how the pieces fit together…) 

public partial class Dialog : Window
{
    public Dialog(Type vmType)
    {
        InitializeComponent();

        ViewModelBase vmb = Activator.CreateInstance(vmType) as ViewModelBase;
        
        item.Content = vmb;

        this.Title = vmb.DisplayName;
    }
}

In the XAML for Dialog, there’s just a Grid that contains a ContentPresenter called “item”.  The constructor sets item’s content to be the ViewModel, and the DataTemplate takes care of associating the View (a UserControl) with the ViewModel.  Note the use of SizeToContent="WidthAndHeight" on the Dialog window, which causes the window to resize to how ever big the UserControl that represents the View might be.

<Window x:Class="SomeNamespace.Dialog"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Dialog" SizeToContent="WidthAndHeight">
    <Grid>
        <ContentPresenter x:Name="item">
            
        </ContentPresenter>
    </Grid>
</Window>
<DataTemplate DataType="{x:Type vm:NewThingViewModel}">
    <vw:NewThing/>
</DataTemplate>

To create an instance of the new modal dialog, I just create a new instance of Dialog and pass the type of ViewModel it’s supposed to host…

new Dialog(typeof(NewThingViewModel)).ShowDialog();

There are still some details to work out as far as getting results from said dialog, but hey, progress…

Tuesday, 10 March 2009 15:36:01 (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [0]  |