EF Code First and WPF with the Chinook database. Part 3 – Styles and DataTemplates 101

I have decided to split out the styling work into 2 posts as it would be a huge post to restyle even something so simple.  so this post is going to change the controls to be more style-conscious and introduce basic style and the next post will introduce some more advance concepts such as using adorners to display additional details.

Going back to the previous post we had a basic app as follows:

This is slightly ugly and needs a little work so the first thing I want to add is  a style that will tidy up the artist list.

I want the artist list to have a nice look and feel with rounded button type items and also contain a count of the number of albums – I want each item in the list to look something like this:

image

The first step to getting this design in place is adding the DataTemplate so that it is picked up by the item.  A DataTemplate is a template that gets applied to an object that has no default way of showing itself and manifests itself as its type name.

NOTE – this can also be be done by overriding Object.ToString() but this is a client side post so I don’t want to have to change model code to do something.

I have added a simple DataTemplate to the Application.Resources section in App.xaml as follows:

<DataTemplate DataType="{x:Type business:Artist}">
    <TextBlock x:Name="contentHolder">
        <TextBlock.Text>
            <MultiBinding StringFormat="{}{0} - {1} albums">
                <Binding Path="Name"/>
                <Binding Path="Albums.Count" />
            </MultiBinding>
        </TextBlock.Text>                
    </TextBlock>
    <DataTemplate.Triggers>
        <DataTrigger Binding="{Binding Albums.Count}" Value="1">
            <DataTrigger.Setters>
                <Setter Property="TextBlock.Text" TargetName="contentHolder">
                    <Setter.Value>
                        <MultiBinding StringFormat="{}{0} - {1} album">
                            <Binding Path="Name"/>
                            <Binding Path="Albums.Count" />
                        </MultiBinding>
                    </Setter.Value>
                </Setter>
            </DataTrigger.Setters>
        </DataTrigger>
    </DataTemplate.Triggers>
</DataTemplate>

There are several things going on here:

  1. the first line declares the type that this template is associated with – you have to add the namespace to this file first in order to make this work:
    xmlns:business="clr-namespace:MusicApp.Model;assembly=MusicApp.Model"
    
  2. The MultiBinding has an associated StringFormat – this is the same as a normal format string except for the “{}” after the equals sign – this simply escapes the format string.
  3. The binding to Albums.Count – yes you can bind to “built-in” properties as well.
  4. The DataTrigger is a simple way of saying that if we have only one album then the trailing text shouldn’t have an ‘s’ on the end.

It is possible to do the whole string in a converter but I like the declarative way as you can see everything going on in one place.  For those that like using converters you would bind the TextBlock’s Text property to the whole Artist ({Binding}) and then use a converter like the following:

public class ArtistStringConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        string retVal = string.Empty;
        var artist = value as Artist;
        if (artist != null)
        {
            retVal += string.Format("{0} - {1} {2}", artist.Name, artist.Albums.Count, artist.Albums.Count == 1 ? "artist" : "artists");
        }

        return retVal;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

this is then used from the xaml as follows:

<local:ArtistStringConverter x:Key="artistConverter"/>
<DataTemplate DataType="{x:Type business:Artist}">
    <TextBlock x:Name="contentHolder" Text="{Binding Converter={StaticResource artistConverter}}" />
</DataTemplate>

Once this is added (either option) you need to remove the DisplayMemberPath property from the ArtistList.xaml view so that the template is used instead.

I now have a list of Artists that show the name and the total albums they have so I can work on the actual style to make the list items look like the above image.

I want all three lists to look the same so I am adding a style with no key to the app.xaml file.  If you want specific styles for your controls then you can add ‘x:Key=”YourKeyName”’ and reference it using ‘{StaticResource YourKeyName}’ (in this instance the reference would be in the ItemContainerStyle property of the ListBox).

<Style TargetType="ListBoxItem">
    <Style.Setters>
        <Setter Property="Margin" Value="5,2" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ListBoxItem">
                    <Grid>
                        <Rectangle Opacity="0.5" Height="30" StrokeThickness="1" x:Name="backBox"
                                        Stroke="Silver" RadiusX="5" RadiusY="5" Fill="Azure"/>
                        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                    </Grid>
                    <ControlTemplate.Triggers>
                        <Trigger Property="Selector.IsSelected" Value="True">
                            <Setter TargetName="backBox" Property="Fill" Value="Silver"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style.Setters>
</Style>

Again I have a couple of things going on inside this style:

  1. It targets ListBoxItem as this is what we want to style (not the ListBox itself).
  2. The margin separates the items nicely.
  3. The actual style part is contained inside a ControlTemplate which is then assigned  the Template property of the ListBoxItem.
  4. The ContentPresenter will present whatever content it is given, in this case it is presenting the passed in DataTemplate.
  5. The trigger here indicates that when the ListBoxItem is selected we want to change the fill colour of the rectangle to indicate we have selected an item.

To finish I have added a new DataTemplate for the albums – this looks the same with the type and property names changed to display the correct things and I have also rearranged the view as follows:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="0.5*" />
        <ColumnDefinition Width="0.5*" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="0.5*"/>
        <RowDefinition Height="0.5*"/>
    </Grid.RowDefinitions>

    <ListBox ItemsSource="{Binding Path=Artists}" Margin="5" 
                Grid.Column="0" Grid.Row="0"
                Grid.RowSpan="2"
                SelectedItem="{Binding SelectedArtist}" />
        
    <ListBox ItemsSource="{Binding Path=SelectedArtist.Albums}" Margin="5" 
                Grid.Column="1" Grid.Row="0" 
                SelectedItem="{Binding SelectedAlbum}" />
        
    <ListBox ItemsSource="{Binding Path=SelectedAlbum.Tracks}" Margin="5" 
                DisplayMemberPath="Name" 
                Grid.Column="1" Grid.Row="1" />
</Grid>

This now gives me the following view which I am sure you will agree looks a lot better and is easily achievable by simply using XAML – we could have done this in blend as well but for the simple changes we have made I prefer to edit the XAML directly.

image

In the next post I will be adding some adorner goodness to the screen for displaying album and track details (which also covers changes to the model).

EF Code First and WPF with the Chinook database. Part 2 – The client

Now we have the data fetching work sorted out we can turn our attentions to the front-end.

I am going to make a very simple view in this post listing the artists and associated albums with their tracks.  It is going to look like this:

image

Now, this is very basic but it serves its purpose to show the tools we are going to be using – a later post will use the power of WPF to style and transform the screen into something more palatable.

The first thing to do is add a WPF project(I have named mine MusicApp.WPF.Client).  If you rename the the MainWindow.xaml file then don’t forget to change the startup uri in app.xaml

<Application x:Class="MusicApp.WPF.Client.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="Main.xaml">

In terms of the structure for the project I have separate folders for views, view models and common files.

The View

Once the basic structure is in place we can add our view to the Views folder.  The view in this case is a user control that we will add to the main window.

The view itself is very simplistic – 1 grid containing 3 ListBoxes and is created as follows

<UserControl x:Class="MusicApp.WPF.Client.Views.ArtistList"
              xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
              Height="Auto" Width="Auto">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="0.5*" />
            <ColumnDefinition Width="0.5*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="0.7*"/>
            <RowDefinition Height="0.3*"/>
        </Grid.RowDefinitions>
        <ListBox ItemsSource="{Binding Path=Artists}" Margin="5" 
                 DisplayMemberPath="Name" Grid.Column="0" 
                 Grid.ColumnSpan="2" Grid.Row="0" 
                 SelectedItem="{Binding SelectedArtist}" />
        
        <ListBox ItemsSource="{Binding Path=SelectedArtist.Albums}" Margin="5" 
                 DisplayMemberPath="Title" Grid.Column="0" Grid.Row="1" 
                 SelectedItem="{Binding SelectedAlbum}" />
        
        <ListBox ItemsSource="{Binding Path=SelectedAlbum.Tracks}" Margin="5" 
                 DisplayMemberPath="Name" Grid.Column="1" Grid.Row="1" />
    </Grid>
</UserControl>

This is a view with a 2 x 2 grid with columns of equal width (1/2 of the grid each) and one row at 70% width and one at 30%.  Inside the grid there is a ListBox that takes up the whole top row (ColumnSpan=2) and one ListBox in each of the columns in the lower row.

I have included all of the bindings so that I know what is required on the view model when I write it.  I will need a collection property called ‘Artists’ and 2 properties for the selected artist and selected album.

The DisplayMemberPath details which property of the object will be displayed as text in the ListBoxItem.

Once the control has been written then we can add it to the main window xaml.  There are 2 things to do to add a usercontrol to another xaml file

  1. add the correct namespace.
  2. add the control

Adding the namespace requires that we add an xmlns to the top of the main window file

xmlns:views="clr-namespace:MusicApp.WPF.Client.Views"

Once we have this then we can simply add the control as a new object on the window

<views:ArtistList/>

which gives us a Main window with the following xaml

<Window x:Class="MusicApp.WPF.Client.Main"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:views="clr-namespace:MusicApp.WPF.Client.Views"
        Title="Main" Height="475" Width="425">
    <Grid>
        <views:ArtistList/>
    </Grid>
</Window>

The ViewModel

Now the view is done I can create a ViewModel to support it.  The ViewModel will need to implement INotifyPropertyChanged and I have the following snippet method that will fire the event implemented by it

private void Notify(string propertyName)
{
    if (PropertyChanged != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

Unity

I want to be able to use a different data provider here if I want to so I am going to introduce the Unity IoC container to the application at this point.  Unity can be installed into the current project directly from NuGet (install-package unity) or you can download directly. It needs a little configuration before we can use it.

I am going to use it to resolve a reference to the IDataProvider interface we created previously so I add a new app.config file to the client project and add the following configuration

<configuration>
    <configSections>
        <section name="unity"
                             type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" />
    </configSections>
    <unity>
        <containers>
            <container>
                <type type="MusicApp.Model.IDataProvider, MusicApp.Model" mapTo="MusicApp.Model.EFCodeFirstDataProvider, MusicApp.Model" />
            </container>
        </containers>
    </unity>
</configuration>

This is simply adding a mapping between IDataProvider and EFCodeFirstDataProvider which allows me to resolve the former to the latter.

We need a way of referencing this container in our application so I use a factory class with a static member to hold the actual UnityContainer

class ContainerFactory
{
    private static UnityContainer container;

    public ContainerFactory()
    {
        if (container == null)
        {
            container = new UnityContainer();
            UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
            section.Containers.Default.Configure(container);
        }
    }

    public UnityContainer Container
    {
        get
        {
            return container;
        }
    }
}

I can then have a reference to an IDataProvider in the ViewModel and resolve it from the constructor as follows

ContainerFactory factory = new ContainerFactory();
provider = factory.Container.Resolve<IDataProvider>();

The whole ViewModel including properties now looks like this.

public class ArtistListViewModel : INotifyPropertyChanged
{
    private IDataProvider provider;
    private ObservableCollection<Artist> artists;
    private Artist selectedArtist;
    private Album selectedAlbum;

    public ArtistListViewModel()
    {
        ContainerFactory factory = new ContainerFactory();
        provider = factory.Container.Resolve<IDataProvider>();
        GetArtists();
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public ObservableCollection<Artist> Artists
    {
        get
        {
            return artists;
        }
        private set
        {
            artists = value;
            Notify("Artists");
        }
    }

    public Artist SelectedArtist
    {
        get
        {
            return selectedArtist;
        }
        set
        {
            selectedArtist = value;
            Notify("SelectedArtist");
        }
    }

    public Album SelectedAlbum
    {
        get
        {
            return selectedAlbum;
        }
        set
        {
            selectedAlbum = value;
            Notify("SelectedAlbum");
        }
    }

    private void GetArtists()
    {
        Artists = new ObservableCollection<Artist>(provider.GetArtists());
    }

    private void Notify(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

Wire it up

Now we have the ViewModel and view in place we need to wire them together this is just a case of setting the views DataContext from its constructor

public ArtistList()
{
    InitializeComponent();
    this.DataContext = new ArtistListViewModel();
}

Wrapping up

Now we have these wired we simply need to add the ConnectionStrings to the config file (that we added the unity config to earlier), change the startup project to the new WPF app and run it.  This will now display the window shown at the start and I can change the artist to update the albums/tracks at the bottom.

Next time – making the view look good.

EF Code First and WPF with the Chinook database. Part 1 – the model

Introduction

I am going to start a series of posts building a simple app using the Chinook database as a back-end and putting a WPF client on the front-end.  I am going to keep it loose as I don’t want to commit to blog posts that I may not get chance to complete so I will keep every post self-contained covering 1 detail of the implementation.

The technologies and tools I plan on using for this series are as follows:

As you can see the idea is to use the latest technologies available to build a simple app to display the music details from the Chinook database.  As I am not committing to a large series I will say that my intentions for the series include:

  • Setting up the model using EF4 Code First (this post).
  • creating a basic screen listing the artists and associated albums.
  • Creating an album details adorner to show the tracks of individual albums.

Possible future posts will include:

  • Adding the ability for customers to place an order (creating invoices).
  • Adding employees to manage the customer invoices (this is a WPF app so the employee will be doing all of the work as this is not a customer facing app).
  • Adding the ability to create custom playlists that can reviewed.

Note that all of these items already exist in the Chinook database and I will be focusing on the data access and UI layers.

Building the model using EF Code First

The first thing we need to do is create a new solution for our app.  Being as we are creating the model first I am going to create a class library.

Once the solution and project are in place we need to get the Code First bits into the project.  I am going to use NuGet so you need to have this installed.

In the NuGet package manager window we can find the required package by firing the command:

Get-Package –remote –filter CodeFirst

This will give us the following output:

image

This shows us the package that we need to install is EFCodeFirst so we issue

Install-Package EFCodeFirst

this should add the EntityFramework reference to your project but it didn’t do that on my class library so I had to add the reference manually ({SolutionFolder}\packages\EFCodeFirst.0.8\lib\EntityFramework.dll).

Now we have the reference we can start to create our POCO objects.  I am going to create a model that initially uses the Artist, Album and Track tables as they are going to be used in the first part of this app – I will add more as I go along.

EF Code First allows us to create standard POCOs to represent our model so for my initial model I have:

public class Artist
{
    public int ArtistId { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Album> Albums { get; set; }
}

public class Album
{
    public int AlbumId { get; set; }
    public string Title { get; set; }
    public virtual Artist Artist { get; set; }
    public virtual ICollection<Track> Tracks { get; set; }
}

public class Track
{
    public int TrackId { get; set; }
    public string Name { get; set; }
    public virtual Album Album { get; set; }
    public string Composer { get; set; }
}

Note the virtual association properties – this is to allow these properties to be lazy-loaded.

The next thing we need is the actual dbContext which is defined as follows:

using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions.Edm.Db;
.
.
.
public class Chinook : DbContext
{
    protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }

    public DbSet<Artist> Artist { get; set; }
    public DbSet<Album> Album { get; set; }
    public DbSet<Track> Track { get; set; }
}

This is a class that includes one property per table in the database and handles the mapping to our objects.  This is using default conventions with the exception of the one removed in the overridden OnModelCreating method.  This says that the database we have doesn’t have pluralised names as Code First expects and instead the names match the entities.

Next we need to add an app.config file to the project and add the ConnectionString for the database.  I use SQLServer so adjust accordingly.

<connectionStrings>
    <add name="Chinook" providerName="System.Data.SqlClient"
        connectionString="Data Source=.;Initial Catalog=chinook;Integrated Security=true" />
</connectionStrings>

Notice that the name of the connectionString must be the same as the class name when using the default conventions.

Testing that it works

OK, we have the model built now and can run a crude test to see if it works.  Add a console app to your solution and set it as the startup project.  Add references to the Model assembly and the Code First assembly and move the app.config to the new project. Now add the following code to the main method.

static void Main(string[] args)
{
    using (Chinook db = new Chinook())
    {
        foreach (var artist in db.Artist)
        {
            Console.WriteLine(artist.Name);
        }

        Console.ReadLine();
    }
}

This will loop through all of the artists and print their name to the screen.

That’s all there is to creating a simple model with Entity Framework Code First CTP5.  In the next instalment I plan on writing a simple data provider class that will abstract the actual DbContext calls away from the user and allow the user to simply call methods like provider.GetArtists().

WPF/Silverlight ListBox and equality checking

In WPF we bind collections of objects to ListBoxes and the like all the time – its part and parcel of the WPF development cycle but this is something that stung me recently.

I bound a collection of objects to the ItemsSource property as usual but the selection was odd.  Every time I selected an item the ListBox assumed that the first item was also selected and subsequent selections marked all previous selections as selected, also the SelectedIndex was always 0.  It took some time but I tracked it down to the way that ListBoxes use equality.

Something I didn’t know was that the objects that I was using had an overridden Equals method which was simply comparing a single string on the objects to determine if they were equal.  Because I only wanted a small subset of of the object I only populated those properties I needed along with the id of the object and not the string being compared.

The below shows an example of what I was doing.

public class MainViewModel : INotifyPropertyChanged
{
    private ObservableCollection foos;

    public ObservableCollection Foos
    {
        get
        {
            return foos;
        }
        set
        {
            foos = value;
        }
    }

    public MainViewModel()
    {
        this.Foos = new ObservableCollection();
        this.Foos.Add(new Foo { id = 1, Display = "First" });
        this.Foos.Add(new Foo { id = 2, Display = "Second" });
        this.Foos.Add(new Foo { id = 3, Display = "Third" });
        this.Foos.Add(new Foo { id = 4, Display = "Fourth" });
        this.Foos.Add(new Foo { id = 5, Display = "Fifth" });
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

public class Foo
{
    public int id { get; set; }

    public string Display { get; set; }

    public string FooCode { get; set; }

    public override bool Equals(object obj)
    {
        return FooCode == (obj as Foo).FooCode;
    }
}

As we can see I have no interest in the FooCode property and as a result don’t use it in my ViewModel.

The problem with this is that now the ListBox has no way of knowing if the objects are different as we have an overriding Equals method that implements value equality rather than reference equality and because the value is always going to be the same (as I don’t set it) then the ListBox will assume that every object is essentially the same object.

A simple change to include the FooCode property in each object in the collection solves this problem and gives us different values for equality testing.

A sample project with 2 lists displaying this different behaviour can be found here.

Skinning in WPF

I like writing XAML.  It gives me a sense of completion when I write a style of template by hand and it just works, I like using blend as well but raw is more fun Smile.

Lets say we have a requirement to change the front-end of a product for different brandings and “products” (that is, the same product with a different ‘skin’).  One of the challenges we have is that we don’t want to write new user controls every time the client screen needs to change (especially for something simple such as switching to a different style for certain builds).  What follows is a way of using the power of WPF resources to skin an application with little work.

we start off with 2 ListBoxes on a window, for the purposes of this article the list boxes are simple with a list of colours, as follows (they are both the same).

<ListBox Grid.Column="0" Margin="5"> 
    <ListBoxItem>Red</ListBoxItem> 
    <ListBoxItem>Yellow</ListBoxItem> 
    <ListBoxItem>Pink</ListBoxItem> 
    <ListBoxItem>Green</ListBoxItem> 
    <ListBoxItem>Orange</ListBoxItem> 
    <ListBoxItem>Purple</ListBoxItem> 
    <ListBoxItem>Blue</ListBoxItem> 
</ListBox> 

Now, this will just display 2 boring list so lets add a nice style in the app.xaml file for the left hand list as follows:

<Style x:Key="RoundedList" TargetType="{x:Type ListBoxItem}">
    <Setter Property="Width" Value="150" />
    <Setter Property="Margin" Value="5,2" />
    <Setter Property="Padding" Value="2" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ListBoxItem}">
                <Border x:Name="border" BorderThickness="1" BorderBrush="Silver" Background="AliceBlue" CornerRadius="5">
                    <ContentPresenter x:Name="Content" Margin="0" HorizontalAlignment="Center" TextBlock.Foreground="Black" VerticalAlignment="Stretch" />
                </Border>
                <ControlTemplate.Triggers>
                    <Trigger Property="Selector.IsSelected" Value="True">
                        <Setter TargetName="border" Property="Background" Value="Silver" />
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Adding the ItemContainerStyle ({StaticResource RoundedList}) to the list box will now give us something like the following:

image

As we can see we now have a nice styled list on the left which will change colour when we click on each item.  To demonstrate the skinning I am going to apply the same style to the right hand list but with a different name (so we now have 2 styles in the app.xaml file – RoundedList and RoundedList_skin).

So, for certain builds of this app we want the list buttons to shrink slightly when we click them but we only want it to do that for certain configurations.  We can add a new WPF resource dictionary to our project (Skin.xaml) and add the new style to it – it is important that the new style retains the name of the one it is replacing as we shall see shortly.

<Style x:Key="RoundedList_skin" TargetType="{x:Type ListBoxItem}">
    <Setter Property="Width" Value="150" />
    <Setter Property="Margin" Value="5,2" />
    <Setter Property="Padding" Value="2" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ListBoxItem}">
                <Border x:Name="border" BorderThickness="1" BorderBrush="Silver" Background="AliceBlue" CornerRadius="5">
                    <ContentPresenter x:Name="Content" Margin="0" HorizontalAlignment="Center" VerticalAlignment="Stretch" />
                </Border>
                <ControlTemplate.Triggers>
                    <Trigger Property="Selector.IsSelected" Value="True">
                        <Setter Property="RenderTransform">
                            <Setter.Value>
                                <ScaleTransform ScaleX="0.85" ScaleY="0.85"/>
                            </Setter.Value>
                        </Setter> 
                        <Setter Property="RenderTransformOrigin" Value="0.5, 0.5"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
       </Setter.Value>
    </Setter>
</Style>

The transform in this style simply makes the item look as though it had been pressed.

And now for the actual trick of making the new skin available to the app thus replacing the defaults in App.xaml.  I need a new Application configuration file (App.config) with an appSetting (skins) to hold the required skins for this application build.  This is a comma-separated list of resource dictionaries that we are going to include in this build.  In order to allow the new skins to override the existing ones we are required to move the current resources that we have defined into a dictionary of their own (this is due to the scoping rules of merged dictionaries in WPF – the primary dictionary will always take precedence).  I am simply going to move them into a new dictionary called OriginalSkin.xaml and include this in my skins appSetting which now looks like this.

<add key="skins" value="OriginalSkin.xaml,Skin.xaml"/>

We now have the two dictionaries ready to be loaded.  In App.xaml.cs we need a new method to load the skins from the config and this should be called from the OnStartup method of the app (its virtual so is available right there in app.xaml.cs to be overridden).

private void LoadSkins()
{
    string skins = ConfigurationManager.AppSettings["skins"];
    if (string.IsNullOrEmpty(skins))
    {
        return;
    }

    string[] resources = skins.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
    foreach (string resource in resources)
    {
        ResourceDictionary dictionary = new ResourceDictionary();
        dictionary.Source = new Uri(resource, UriKind.Relative);
        this.Resources.MergedDictionaries.Add(dictionary);
    }
}

This code loops through the skins in the appSetting and adds them as merged dictionaries.  The beauty of this is that merged dictionaries are read in the order that they are added so the latter dictionaries will override the earlier ones resulting in our newly minted RoundedList_skin being called instead of the original one but the original version of RoundedList is still available for the other ListBox:

image

We can now add any number of skins to this configuration but we will only load the ones listed in the App.config file – this now makes the app very extensible and can be changed at the drop of a hat.

The sample application that I used for this post can be found here

MVVM – The ‘Other’ ViewModel

Something that we regularly do at work is add additional properties to business objects that are only for use on the client (isDirty, HasChanged …etc).  We have always just added these to the business object directly and thought nothing of it, but after listening to a Hanselminutes interview with Laurent Bugnion I discovered the ‘other’ use for a ViewModel – wrapping client side business objects to expose new properties.  This is also useful in removing the overhead of viewing objects via a converter.

I have recently started looking at ASP.NET MVC as well and the way to pass things between controller and view is by using a ViewModel class.  This overload of the term had not translated into being useable in MVVM as well so what follows is a short, simple example of using a ViewModel to better model some data to fit a view.

Lets say we have a meeting object that we have extracted from a service and it is now ready to display on our client.  This business object has no real relation to them ORM version of the same object if we are correctly differentiating between them and client facing business objects so it has no in-built tracking to determine if it has changed and we don’t want to send it back to the service for updating if nothing has changed.  Our class looks like this.

public class Meeting
{
    public Meeting()
    {

    }
    public string Subject { get; set; }
    public string Location { get; set; }
    public DateTime StartTime { get; set; }
    public List<Person> Attendees { get; set; }
}

This is a very simple class to define our meeting but it has no way of knowing if it has changed and also the StartTime property is stored on the server as UTC but the client could be anywhere.

 

Taking the latter problem first you may be tempted to bind directly to the StartTime property of this object and use a converter to convert to the appropriate time zone based on the user culture (as I have done many times).  As for the problem with a meeting change, there has to be some way of telling an object that it has changed.  Both of these problems can be solved with a MeetingViewModel.  This is a VM that follows the decorator pattern and could be implemented as follows:

public class MeetingViewModel
    {
        private Meeting inner;
        public MeetingViewModel(Meeting m)
        {
            inner = m;
        }

        public Meeting Inner
        {
            get
            {
                return inner;
            }
        }

        public string Location
        {
            get
            {
                return inner.Location;
            }
            set
            {
                inner.Location = value;
            }
        }
        public DateTime StartTime
        {
            get
            {
                return inner.StartTime;
            }
            set
            {
                inner.StartTime = value;
            }
        }
        public List<Person> Attendees
        {
            get
            {
                return inner.Attendees;
            }
            set
            {
                inner.Attendees = value;
            }
        }

        public DateTime LocalStartTime
        {
            get
            {
                return inner.StartTime.ToLocalTime();
            }
            set
            {
                inner.StartTime = value.ToUniversalTime();
            }
        }

        public bool IsDirty { get; set; }
    }

Here we now have a nice property that sorts out the StartTime into a local time for us and a property that determines if this object has changed.  In your VM that controls your view you now operate on an object of type MeetingViewModel and all bindings are to this object.  When it comes time to save the object you simply need to check if you have set the dirty flag and if so extract the internal Meeting object using the get-only property and send it back to the service.

 

This is also a nice way of working with business objects that you have no control over such as from an external web service or third party library.  Once you start to understand the power of this approach over simply using converters you will find yourself writing VM’s for all of your business objects that you need to modify slightly on the client side when you need properties like the above or other bits of information like calculated properties.

Binding and styling text to a RichTextBox in WPF

The RichTextBox in WPF is a great tool for dealing with text that needs to be styled (such as syntax highlighting) but its not so great when it comes to allowing us to bind and edit text on the fly.

I got a feature request from our product manager to change the colour of certain text within a TextBox to match a legacy application.  It turns out it is not as straight forward as you might expect.

We have text in an SQL database like this:

this is a title:.\r\n\r\nThis is a normal line\r\n\r\nthis is another title:.\r\n

You can see that the titles end with “:.” so all we need to do is pull out these lines and make them (in my case) blue.

The problem is that this text is on an object that my previous TextBox was able to bind its Text property to with ease, but the RichTextBox has no text property as it displays a flow document. OK, I thought, I will just bind the text to the document as follows:

<RichTextBox IsReadOnly=”True” Document=”{Binding ElementName=ViewType, Path=SelectedItem.Tag />

This doesn’t work because the Document property is not a Dependency Property and therefore can not be bound to.  So BindableRichTextBox here I come.  I created a very simple control so that I could bind to the Document property.  In doing this I discovered that the Document property expects a FlowDocument as its content so I had to convert my text string to a flow document with the relevant parts highlighted.  I used a converter to spit out the FlowDocument with the correctly formatted text on a per line basis


public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
    FlowDocument doc = new FlowDocument();

    string s = value as string;
    if (s != null)
    {
        using (StringReader reader = new StringReader(s))
        {
            string newLine;
            while ((newLine = reader.ReadLine()) != null)
            {
                Paragraph paragraph = null;
                if (newLine.EndsWith(":."))
                {
                    paragraph = new Paragraph(new Run(newLine.Replace(":.", string.Empty)));
                    paragraph.Foreground = new SolidColorBrush(Colors.Blue);
                    paragraph.FontWeight = FontWeights.Bold;
                }
                else
                {
                    paragraph = new Paragraph(new Run(newLine));
                }

                doc.Blocks.Add(paragraph);
            }
        }
    }

    return doc;
}

This simply takes the string and reads it line by line.  If we have the desired characters at the end of a line (“:.”) then we make the line blue and bold and remove the characters, otherwise we just add the text.  Each line is added as a paragraph so to reduce the space between each one I added the following to the control declaration in the XAML

<RichTextBox.Resources>

<Style TargetType=”{x:Type Paragraph}”>

<Setter Property=”Margin” Value=”0″/>

</Style>

</RichTextBox.Resources>

This simply removes the the margin from each paragraph.

The final part of the puzzle is the control that allows binding this is a simple case of adding a dependency property onto a new control that inherits from RichTextBox

public class BindableRichTextBox : RichTextBox
{
    public static readonly DependencyProperty DocumentProperty = DependencyProperty.Register("Document", typeof(FlowDocument), typeof(BindableRichTextBox), new FrameworkPropertyMetadata(null, new PropertyChangedCallback(OnDocumentChanged)));

    public new FlowDocument Document
    {
        get
        {
            return (FlowDocument)this.GetValue(DocumentProperty);
        }

        set
        {
            this.SetValue(DocumentProperty, value);
        }
    }

    public static void OnDocumentChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
    {
        RichTextBox rtb = (RichTextBox)obj;
        rtb.Document = (FlowDocument)args.NewValue;
    }
}

I hope you find a use for this – I simply need it written down somewhere so I don’t forget!