views:

171

answers:

2

I have a ControlTemplate that I'm using to change the appearance and behavior of several Buttons. I only want part of the Button to be clickable and to execute the bound Command, so I added a Button within the ControlTemplate and bound it to the template's Command property.

The problem I'm having is that since I am defining the Command binding on the templated Button, it executes regardless of which part of the template I am clicking.

In the below example you can click the Border and execute the Command. How do I change it so that the Command only executes when you click the Button within the template?

<ControlTemplate x:Key="ButtonControlTemplate" TargetType="{x:Type Button}">
    <Border BorderThickness="10" BorderBrush="Black">
        <Button
            Command="{TemplateBinding Command}"
            CommandParameter="{TemplateBinding CommandParameter}" >
            <ContentPresenter Content="{TemplateBinding Content}" />
        </Button>
    </Border>
</ControlTemplate>

...

<Button
    Command="{Binding Path=SomeViewmodelCommand}"
    CommandParameter="{Binding Path=SomeViewmodelCommandParameter}"
    Content="Click"
    Template="{StaticResource ButtonControlTemplate}" />

I don't think I can template a different element (like the Border) because I still need to pass in the Command somehow, and attached properties would still give me the same behavior.

+1  A: 

It's a dirty hack, but you can bind the inner button's Command property to the templated parent's Tag property instead. That way you 'hide' the command from the containing button, but the inner button secretly knows how to get to it.

You can leave the CommandParameter as is, since it has no effect by itself.

Aviad P.
+1  A: 

Another alternative is to re-template another control, such as Border and use a RoutedCommand on the Button inside the template. You could bind it to one of the built-in RoutedCommands, such as ApplicationCommands.Save and in the XAML for the containing control, add a CommandBinding for that particular command. Let me know if some code would be helpful.

jgraves