WPF custom button

68 views Asked by At

I start to learn WPF and there is something that is still unclear for me:

i created new Style for button:

<!-- no border button style -->
<Style x:Key="NoBorderButton" TargetType="Button">
    <Setter Property="Foreground" Value="White" />
    <Setter Property="Background" Value="Transparent" />            
    <Setter Property="BorderBrush" Value="Transparent" />
    <Setter Property="BorderThickness" Value="0" />
    <Style.Triggers>
        <Trigger Property="Control.IsMouseOver" Value="true">
            <Setter Property="Control.FontSize" Value="18" />
        </Trigger>
        <Trigger Property="Control.IsMouseOver" Value="true" >
            <Setter Property="Foreground" Value="LightSkyBlue" />
        </Trigger>
        <Trigger Property="Control.IsMouseOver" Value="false" >
            <Setter Property="Foreground" Value="White" />
        </Trigger>
    </Style.Triggers>
</Style>

So this is my button:

<Button Content="Button"  Style="{StaticResource NoBorderButton}">

</Button>

Now after search for solution to remove all the border i found this template that need to be add to the button:

<Button.Template>
    <ControlTemplate TargetType="{x:Type Button}">
        <ContentPresenter Content="{TemplateBinding Content}"/>
    </ControlTemplate>
</Button.Template>

So i have several questions:

  1. What this template doing ?
  2. Why i cannot add it the the style i created inside my Windows.Resources ?
1

There are 1 answers

0
Mike Eason On BEST ANSWER

I'm going to attempt to answer your questions directly, however there is much that can be discussed here.

What this template doing?

All controls have some kind of default template, a pre-defined look and feel of what the control looks like.

The Template is overriding the default look and feel for your Button. What you are effectively doing is completely starting afresh a new template for a button.

So for example, you can define a new template for what a button would look like. It can be a TextBlock inside an Ellipse for example. Instead of the default button template.

It's hard to put into words, but I think I explained that well enough.

Why i cannot add it the the style i created inside my Windows.Resources?

You can:

<Setter Property="Template">
    <Setter.Value>
        <ControlTemplate TargetType="Button">
            ...
        </ControlTemplate>
    </Setter.Value>
</Setter>