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.
nice 🙂