View-Only Actions in WPF

About a year ago, I answered a question about WPF bindings on stackoverflow.com. The goal was to bind a button to the “close window” action. All answers involved writing some C# code to actually close the window, which is a rather cumbersome approach.

Recently, I was asked about a very similar problem at the project I’m currently working on, so I thought it may be worth to share an elegant solution to this, using only XAML code.

Problem: How do you bind input events to method calls on other view elements?

As an example I will use the stackoverflow case again, binding a button to the “close window” action.

The key concept is to use Event Triggers and Call Method Actions, which leads to the following, very concise fragment of XAML code:

<Window x:Name="window"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
   xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions">
  <Button Content="Close">
    <i:Interaction.Triggers>
      <i:EventTrigger EventName="Click">
        <ei:CallMethodAction
            TargetObject="{Binding ElementName=window}"
            MethodName="Close"/>
      </i:EventTrigger>
    </i:Interaction.Triggers>
  </Button>
</Window>

In Expression Blend

If you are creating your views in Expression Blend, this can actually be achieved solely using drag-and-drop:

  1. Create a button
  2. Name your window
  3. Grab a “Call Method Action” behavior from the controls toolbox and drop it over the button
  4. Specify the Target Object and Method Name properties

Or in Visual Studio

If you don’t have Blend installed, you can of course manually create the XAML code above, but first you need to get hold of the assemblies that contain the EventTrigger and CallMethodAction.

As you can guess from the namespaces, they are shipped with Expression Blend. You can however use them even if you don’t have Blend itself, because they can be downloaded as part of the Expression Blend SDK, which is freely available for download:

http://www.microsoft.com/download/en/details.aspx?id=10801

Get them and then get rid of ugly code-behind hacks!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>