Colin Eberhardt's Adventures in .NET

MVVM Charting – Binding Multiple Series to a Visiblox Chart

March 6th, 2011

This post describes a method of using attached properties to bind a ViewModel which contains multiple data series to a Visiblox chart without any code-behind.




The Visiblox chart supports databinding in both WPF and Silverlight, where the X and Y values for each datapoint are bound to properties on an underlying model. However, there is no interface for binding a varying number of series (i.e a collection of collections). The solution provided here is similar to the one which Jeremiah Morrill published for binding multiple series to the Silverlight Toolkit charts, but with a few added extras, like series title binding and series type selection.

The solution is surprisingly simple, so I am going to dive straight into the code (note, I have collapsed the verbose attached property definitions so that just the interesting bits are shown below!)

public static class MultiSeries
{
  #region TitlePath attached property
 
  #region ItemsSourcePath attached property
 
  #region XValuePath attached property
 
  #region YValuePath attached property
 
  #region ChartTypeProvider attached property
 
  #region Source attached property
 
  /// <summary>
  /// Handles property changed event for the Source property
  /// </summary>
  private static void OnSourcePropertyChanged(DependencyObject d,
                                                      DependencyPropertyChangedEventArgs e)
  {
    Chart targetChart = d as Chart;
 
    SynchroniseChartWithSource(targetChart);
 
    IEnumerable Source = GetSource(targetChart);
    INotifyCollectionChanged incc = Source as INotifyCollectionChanged;
    if (incc != null)
    {
      incc.CollectionChanged += (s, e2) => SynchroniseChartWithSource(targetChart);
    }
 
  }
 
  private static void SynchroniseChartWithSource(Chart chart)
  {
    chart.Series.Clear();
 
    IEnumerable Source = GetSource(chart);
    if (Source == null)
      return;
 
    // iterate over each source series
    foreach (object seriesDataSource in Source)
    {
      // create a visiblox chart series
      IChartSeries chartSeries = GetChartTypeProvider(chart).GetSeries(seriesDataSource);
 
      // resolve the ItemsSource path (if present).
      var itemsSourcePath = GetItemsSourcePath(chart);
      IEnumerable itemsSource = null;
      if (!string.IsNullOrEmpty(itemsSourcePath))
      {
        itemsSource = seriesDataSource.GetPropertyValue<IEnumerable>(itemsSourcePath);
      }
      else
      {
        // if not present, assume this is a collection of collections
        itemsSource = seriesDataSource as IEnumerable;
      }
 
      // resolve the title path
      var titlePath = GetTitlePath(chart);
      var seriesTitle = "";
      if (!string.IsNullOrEmpty(titlePath))
      {
        seriesTitle = seriesDataSource.GetPropertyValue<string>(titlePath);
      }
 
      // create the data series, and add to the chart.
      chartSeries.DataSeries = new BindableDataSeries()
      {
        XValueBinding = new Binding(GetXValuePath(chart)),
        YValueBinding = new Binding(GetYValuePath(chart)),
        ItemsSource = itemsSource,
        Title = seriesTitle
      };
      chart.Series.Add(chartSeries);
    }
  }
 
  /// <summary>
  /// Gets the value of the named property.
  /// </summary>
  public static T GetPropertyValue<T>(this object source, string propertyName)
  {
    var property = source.GetType().GetProperty(propertyName);
    if (property == null)
    {
      throw new ArgumentException(string.Format("The property {0} does not exist on the type {1}",
        propertyName, source.GetType()));
    }
    return (T)property.GetValue(source, null);
  }
}

The MultiSeries class defines a number of attached properties, Source is used to bind the collection of series, this property must be an IEnumerable, but if it also implements INotifyCollectionChanged, we handle the CollectionChanged events to update the chart (adding or removing series). The optional ItemsSourcePath is used to provide the path to the nested collection (more on this later) and the optional TitlePath binds the chart title. The XValuePath and YValuePath properties are used to bind the X & Y values of the chart. Finally, ChartTypeProvider is used to determine the series type (Line, Bar, Column …) for each of the bound series. The provider must implement the following interface:

/// <summary>
/// An interface for providing Visiblox chart series.
/// </summary>
public interface IChartTypeProvider
{
  /// <summary>
  /// Creates a suitable chart series for the given data
  /// </summary>
  IChartSeries GetSeries(object boundObject);
}

In most MVVM chart binding applications, you will probably want all the series to have the same type. To achieve this, we can create a simple implementation of this interface which always returns the same chart type:

/// <summary>
/// A ChartTypeProvider that always returns the Visiblox series
/// type that was supplied in the constructor.
/// </summary>
public class DefaultChartTypeProvider : IChartTypeProvider
{
  private Type _seriesType;
 
  public DefaultChartTypeProvider(Type seriesType)
  {
    _seriesType = seriesType;
  }
 
  public IChartSeries GetSeries(object boundObject)
  {
    var ctr = _seriesType.GetConstructor(new Type[] { });
    return (IChartSeries)ctr.Invoke(new object[] { });
  }
}

In order to simplify the usage of this provider in XAML, we can provide a type converter which allows us to specify the required series type as a string, e.g. ChartTypeProvider="LineSeries", this makes use of the same framework mechanisms that allow you to specify a Fill as a string, e.g. Fill="Red", where the result will be to create the following, new SolidColorBrush() { Color = Colors.Red }, a suitable type converter is shown below:

[TypeConverter(typeof(StringToChartTypeProvider))]
public interface IChartTypeProvider
{
   ...
}
 
/// <summary>
/// A type converter that converts a string into a FixedChartTypeProvider. For example
/// "LineSeries" is converted into a FixedChartTypeProvider which
/// always returns Visblox.Chart.LineSeries instances
/// </summary>
public class StringToChartTypeProvider : TypeConverter
{
  public override object ConvertFrom(ITypeDescriptorContext context,
    CultureInfo culture, object value)
  {
    if (value is string)
    {
      var visibloxAssembly = typeof(Chart).Assembly;
      var seriesType = visibloxAssembly.GetType("Visiblox.Charts." + value.ToString());
      return new DefaultChartTypeProvider(seriesType);
    }
    return base.ConvertFrom(context, culture, value);
  }
 
  public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
  {
    if (sourceType == typeof(string))
      return true;
 
    return base.CanConvertFrom(context, sourceType);
  }
}

A Simple Example

We’ll start with a simple example, binding a collection of collections, in this case the harmonic vibrations of a string. The series are created as follows:

  public MainPage()
  {
    InitializeComponent();
 
    // a collection of collections
    var harmonics = new List<List<Point>>();
 
    // plot each harmonic frequency
    for (int frequency = 1; frequency < 5 ;frequency++)
    {
      // create the upper and lower component
      var upperHarmonic = new List<Point>();
      var lowerHarmonic = new List<Point>();
      for (double phase = 0; phase < Math.PI; phase+= (Math.PI / 100))
      {
        upperHarmonic.Add(new Point(phase, Math.Sin(phase * frequency) + frequency * 2.5));
        lowerHarmonic.Add(new Point(phase, Math.Sin(phase * frequency + Math.PI) + frequency * 2.5));
      }
 
      // add each to the collection
      harmonics.Add(upperHarmonic);
      harmonics.Add(lowerHarmonic);
    }
 
    this.DataContext = harmonics;      
  }
}

We can then use the attached properties defined above to bind this data to the chart. Note, because the bound data is a collection of collections (rather than a collection of items which expose the child collection via a property), the optional ItemsSourcePath is not required:

<UserControl.Resources>
  <vis:Palette x:Key="palette">
    <Style TargetType="vis:LineSeries">
      <Setter Property="LineStroke" Value="Black"/>
    </Style>
    <Style TargetType="vis:LineSeries">
      <Setter Property="LineStroke" Value="Black"/>
    </Style>
    <Style TargetType="vis:LineSeries">
      <Setter Property="LineStroke" Value="Red"/>
    </Style>
    <Style TargetType="vis:LineSeries">
      <Setter Property="LineStroke" Value="Red"/>
    </Style>
  </vis:Palette>
</UserControl.Resources>
 
<Grid x:Name="LayoutRoot" Background="White">
  <vis:Chart x:Name="chart"
              Palette="{StaticResource palette}"
              LegendVisibility="Collapsed"
              Title="Modes of a vibrating string"               
              local:MultiSeries.ChartTypeProvider="LineSeries"
              local:MultiSeries.XValuePath="X"
              local:MultiSeries.YValuePath="Y"
              local:MultiSeries.Source="{Binding}"/>
</Grid>

Whilst the MultiSeries class allows you to specify the chart type via ChartTypeProvider, it does not provide a mechanism for styling the various series which it produces based on the supplied Source. However, styling can be achieved using the chart’s Palette, which is a collection of Style instances which are applied to the series in order.

The resulting chart is shown below:

A More Complex MVVM Example

In this example, rather than binding a collection of collections, the following model is bound:

CompanySalesViewModel has a collection of SalesTeamViewModel instances, each of these has a name, TeamName, and a collection of SalesInRegionViewModel instances. Note, SalesTeamViewModel also has a string indexer property which will be used to bind this model to a DataGrid.

A custom ChartTypeProvider is used so that we can select chart types based on the bound SalesTeamViewModel:

public class SalesTypeProvider : IChartTypeProvider
{
  public IChartSeries GetSeries(object boundObject)
  {
    var viewModel = boundObject as SalesTeamViewModel;
    if (viewModel.TeamName == "Target")
      return new LineSeries();
    else
      return new ColumnSeries();
  }
}

The view model is bound to a chart and is also bound to a DataGrid as follows. Note this time the ItemsSourcePath is used to bind the TeamSales property of each SalesTeamViewModel:

<UserControl.Resources>
  <DropShadowEffect x:Key="shadow" Opacity="0.3"/>
 
  <Style TargetType="UIElement" x:Key="collapsedStyle">
    <Setter Property="Visibility" Value="Collapsed"/>
  </Style>
 
  <!-- a base style for column series -->
  <Style TargetType="vis:ColumnSeries" x:Key="columnBaseStyle">
    <Setter Property="PointStroke" Value="White"/>
    <Setter Property="PointStrokeThickness" Value="0.5"/>
    <Setter Property="Effect" Value="{StaticResource shadow}"/>
  </Style>
 
  <!-- a Visiblox palette -->
  <vis:Palette x:Key="palette">
    <Style TargetType="vis:ColumnSeries"
            BasedOn="{StaticResource columnBaseStyle}">
      <Setter Property="PointFill" Value="#4f81bd"/>
    </Style>
    <Style TargetType="vis:ColumnSeries"
            BasedOn="{StaticResource columnBaseStyle}">
      <Setter Property="PointFill" Value="#c0504d"/>
    </Style>
    <Style TargetType="vis:ColumnSeries"
            BasedOn="{StaticResource columnBaseStyle}">
      <Setter Property="PointFill" Value="#9bbb59"/>
    </Style>
    <Style TargetType="vis:LineSeries">
      <Setter Property="LineStroke" Value="#8064a2"/>
      <Setter Property="LineStrokeThickness" Value="4"/>
      <Setter Property="Effect" Value="{StaticResource shadow}"/>
    </Style>
  </vis:Palette>
</UserControl.Resources>
 
<Grid x:Name="LayoutRoot" Background="White"
      util:GridUtils.RowDefinitions=",Auto">
  <vis:Chart x:Name="chart"
              Title="Global Team Sales"
              LegendTitle="Team"
              Palette="{StaticResource palette}"
              local:MultiSeries.XValuePath="Region"
              local:MultiSeries.YValuePath="Sales"
              local:MultiSeries.TitlePath="TeamName"
              local:MultiSeries.ItemsSourcePath="TeamSales"
              local:MultiSeries.Source="{Binding SalesTeams}">
    <local:MultiSeries.ChartTypeProvider>
      <local:SalesTypeProvider/>
    </local:MultiSeries.ChartTypeProvider>
    <vis:Chart.XAxis>
      <vis:CategoryAxis GridlineStyle="{StaticResource collapsedStyle}" />
    </vis:Chart.XAxis>
  </vis:Chart>
 
  <sdk:DataGrid Grid.Row="1"
                ItemsSource="{Binding SalesTeams}"
                AutoGenerateColumns="False">
    <sdk:DataGrid.Columns>
      <sdk:DataGridTextColumn Binding="{Binding TeamName}"
                              Header="Team"
                              IsReadOnly="True"/>
      <sdk:DataGridTextColumn Binding="{Binding [US]}"
                              Header="US"/>
      <sdk:DataGridTextColumn Binding="{Binding [UK]}"
                              Header="UK"/>
      <sdk:DataGridTextColumn Binding="{Binding [Germany]}"
                              Header="Germany"/>
      <sdk:DataGridTextColumn Binding="{Binding [Japan]}"
                              Header="Japan"/>
    </sdk:DataGrid.Columns>
  </sdk:DataGrid>
</Grid>

The result is show below, note that updating the data in the grid causes the chart to update accordingly:

You can download the full sourcecode for this example: VisibloxMultiSeriesBinding.zip

Regards, Colin E.

The mini-ViewModel pattern

August 7th, 2009

The construction of a ViewModel is often seen as the standard technique for solving binding problems within WPF and Silverlight. However, the addition of a ViewModel adds complexity to your code. This post describes an alternative method where a mini-ViewModel is applied directly to the problem areas in the view, leaving the rest to use simpler, straightforward binding to business objects.

One of the features of WPF / Silverlight that appealed to me immediately when I started to learn it was the flexibility of the binding framework. The concepts of DataContext inheritence and flexibility of the value converters results in a lot less glue-code, which makes me a happy developer! However, it does not take long before you start finding examples that just dont fit with the framework and things start to get just little more complex. This blog post describes one such example.

The example used in this blog post is of a very simple application which displays a business card. The business object rendered by the application, ContactDetails, has a number of simple CLR properties. Constructing a UI for viewing this business object is very easy, simply create an instance of this object (in a real application this object might come from a database or web service) and set it as the DataContext of the view:

public Page()
{
    InitializeComponent();
 
    ContactDetails details = new ContactDetails()
    {
        Company = "Scott Logic Ltd.",
        Email = "ceberhardt@scottlogic.co.uk",
        URL = "http://www.scottlogic.co.uk",
        Country = "UK",
        FullName = "Colin Eberhardt",
        PhoneNumber = 4408452241930
    };
 
    this.DataContext = details;
}

We then create some simple XAML with UI elements that bind to the various propeties of our object …

<Grid x:Name="LayoutRoot" Background="White">
    <Border BorderBrush="LightGray" Background="White"  BorderThickness="1.5" CornerRadius="20"
        VerticalAlignment="Center" HorizontalAlignment="Center">
        <Border Margin="5" BorderBrush="LightGray" BorderThickness="1.5" CornerRadius="15">
            <Border.Background>
                <ImageBrush>
                    <ImageBrush.ImageSource>
                        <BitmapImage UriSource="back.jpg" />
                    </ImageBrush.ImageSource>
                </ImageBrush>
            </Border.Background>
 
            <StackPanel Orientation="Vertical" Margin="10">
                <TextBlock Text="{Binding FullName}"
                           FontSize="15"
                           FontWeight="Bold" />
                <Rectangle Stroke="DarkGray" HorizontalAlignment="Stretch"
                           StrokeThickness="0.5" Height="1"/>
                <TextBlock Text="{Binding Company}" Margin="0,10,0,0"/>
                <StackPanel Orientation="Horizontal" >
                    <TextBlock Text="e: "/>
                    <TextBlock Text="{Binding Email}" />
                </StackPanel>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="w: "/>
                    <HyperlinkButton Content="{Binding URL}"/>
                </StackPanel>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="p: "/>
                    <TextBlock Text="{Binding PhoneNumber}"/>
                </StackPanel>
            </StackPanel>
        </Border>
    </Border>
</Grid>

And we get a lovely looking business card:

card

One problem with the above example is the phone number, outputting the raw number ’4408452241930′ is not terribly readable, besides phone numbers have a standard format, in this case, the phone number would be represented as ‘+44 (0)845 2241930′. Also, let’s make the problem more interesting; you might want to highlight the international dialing code in a different colour, or, if the application is being used by a UK client, display the number in a local format without the international code ’0845 2241930′. So just how do we achieve this?

In order to break the number up into different blocks of text, with different colours (i.e. styles), we need to modify our view to have multiple TextBlocks mapped to the PhoneNumber property of our business object. The part of our view which renders the phone number is modified as follows:

<StackPanel Orientation="Horizontal">
    <TextBlock Text="p: "/>
    <TextBlock Text="... country code ..." Foreground="LightGray"/>
    <TextBlock Text="... area code ..."/>
    <TextBlock Text="... local number ..."/>
</StackPanel>

But just how exactly do we bind the properties of these business objects?

One approach would be to use a value converter for each binding in order to extract the required part of the number, for example a CountryCodeValueConverter could be implemented which grabs the first 2 digits of the number. However, this approach is a little inelligent in that it fragments our logic into a number of separate classes, furthermore, if we want country specific formatting this requires the use of multibindings, which can be rather cumbersome if over-used (for a Silverlight implementation of multi bindings see my blog post from earlier this year).

Another approach which is often used to tackle tricky binding problems is the use of the Model-View-ViewModel (MVVM) pattern. With this pattern, our ContactDetails object is the Model, we construct a ViewModel which is a UI-oriented abstraction of the Model and it is this which we bind to the View. WPF guru Josh Smith describes MVVM as “a value converter on steroids” in order to highlight the usefulness of the pattern in this context.

The basic approach used here is to bind your View to a ViewModel rather than binding it to the business object directly. The ViewModel is specific to the view and wraps the business object (i.e. Model), forwarding the property values and change notification to the View. This extra layer allows us to supplement the properties of the Model object, adding new computed properties which are specific to the View. In this case, these computed properties can be used to expose ‘country code’, ‘area code’, etc… to our View.

(This is a common pattern so I am not going to reproduce the code required here, however, if you are interested, the attached sourcecode accompanying this article contains a regular ViewModel version as well as a mini-ViewModel implementation)

Whilst this approach works, my issue with it is that it adds quite a bit of boiler-plate code for wrapping properties, forwarding events etc … The removal of this glue-code is the exact reason that I like WPF/Silverlight so much! The MVVM pattern is primarily for supporting the designer-developer paradigm and enabling unit testing of UI applications, in my opinion the use of MVVM for anything else is just plain wrong!

So, how can we solve the problem of providing a nicely formatted phone number without the pain of bashing out line-after-line line of boiler-plate MVVM code? My solution to the problem isn’t to dispose of the MVVM pattern altogether, rather, it is to localise its usage to just the problem area. The first step is to encapsulate the rendering of the phone number as a user control:

...
<StackPanel Orientation="Horizontal">
    <TextBlock Text="p: "/>
    <local:PhoneNumberControl Number="{Binding PhoneNumber}" />
</StackPanel>
...

… which probably makes sense anyway from a perspective of good design and code re-use!

Now that we have moved the phone number property within the PhoneNumberControl we have isolated the problem and can deal with it locally. We can create a PhoneNumberControlViewModel which splits the phone number up into its various components and bind this to the PhoneNumberControl.

The control’s ViewModel looks something like this:

public class PhoneNumberControlViewModel : INotifyPropertyChanged
{
    public PhoneNumberControlViewModel(PhoneNumberControl ctrl)
    {
        _ctrl = ctrl;
        ComputeProperties();
 
        // listen to property changes in the control (we are interested
        // in just the Number property)
        _ctrl.PropertyChanged += Control_PropertyChanged;
    }
 
    private PhoneNumberControl _ctrl;
 
    private string _countryCodeText;
 
    private string _areaCodeText;
 
    private string _localNumberText;
 
    public string CountryCodeText
    {
        get { return _countryCodeText; }
        set { _countryCodeText = value; OnPropertyChanged("CountryCodeText");  }
    }
 
    public string AreaCodeText
    {
        get { return _areaCodeText; }
        set { _areaCodeText = value; OnPropertyChanged("AreaCodeText"); }
    }
 
    public string LocalNumberText
    {
        get { return _localNumberText; }
        set { _localNumberText = value; OnPropertyChanged("LocalNumberText"); }
    }
 
    private void Control_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        if (e.PropertyName == "Number" || e.PropertyName == "Country")
        {
            ComputeProperties();
        }
    }
 
    private void ComputeProperties()
    {
        string formattedNumber = _ctrl.Number.ToString();           
        CountryCodeText = "+" + formattedNumber.Substring(0, 2);
        AreaCodeText = " (" + formattedNumber.Substring(2, 1) + ")" + formattedNumber.Substring(3, 3);
        LocalNumberText = " " + formattedNumber.Substring(6);
    }
}

Note that here the ViewModel is ‘wrapping’ the PhoneNumberControl rather than an instance of some Business / Model object.

Now we just set our ViewModel as the DataContext for the View, as per the typical usage of this pattern:

public PhoneNumberControl()
{
    InitializeComponent();
 
    this.DataContext = new PhoneNumberControlViewModel(this);
}

… and it doesn’t work. If you try the above, you will find that the binding on the PhoneNumberControls Number property no longer works. So why is this? if you look back at where the PhoneNumberControl instance is defined in our business card’s XAML markup you see that its Number property is bound as follows:

<local:PhoneNumberControl Number="{Binding PhoneNumber}" />

The source of this binding is not explicitly set, so will default to using the DataContext of the PhoneNumberControl instance. However, we have just changed this DataContext in our constructor to something else … oops!

Solving this problem is actually quite simple, the PhoneNumberControl markup is as follows:

<UserControl x:Class="SLMiniViewModel.PhoneNumberControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <StackPanel x:Name="LayoutRoot" Orientation="Horizontal">
        <TextBlock Text="{Binding CountryCodeText}" Foreground="DarkGray"/>
        <TextBlock Text="{Binding AreaCodeText}"/>
        <TextBlock Text="{Binding LocalNumberText}"/>
    </StackPanel>
</UserControl>

If we modify our binding to the ViewModel as follows:

public PhoneNumberControl()
{
    InitializeComponent();
 
    LayoutRoot.DataContext = new PhoneNumberControlViewModel(this);
}

The subtle difference being that the ViewModel is now bound to the StackPanel which is the root of our visual tree within the control. This means that the PhoneNumberControl DataContext is still inherited from the business card and is our business object instance, the DataContext switch to the ViewModel is now neatly tucked just within the PhoneNumberControls visual tree, and it is this DataContext which our TextBlocks will inherit and bind to.

The result is that we can now use our mini-ViewModel embedded within the PhoneNumberControl to expose properties which are more amenable to binding to our View:

card2

Whilst this is a quite trivial example, in real-world applications, more complex examples where the data representation within the View is dependant on a number of properties are quite common. The source code accompanying this article extends the example a little further by making the formatting dependant on a second property of the business object. This is the sort of problem that would either push you towards multi-binding and numerous fragmented value converters, or a ViewModel.

In conclusion, the use of a mini-ViewModel which is embedded within a UserControl allows you to solve tricky binding problems without being weighed down by rolling out the MVVM pattern across your entire View. I am not against the MVVM pattern in itself, however I do firmly believe that it should only be used to solve the problems which it is was specifically designed for, i.e. supporting the designer-developer workflow and unit testing.

You can download the source-code for this article: SLMiniViewModel.zip – this project contains both MVVM and mini-MVVM implementations (count the number of lines in the ViewModel and contrast it with the mini-ViewModel).

Regards, Colin E.