user2891892
user2891892

Reputation:

WPF Button Template issue

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?

Upvotes: 1

Views: 46

Answers (1)

Rohit Vats
Rohit Vats

Reputation: 81253

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}"/>

Upvotes: 1

Related Questions