WPF: How to use BasedOn Style

3.4k Views Asked by At

I am new to WPF and I created the following simple style example. But it doesn't work properly and button's content doesn't show although I can still click on it. Can anyone tell me why it is broken?

<Window.Resources>
    <Style TargetType="{x:Type Button}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate>
                    <Border BorderBrush="Blue" 
                            BorderThickness="5" 
                            Background="Aqua"
                            Width="80"
                            Height="40">
                        <ContentPresenter></ContentPresenter>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

    <Style TargetType="Grid" x:Name="GridWithMarginStyle">
        <Setter Property="Margin" Value="12"></Setter>
    </Style>

</Window.Resources>
<StackPanel>
    <StackPanel.Resources>
        <Style TargetType="{x:Type Button}" BasedOn="{StaticResource {x:Type Button}}">
            <EventSetter Event="Button.Click" Handler="ButtonHandler" />
            <Setter Property="Background" Value="Red"></Setter>
            <Setter Property="Foreground" Value="White"></Setter>
        </Style>
    </StackPanel.Resources>
    <Button Name="OkBtn">OK</Button>
    <Button Name="CancelBtn" Click="CancelBtn_Click">Cancel</Button>
</StackPanel>
1

There are 1 best solutions below

2
Il Vic On

You are using the BasedOn property in the correct way. The problem is that your ContentPresenter is not binded to the control it renders (i.e. the button).

Just try to replace your ControlTemplate XAML with this one:

<ControlTemplate TargetType="{x:Type Button}">
    <Border BorderBrush="Blue" 
        BorderThickness="5" 
        Background="Aqua"
        Width="80"
        Height="40">
        <ContentPresenter Content="{TemplateBinding Content}" />
    </Border>
</ControlTemplate>

By using TemplateBinding you can bind the ContentPresenter to the Content property of your templated control.