简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM