dimanche 1 février 2009

Convert "CLR method" to "ICommand" with just a XAML declaration


When we develop an application in WPF, we want to separate

  • UI in XAML stream
  • Data (in POCO object for example)
  • Links between UI and Data, interaction logic, etc. ...

for example, The Model/ModelView/View approach try do this.

One of the technical problem of this type of architecture is "How can i launch code from UI on ModelView ?"

If I want to launch a simple public method on underneath ModelView by XAML Declaration. It is not very easy.

MethodBinding approach illustrated in this application help you to do this just with declaration syntax, no more code is necessary

Thibaud Bouquely, France, February 2009.


Demo application is Downloaded here.

in Demo tabItem, you can launch this window. It's illustrate different usage of MethodBinding XAML declaration.



  • Create an object with a public method : the method must has no parameter or just one only

    Example :public void MyMethod(); on MyObject class
  • Push this object in DataContext of yours WPF controls

    Example :in Window's constructor : this.DataContext = new MyObject();
  • Declare link between a button and the previous public Method

    Example :<Button Command="{f:MethodBinding MyMethod}" >Clic on me
  • No more code :-)
    if you clic on the button, MyMethod() is launch on MyObject instance in DataContext of the button

Other functionality

  • If public target method has one parameter, CommandParameter on Button (or ICommandSource control) is too transfered
  • If Target object has a Read-only property named MyMethodCanExecute. It's return a boolean value, It used by MethodCommand to manage CanExecute aspect of ICommand system. (rq : target object must be a INotifyPropertyChanged or a DependencyObject/DependancyProperty to use correctly this fonctionnality)

TODO list :

  • Like BindingOperations static class of WPF, add Static method somewhere to create a MethodBinding by code
  • Improve the component ! I just try in this demos, not in real application