Keep code behind clean

Download the sample code here

Last week, Marlon blogged about how to avoid adding command binding code to code-behind files. The idea is both simple and great, and allows you to keep your code behind nice and clean, and your layers separated. There’s only one (and yes, I’m being very anal here) thing that bugged me with it:

DataContext = new ViewModel(new SampleModel());

or, for that matter, "DataContext = anything", is still in the code behind class. This can easily be sorted out with some easy data binding and a supporting class.

First, create a class that will contain your controllers. You can create a factory class, or, simply a class which exposes your controllers. To demonstrate this, I'm only using a class with a static property:

public class ControllerProvider
{
    static ControllerProvider()
    {
        WindowController = new WindowController();
    }
    public static WindowController WindowController { get; private set; }
}

They don't get much simpler than that.

Next, bind the data context in your window:

<Window x:Class="Commands.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:Commands"
    DataContext="{x:Static local:ControllerProvider.WindowController}"
    Title="Commands" Height="200" Width="200">
    
    <Grid>        
        <Button Command="{Binding MyCommand}" Content="Execute command"/>
    </Grid>
</Window>

If we look at the codebehind for this, we have only the usual, Visual Studio generated code:

public partial class Window1 : Window

{

    public Window1()
    {
        InitializeComponent();
    }

}

Is this really worth it?

Yes. No. Maybe. I think it is, because I prefer to keep everything together. Besides, the idea is to keep the code behind as clean as possible. If people have to touch this class to add the data context, they may be tempted to add more stuff in there. Then again, it's very probably a matter of preferences.

Download the sample code here

About these ads

1 comment so far

  1. Marlon Grech on

    nice :)


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: