views:

39

answers:

2

I'm putting a WPF application together in which I have an image control which I want to bind a custom command object to from my view model that will execute when the image is clicked. I have exposed the command object from my view model and just need to bind it to the image control.

Is it possible to bind this command object to an image control? If so any advice would be appreciated.

+4  A: 

You need to put the image in a button, and bind the button to the command:

<Button Command="{Binding MyCommand}">
    <Image Source="myImage.png" />
</Button>

If you don't want the standard button chrome, just change the template of the button with something like that:

<ControlTemplate x:Key="tplFlatButton" TargetType="{x:Type Button}">
    <Border Width="{TemplateBinding Width}"
            Height="{TemplateBinding Height}"
            Background="{TemplateBinding Background}"
            BorderBrush="{TemplateBinding BorderBrush}"
            BorderThickness="{TemplateBinding BorderThickness}">
        <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                          VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                          TextElement.Foreground="{TemplateBinding Foreground}"
                          TextElement.FontFamily="{TemplateBinding FontFamily}"
                          TextElement.FontSize="{TemplateBinding FontSize}"
                          TextElement.FontStretch="{TemplateBinding FontStretch}"
                          TextElement.FontWeight="{TemplateBinding FontWeight}"/>
    </Border>
</ControlTemplate>

Note that you will also need to change other properties to override the default button style, otherwise the template above will use the default button background and border:

<Style x:Key="stlFlatButton" TargetType="{x:Type Button}">
    <Setter Property="Background" Value="{x:Null}" />
    <Setter Property="BorderBrush" Value="{x:Null}" />
    <Setter Property="BorderThickness" Value="0" />
    <Setter Property="Template" Value="{StaticResource tplFlatButton}" />
</Style>
Thomas Levesque
@Thomas: Thanks a million, worked a treat.
David
A: 

It can be simpler to avoid using a button and use a Hyperlink instead:

<TextBlock DockPanel.Dock="Top">
   <Hyperlink Command="{Binding SomeCommand}">
      <Image Source="image.png" />
   </Hyperlink>
</TextBlock>

Note that this will render the hyperlink with the default text decoration, so you'll want to add a style that removes that - putting this in the resource dictionary of the containing element will do the trick:

<Style x:Key={x:Type Hyperlink}" TargetType="Hyperlink">
   <Setter Property="TextDecorations"
           Value="{x:Null}" />
   </Style>
</Style>
Robert Rossney