If you are trying to write an application in WPF that separates the UI from the underlying business logic (otherwise known as Model-View patterns), you may have noticed that some of the features in WPF don't always make that easy.

Commands are an example of this. Although defining and using a command in Xaml is fairly straightforward, you are currently pushed to declare the handlers that do the work in the code-behind, going against the mantra of separation, and making harder to get some of the benefits of encapsulation.

There's a few options you might consider:

  • Command Binding in Xaml, Handlers in code-behind: By implement the business logic somewhere else than your view, you can always re-direct to it in the code-behind methods. (Simplest)
  • Command Binding in Code-Behind: Creating the binding through code allows you to avoid having to implement handlers in code-behind. An example of how to do that can be found on Richard Griffin's blog. (Less Declarative)
  • Command Binding in Xaml using Attached Properties: The idea is to use an attached property in Xaml to create the command binding. I'll give credit to Dan Crevier for coming up with the idea, which you can read in more detail here. (Harder)

 

Another option I didn't list above is using the WPF Composite Application Library (CAL), which has support for Delegate Commands. It's somewhat more heavy-weight, primarily geared towards enterprise application development, so I'll likely create a separate post on the topic.