1

I am trying to make a reuseable button that has a Text followed by an X button (kind of like the close tab button on Google Chrome). I figured to do it something like this;

<Style x:Key="TestButtonStyle" TargetType="Button">
<Setter Property="Template">
    <Setter.Value>
        <ControlTemplate TargetType="{x:Type Button}">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto" />
                    <ColumnDefinition Width="Auto" />
                </Grid.ColumnDefinitions>
                <Label Margin ="3,5,3,5" BorderBrush="Black"  Grid.Column="0" />
                <Button Background="White" BorderBrush="White" Content="X" Grid.Column="1" />
            </Grid>
        </ControlTemplate>
    </Setter.Value>
</Setter>

<Button Style="{StaticResource TestButtonStyle}" Content="Testing" Padding="5" Margin="5"  />

The problem with this is that Button Click command works for the Label as well as the X Button. If I put the click command into the Style then every button will have the same click command. What is the best way to accomplish this?

1 Answers1

1

You can do TemplateBinding on button to inherit Command from parent template button.

<Button Background="White" BorderBrush="White" Content="X"
        Grid.Column="1" Command="{TemplateBinding Command}" />

This way you can set different commands on multiple buttons and re-use the same style:

<Button Style="{StaticResource TestButtonStyle}" Content="Testing"
        Padding="5" Margin="5" Command="{Binding TestCommand}"/>
Rohit Vats
  • 79,502
  • 12
  • 161
  • 185
  • Sorry to ask stupid questions but would would the code for "TestCommand" be like? –  Nov 18 '14 at 22:30
  • 1
    Have you read about ICommand and MVVM pattern? If not this link [here](http://stackoverflow.com/questions/1468791/wpf-icommand-mvvm-implementation) will help you understand it. Also google for it you will get tons of articles over net. – Rohit Vats Nov 18 '14 at 23:47