Skip to main content

Composite applications in WPF: Part 1 - Setting it up

I'm mainly a web and integration kind of developer. I work with HTML, databases, services and getting it all fit together. Next year 2013, I will need to be up to date on WPF and that is why I decided to run a short blog series about building composite applications in WPF.

example application of a modular ui composition

Modularity in a UI, means that you have a shell and you fill that shell with modules that composes the application. These modules will be added dynamically and they will be able to integrate and communicate with one another. Such composite application will surely have a high rate of complexity in its composition, but near extreme cohesion in its modules. In this example I will only have one module (to begin with) and I will use MEF (managed extensibility framework) for composing the application.

application architecture

Creating the application

Start with creating a new WPF Application project. You will get a solution with one project, containing App.config, App.xaml and MainWindow.xaml. MainWindow is our application shell.

Before doing anything else, we will include Prism and Prism Mef Extensions. It is the MVVM library of my choosing. There are other WPF MVVM libraries out there, but Prism seems to be the most commonly used.

create new prism application

Also, make a reference to System.ComponentModel.Composition which should be located in your GAC. This will be needed for all interaction with the MEF container.

Now we're going to create a class called Bootstrapper. It will setup Prism, the MEF container and load modules.

namespace CompositeWPF
{
    using Microsoft.Practices.Prism.MefExtensions;
    using Microsoft.Practices.Prism.Modularity;
    using System.ComponentModel.Composition.Hosting;
    using System.Threading.Tasks;
    using System.Windows;

public class Bootstrapper : MefBootstrapper
{
    protected override System.Windows.DependencyObject CreateShell()
    {
        return new MainWindow();
    }

    protected override void InitializeShell()
    {
        base.InitializeShell();

        Application.Current.MainWindow = (MainWindow)this.Shell;
        Application.Current.MainWindow.Show();
    }

    protected override IModuleCatalog CreateModuleCatalog()
    {
        return new ConfigurationModuleCatalog();
    }

    protected override void ConfigureAggregateCatalog()
    {
        base.ConfigureAggregateCatalog();

        // Add this assembly
        this.AggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(Bootstrapper).Assembly));

        // Modules are copied to a directory as part of a post-build step.
        // These modules are not referenced in the project and are discovered by
        // inspecting a directory.
        // Projects have a post-build step to copy themselves into that directory.
        DirectoryCatalog catalog = new DirectoryCatalog(".");
        this.AggregateCatalog.Catalogs.Add(catalog);
    }
}

}

InitializeShell will create the MainWindow, also called the Shell. CreateModuleCatalog will create the module container and ConfigureAggregateCatalog will find modules and add them to the running instance. In our case, we will look for any DLL in the directory of the running program.

We need to bootstrap the bootstrapper from App.xaml.cs.

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

    Bootstrapper bootstrapper = new Bootstrapper();
    bootstrapper.Run();
}

}

MainWindow is our shell that will define regions where we can place modules. In this example we'll define two regions, a button region for loading modules and a content region.

<Window x:Class="CompositeWPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:prism="http://www.codeplex.com/CompositeWPF"
        Width="525" Height="350"
        Title="Modular UI with Composite WPF Application">

&lt;Window.Resources&gt;
    &lt;!-- Button Bar Panel --&gt;
    &lt;Style x:Key=&quot;button_panel&quot; TargetType=&quot;StackPanel&quot;&gt;
        &lt;Setter Property=&quot;Orientation&quot; Value=&quot;Horizontal&quot; /&gt;
        &lt;Setter Property=&quot;Background&quot; Value=&quot;Beige&quot; /&gt;
        &lt;Setter Property=&quot;DockPanel.Dock&quot; Value=&quot;Top&quot; /&gt;
    &lt;/Style&gt;

    &lt;!-- Content Region Panel --&gt;
    &lt;Style x:Key=&quot;content_panel&quot; TargetType=&quot;DockPanel&quot;&gt;
        &lt;Setter Property=&quot;DockPanel.Dock&quot; Value=&quot;Bottom&quot; /&gt;
    &lt;/Style&gt;

    &lt;!-- Region --&gt;
    &lt;Style x:Key=&quot;region&quot; TargetType=&quot;ItemsControl&quot;&gt;
        &lt;Setter Property=&quot;Padding&quot; Value=&quot;5&quot; /&gt;
    &lt;/Style&gt;
&lt;/Window.Resources&gt;

&lt;DockPanel&gt;
    &lt;StackPanel Style=&quot;{StaticResource button_panel}&quot;&gt;
        &lt;ItemsControl prism:RegionManager.RegionName=&quot;ButtonRegion&quot; Style=&quot;{StaticResource region}&quot; /&gt;
    &lt;/StackPanel&gt;
    &lt;DockPanel Style=&quot;{StaticResource content_panel}&quot;&gt;
        &lt;ItemsControl prism:RegionManager.RegionName=&quot;ContentRegion&quot; Style=&quot;{StaticResource region}&quot; /&gt;
    &lt;/DockPanel&gt;
&lt;/DockPanel&gt;

</Window>

I've included styles directly into the Window.Resources for brevity, but you should extract these into a ResourceDictionary. Now you can start and run the shell. It won't contain much as we haven't created any modules yet.

Your first module

Create a new WPF User Control Project in the same solution. I will call mineĀ CompositeWPF.ShoeSize. Delete the default user control and create a project structure like this image.

every project is a module in solution explorer

ShoeSize.cs is our module entry point that will bootstrap the module.

using CompositeWPF.ShoeSize.View;
using Microsoft.Practices.Prism.MefExtensions.Modularity;
using Microsoft.Practices.Prism.Modularity;
using Microsoft.Practices.Prism.Regions;
using System.ComponentModel.Composition;

[ModuleExport(typeof(ShoeSize))] public class ShoeSize : IModule { private IRegionManager regionManager;

[ImportingConstructor]
public ShoeSize(IRegionManager regionManager)
{
    this.regionManager = regionManager;
}

public void Initialize()
{
    // add views to regions
    regionManager.RegisterViewWithRegion(&quot;ButtonRegion&quot;, typeof(NavigationButton));
    regionManager.RegisterViewWithRegion(&quot;ContentRegion&quot;, typeof(ContentControl));

}

}

The region manager is our connection to the Shell, and our entry point for adding views to regions. In case you want to run the application at this point you need to put the [Export] attribute on the views code behind in order to get it to work.

Model View ViewModel

Everything we've done so far is about the composite application model. We really haven't touched the main subject, MVVM yet. The thought here is to create a poco class that represents the view, the viewmodel. Then you databind the view to the viewmodel leaving the view extremly bare when it comes to application logic. The viewmodel will take model object in order to carry out operations, like querying a webservice.

Let's start with the viewmodel for our content. We want to ask, what is your name? what is your shoe size and then produce a message that concatenates that information into a message. Consider the following viewmodel.

using Microsoft.Practices.Prism.Commands;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows.Input;

public class ContentViewModel : INotifyPropertyChanged {
private string name; private int shoeSize; private string message;

public event PropertyChangedEventHandler PropertyChanged;

public ContentViewModel()
{
    SubmitCommand = new DelegateCommand&lt;object&gt;(this.OnSubmit, this.CanSubmit);
}

public string Name
{
    get { return this.name; }
    set
    {
        if (this.name != value)
        {
            this.name = value;
            NotifyPropertyChanged();
        }
    }
}

public int ShoeSize
{
    get { return this.shoeSize; }
    set
    {
        if (this.shoeSize != value)
        {
            this.shoeSize = value;
            NotifyPropertyChanged();
        }
    }
}

public string Message
{
    get { return this.message; }
    set
    {
        if (this.message != value)
        {
            this.message = value;
            NotifyPropertyChanged();
        }
    }
}

public ICommand SubmitCommand { get; private set; }

private bool CanSubmit(object arg)
{
    return true;
}

private void OnSubmit(object arg)
{
    this.Message = string.Format(&quot;Hello {0}, your shoe size is {1}!&quot;, Name, ShoeSize);
}

private void NotifyPropertyChanged([CallerMemberName] string propertyName = &quot;&quot;)
{
    if (PropertyChanged != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

}

This tells us that the content has a Name, ShoeSize and Message property. Data can be submitted in the SubmitCommand and on that command, the Message should be set to "Hello Mikael, your shoe size is 41.". All this code is testable and does not have any reference to UI or Windows components. How does the XAML markup for the view look like?

<UserControl x:Class="CompositeWPF.ShoeSize.View.ContentControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:clr="clr-namespace:System;assembly=mscorlib"
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300">
    <UserControl.Resources>
        <!-- Wrap elements that stacks vertically -->
        <Style x:Key="wrapper" TargetType="StackPanel">
            <Setter Property="Margin" Value="10" />
            <Setter Property="Orientation" Value="Vertical" />
        </Style>

    &lt;!-- Represents a row in the form --&gt;
    &lt;Style x:Key=&quot;row&quot; TargetType=&quot;DockPanel&quot;&gt;
        &lt;Setter Property=&quot;Margin&quot; Value=&quot;0 0 0 5&quot; /&gt;
    &lt;/Style&gt;

    &lt;!-- Input element in the grid --&gt;
    &lt;Style x:Key=&quot;label&quot; TargetType=&quot;TextBlock&quot;&gt;
        &lt;Setter Property=&quot;DockPanel.Dock&quot; Value=&quot;Top&quot; /&gt;
    &lt;/Style&gt;

    &lt;!-- Input element in the grid --&gt;
    &lt;Style x:Key=&quot;input&quot; TargetType=&quot;TextBox&quot;&gt;
        &lt;Setter Property=&quot;DockPanel.Dock&quot; Value=&quot;Left&quot; /&gt;
        &lt;Setter Property=&quot;Width&quot; Value=&quot;auto&quot; /&gt;
    &lt;/Style&gt;

    &lt;!-- Submitbutton --&gt;
    &lt;Style x:Key=&quot;submit&quot; TargetType=&quot;Button&quot;&gt;
        &lt;Setter Property=&quot;Margin&quot; Value=&quot;0 0 0 5&quot; /&gt;
    &lt;/Style&gt;


    &lt;!-- What is your name? --&gt;
    &lt;clr:String x:Key=&quot;name_content&quot;&gt;What is your name?&lt;/clr:String&gt;

    &lt;!-- What is your shoe size? --&gt;
    &lt;clr:String x:Key=&quot;shoesize_content&quot;&gt;What is your shoe size?&lt;/clr:String&gt;

    &lt;!-- Submit button text --&gt;
    &lt;clr:String x:Key=&quot;submit_content&quot;&gt;Submit&lt;/clr:String&gt;
&lt;/UserControl.Resources&gt;

&lt;StackPanel Style=&quot;{StaticResource wrapper}&quot;&gt;
    &lt;DockPanel Style=&quot;{StaticResource row}&quot;&gt;
        &lt;TextBlock Style=&quot;{StaticResource label}&quot; Text=&quot;{StaticResource name_content}&quot; /&gt;
        &lt;TextBox Style=&quot;{StaticResource input}&quot; Text=&quot;{Binding Path=Name}&quot; /&gt;
    &lt;/DockPanel&gt;

    &lt;DockPanel Style=&quot;{StaticResource row}&quot;&gt;
        &lt;TextBlock Style=&quot;{StaticResource label}&quot; Text=&quot;{StaticResource shoesize_content}&quot; /&gt;
        &lt;TextBox Style=&quot;{StaticResource input}&quot; Text=&quot;{Binding Path=ShoeSize}&quot; /&gt;
    &lt;/DockPanel&gt;

    &lt;StackPanel Style=&quot;{StaticResource wrapper}&quot;&gt;
        &lt;Button Style=&quot;{StaticResource submit}&quot; Command=&quot;{Binding SubmitCommand}&quot; Content=&quot;{StaticResource submit_content}&quot;&gt;&lt;/Button&gt;
        &lt;TextBlock Text=&quot;{Binding Message}&quot;&gt;&lt;/TextBlock&gt;
    &lt;/StackPanel&gt;
&lt;/StackPanel&gt;

</UserControl>

This will produce the following UI.

visual representation of the xaml code

Now, all we need to do is to connect the view to the viewmodel. We do this in the view code behind.

[Export]
public partial class ContentControl : UserControl
{
    public ContentControl()
    {
        InitializeComponent();
        this.DataContext = new ContentViewModel();
    }
}

We have now successfully created a composite application, where a module is loaded dynamically into the Shell with content.

Navigation

We still have a navigation button to take care of. The focus here is that the content should not be visible until we pushed the button. Let us look at the view of the button first.

<UserControl x:Class="CompositeWPF.ShoeSize.View.NavigationButton"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d">

&lt;UserControl.Resources&gt;
    &lt;Style x:Key=&quot;icon&quot; TargetType=&quot;Button&quot;&gt;
        &lt;Setter Property=&quot;Width&quot; Value=&quot;24&quot; /&gt;
        &lt;Setter Property=&quot;Height&quot; Value=&quot;24&quot; /&gt;
        &lt;Setter Property=&quot;Padding&quot; Value=&quot;0&quot; /&gt;
        &lt;Setter Property=&quot;Background&quot; Value=&quot;Transparent&quot; /&gt;
        &lt;Setter Property=&quot;BorderThickness&quot; Value=&quot;0&quot; /&gt;
    &lt;/Style&gt;

    &lt;BitmapImage x:Key=&quot;simple-icon&quot; UriSource=&quot;../Resources/icon.png&quot; /&gt;
&lt;/UserControl.Resources&gt;

&lt;Grid&gt;
    &lt;Button Style=&quot;{StaticResource icon}&quot; Command=&quot;{Binding NavigateCommand}&quot;&gt;
        &lt;Image Source=&quot;{StaticResource simple-icon}&quot; /&gt;
    &lt;/Button&gt;
&lt;/Grid&gt;

</UserControl>

In the viewmodel we need to specify the NavigateCommand. This command should publish a navigation event in the event aggregator. Later we will subscribe to that event and decide what to do. The viewmodel looks like this.

using Microsoft.Practices.Prism.Commands;
using Microsoft.Practices.Prism.Events;
using System.ComponentModel.Composition;
using System.Windows.Input;

[Export] public class NavigationViewModel { private IEventAggregator eventAggregator;

[ImportingConstructor]
public NavigationViewModel(IEventAggregator eventAggregator)
{
    this.eventAggregator = eventAggregator;
    this.NavigateCommand = new DelegateCommand&lt;object&gt;(this.OnNavigate, this.CanNavigate);
}

public ICommand NavigateCommand { get; private set; }

private bool CanNavigate(object arg)
{
    return true;
}

private void OnNavigate(object arg)
{
    this.eventAggregator.GetEvent&lt;NavigationEvent&gt;().Publish(&quot;ContentRegion&quot;);
}

}

public class NavigationEvent : CompositePresentationEvent<string> { }

Since the constructor here is not empty we need to let the MEF container to resolve the dependency for us. This means that we need to do the codebehind of our view a bit different.

[Export]
public partial class NavigationButton : UserControl
{
    [ImportingConstructor]
    public NavigationButton(NavigationViewModel viewModel)
    {
        InitializeComponent();
        this.DataContext = viewModel;
    }
}

Now, each time we push the button a NavigationEvent is published. We need to subscribe to this event, and I choose to do this in the ShoeSize module. When the event is triggered I want to tell the region manager to navigate the content region to the ContentView. This looks like the following.

using CompositeWPF.ShoeSize.View;
using CompositeWPF.ShoeSize.ViewModel;
using Microsoft.Practices.Prism.Events;
using Microsoft.Practices.Prism.MefExtensions.Modularity;
using Microsoft.Practices.Prism.Modularity;
using Microsoft.Practices.Prism.Regions;
using System.ComponentModel.Composition;

[ModuleExport(typeof(ShoeSize))] public class ShoeSize : IModule { private IRegionManager regionManager; private IEventAggregator eventAggregator;

[ImportingConstructor]
public ShoeSize(IRegionManager regionManager, IEventAggregator eventAggregator)
{
    this.regionManager = regionManager;
    this.eventAggregator = eventAggregator;
}

public void Initialize()
{
    regionManager.RegisterViewWithRegion(&quot;ButtonRegion&quot;, typeof(NavigationButton));
    this.eventAggregator.GetEvent&lt;NavigationEvent&gt;().Subscribe(NavigateTo);
}

private void NavigateTo(string regionName)
{
    regionManager.RequestNavigate(regionName, &quot;ShoeSizeContent&quot;);
}

}

Now only one thing remain. We need to name the view to "ShoeSizeContent" in order for MEF to find it as it is resolved. So we need to revisit the content view codebehind and make sure that the export is named.

[Export("ShoeSizeContent")]
public partial class ContentControl : UserControl
{
    public ContentControl()
    {
        InitializeComponent();
        this.DataContext = new ContentViewModel();
    }
}

Summary

We have looked at how to build composite applications with WPF, the basics. The plan is to continue with advanced techniques, how modules can communicate with each others, how to handle subregions and dependency between modules.

comments powered by Disqus