Home > OS >  Change ToggleButton Background in WPF
Change ToggleButton Background in WPF

Time:09-13

I'm changing the background of a ToggleButton on MouseOver like this :

    <Style x:Key="ToggleButtonStyle" TargetType="{x:Type ToggleButton}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ToggleButton}">
                    <Border  x:Name="border" 
                             Background="{TemplateBinding Background}"                                                                 
                        <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="true">
                            <Setter 
                                TargetName="border"
                                Property="Background"
                                Value="{StaticResource ToggleButtonMouseHover}"/>                                
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style> 

I don't understand why we have to use a Border control. Do you have an explanation?

Thanks.

CodePudding user response:

It is not mandatory, you can use any Panel as a new Template for the ToggleButton

<Style x:Key="ToggleButtonStyle" TargetType="{x:Type ToggleButton}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="ToggleButton">
                <Canvas x:Name="border" Background="Red" />
                <ControlTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="true">
                        <Setter TargetName="border" Property="Background" Value="Blue" />
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

CodePudding user response:

Thanks to everyone, the point is that a background needs a container.

  • Related