Sunday, 28 April 2013

WPF – Automatic ViewModel Resolution with Autofac

In MVVM there are lots of elaborate ways to make sure our XAML’s DataContext is correctly instantiated, and if you are using IoC then you should be letting the IoC container instantiate your viewmodel, which doesnt fit naturally into the XAML view paradigm.

An easy way to do this is to create a XAML resource that will resolve your ViewModel for you, via your IoC container.

Many MVVM frameworks offer this feature, but I wanted one to specifically work with Autofac, so I have written on for this purpose.

Here’s my data provider class

public class AutofacDataProvider : DependencyObject
    public static readonly DependencyProperty AutofacContainerProperty =
DependencyProperty.Register("AutofacContainer", typeof(IContainer), typeof(AutofacDataProvider), new PropertyMetadata(null, AutofacValuesChanged));

    public IContainer AutofacContainer
        get { return (IContainer)GetValue(AutofacContainerProperty); }
        set { SetValue(AutofacContainerProperty, value); }

    public static readonly DependencyProperty DataTypeNameProperty =
DependencyProperty.Register("DataTypeName", typeof(string), typeof(AutofacDataProvider), new PropertyMetadata(null, AutofacValuesChanged));

    public string DataTypeName
        get { return (string)GetValue(DataTypeNameProperty); }
        set { SetValue(DataTypeNameProperty, value); }

    private static readonly DependencyPropertyKey DataPropertyKey =
DependencyProperty.RegisterReadOnly("Data", typeof(object), typeof(AutofacDataProvider), new PropertyMetadata(null));

    public static readonly DependencyProperty DataProperty = DataPropertyKey.DependencyProperty;

    public object Data
        get { return (object)GetValue(DataProperty); }
        private set { SetValue(DataProperty, value); }

    private static void AutofacValuesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        var container = d.GetValue(AutofacContainerProperty) as IContainer;
        var typeName = d.GetValue(DataTypeNameProperty) as string;
        if (container == null || string.IsNullOrEmpty(typeName))
        var assembly = Assembly.GetExecutingAssembly();
        var type = assembly.GetType(typeName, false, true);
        if (type == null)
        var data = container.Resolve(type);
        d.SetValue(DataPropertyKey, data);

here's an example of a viewmodel I want to instantiate

public interface IMainViewModel
    string Name { get; set; }

public class MainViewModel : IMainViewModel, INotifyPropertyChanged
    private string name = "test name";
    public string Name
        get { return name; }
            name = value;

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
Here is where I wire up my container (you probably wouldn’t do it like this but this will do for our example)
public partial class App : Application
    public static IContainer Container { get; private set; }
    protected override void OnStartup(StartupEventArgs e)
        var builder = new ContainerBuilder();
        Container = builder.Build();

And here it is in my XAML

<Window x:Class="WpfApplication7.MainWindow"
        xmlns:x="" xmlns:app="clr-namespace:WpfApplication7"
        Title="MainWindow" Height="350" Width="525">
        <app:AutofacDataProvider DataTypeName="WpfApplication7.IMainViewModel" 
                                 AutofacContainer="{Binding Source={x:Static app:App.Container}}" 
                                 x:Key="DataSource" />
    <Grid DataContext="{Binding Source={StaticResource DataSource}, Path=Data}">
         <TextBlock Text="{Binding Name}" />

WPF – UI Performance – Maintain A Responsive UI With Asynchronous Bindings

I see a lot of developers writing code in their ViewModels that include a lot of data initialization logic that is performed eagerly, before the data is required. Most developers believe that lazy initialization is a tricky thing to achieve in MVVM, because it is difficult to know when exactly a XAML data binding will need the data in question.

Another area of confusion is the incorrect belief that property data that is lazily initialized needs to be marshaled onto the UI thread via the dispatcher. All of this misunderstanding and misinformation often leads to complex viewmodels that include a lot of complex asynchronous code as well as a heavy sprinkling of Dispatcher.BeginInvoke.

The answer is to use a little known property of the binding class called ‘IsAsync’

<DataGrid ItemsSource="{Binding TradeLegs, IsAsync=True}" />

Using IsAsync will mean that the ‘Get’ accessor on your property will be called asynchronously on a threadpool thread. When the data is available, the data will become available to the DataGrid automatically (no Dispatcher.BeginInvoke required for property changes – a common misunderstanding).

You can also combine this with progressive binding syntax to show ‘temporary’ data until the real data has been initialized.

WPF / MVVM – INotifyPropertyChanged – Not Required 95% Of The Time

Here’s another quickie

Question : Does your DataContext (or ViewModel if you’re doing MVVM) have to implement INotifyPropertyChanged in order to participate in XAML data binding and change synchronization (and all other goodies that follow)

Answer: Absolutely NOT !

Its an almost ubiquitous misunderstanding that unless you implement INotifyPropertyChanged on your class that is used as a binding source/target (DataContext) then your XAML wont work. Well it will – perfectly ! (well almost)

When you create a binding expression on XAML like this

<TextBox Text="{Binding Name}" Margin="5" Grid.Column="1" />

and your DataContext is a class like this (notice complete lack of INotifyPropertyChanged)
public class MyModel
    public string Name { get; set; }

what the XAML databinding subsystem does is in this example is add the ‘Name’ property of your DataContext class to a dictionary of values that it is tracking internally. Any time a binding expression changes this property, not only will the property setter be correctly set, but other usages of this property in your XAML will automatically get updated – which is 95% of the functionality that most implementations require.

The usual extras like value converter and update trigger work as you’d expect – e.g:

<TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}" Margin="5" Grid.Column="1" />
<TextBlock Text="{Binding Name, Converter={StaticResource TestValueConverter}}" Margin="5" Grid.Column="2" />

all works as expected.

So what's the 5% that doesn't work

Well, it simply wont work if you change a property directly in your class, rather than through the XAML, which makes sense – as how would the XAML know if you’ve been changing properties behind its back.

Saturday, 27 April 2013

WPF, MVVM and Background Threads – Common Misunderstandings

Just a quickie

You have MVVM and you have properties that notify via INotifyPropertyChanged.

Question : Do I have to use Dispatcher.BeginInvoke in order to change my bound properties in my ViewModel (i,e. when changing property values on background threads)

Answer: No. The Binding class will automatically marshal property changes via INotifyPropertyChanged onto the dispatcher for you automatically, and most importantly efficiently – by which I mean it evaluates the binding sources and targets and decide whether to marshal asynchronously or synchronously, and at what priority depending on other factors. This is half the reason for not bothering with MVVM frameworks like Caliburn, as they mostly perform tasks for you that don't actually need to be performed.

Except: Some poorly written 3rd party controls (no names mentioned….. ‘cough -  Infragistics’) assume that all data changes in the dependency system are always on the UI thread, and then tries to change dependency properties on the same thread (Dependency properties being changed directly MUST be updated on the UI thread). When using some of these controls you will have to marshal changes onto the UI thread just to support this buggy behavior.

FX Trading & Reactive Extensions (Rx) – Part 1 – Getting a Feel

My current contract is within FX trading, supporting a front-office team with high-performance, low latency applications.
We are currently doing a refactoring exercise around our currency pair data feeds, and we are looking to code better data consumption logic through implementations of IObsrevable<T> and IObserver<T>, courtesy of the Reactive Extensions library.
Form more information about Reactive Extensions, you should visit the Microsoft Reactive Extensions site ( or read Lee Campbell’s excellent (free) eBook (
Firstly I used LinqPad ( to play around with potential candidates for an approach.
Firstly, I thought I’d create a fake currency rate ticker and observe it.
var rand = new Random(Guid.NewGuid().GetHashCode()); 
var currencyTick = Observable.Interval(TimeSpan.FromMilliseconds(500))
    .Scan(new[] { 
            new { CurrencyPair = "AUD/GBP", Rate = 0.665000m}, 
            new { CurrencyPair = "USD/EUR", Rate = 0.775000m}, 
            new { CurrencyPair = "NOK/EUR", Rate = 0.130000m}
            }, (r,i) => 
        r.Select(s => new {CurrencyPair = s.CurrencyPair, 
                Rate = s.Rate + rand.Next(-100,100)/1000000m}).ToArray())
var disp = currencyTick.Subscribe(s => Console.WriteLine(string.Join("|",
    s.Select(i => string.Format("{0}:{1}",i.CurrencyPair, i.Rate.ToString())).ToArray())));

In the trivial code above I simply create a 500 millisecond tick, which gets pipelined into a scan (which takes a seed and then generates new values for every tick). The scan gets published to create a hot observable, which is finally pipelined into the refcount – which gives the observable automatic connect and disconnect behavior.

The end result is currency pair data ticking into our console on LinqPad.


OK, the result of this exercise is that we have a good idea that we want to publish our data feed through a observable, and the publishing and subscribing mechanisms are in-line with our desired end-result.

Step 2 – Get this to work in WPF

Thursday, 18 April 2013

Ramping Up The WPF and XAML Blogging

Ive decided to put a LOT more effort into my blogging, and will be creating regular posts on this blog that discuss advanced features and solutions in the .NET C#, WPF and XAML.

I hope you enjoy the posts Im going to write. My existing blog posts were imported from another blog provider, so may not be perfectly matched to this layout. I will be going through each one and 'making good'.

Feel free to contact me on my social networking profiles, or directly at me email address.

Dean Chalk

Visual Studio Debugging Tip – Change A Value Automatically With A Silent Breakpoint

Your debugging your code, and you have the need to change the value of a variable automatically without changing any code. Perhaps the URL of a production webservice is valid and cannot be changed in code, but you want to switch it to a development URL There are several ways of doing this, but only when the code execution has stopped at a breakpoint, and you need to change it every time manually.

Here is a good trick to set a ‘silent’ breakpoint (one that will never break the code), which will always change the value you want to change, for as long as the breakpoint is enabled.

Here’s an example:

class Program
static void Main(string[] args)
var productionUrl = "";



In this simple example above, we have a local variable holding the value of a production webservice URL, and we simply write it to the console


Just as you expected.

Now add a silent breakpoint like this, before the variable is used


as you can see, we’ve high-jacked the conditional breakpoint feature. This breakpoint will never stop code execution, BUT it will always change the value of a local variable, without changing any code.


Now, when we run our code we get this output


Which is a great way of changing state without changing any code. You can group and name breakpoints, and manage them in the breakpoints window – so they can be switched on and off in different scenarios.

A word of caution though, leave one of these breakpoints on accidentally, and you could have a head-scratcher on your hands that will take hours to work out.