R – Using WPF, what is the best method to update the background for a custom button control

buttonmouseovertriggerswpf

In WPF, we are creating custom controls that inherit from button with completely drawn-from-scratch xaml graphics. We have a border around the entire button xaml and we'd like to use that as the location for updating the background when MouseOver=True in a trigger. What we need to know is how do we update the background of the border in this button with a gradient when the mouse hovers over it?

Best Answer

In your ControlTemplate, give the Border a Name and you can then reference that part of its visual tree in the triggers. Here's a very brief example of restyling a normal Button:

<Style
    TargetType="{x:Type Button}">
    <Setter
        Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Border Name="customBorder"
                    CornerRadius="5"
                    BorderThickness="1"
                    BorderBrush="Black"
                    Background="{StaticResource normalButtonBG}">
                    <ContentPresenter
                        HorizontalAlignment="Center"
                        VerticalAlignment="Center" />
                </Border>
                <ControlTemplate.Triggers>
                    <Trigger
                        Property="IsMouseOver"
                        Value="True">
                        <Setter
                            TargetName="customBorder"
                            Property="Background"
                            Value="{StaticResource hoverButtonBG}" />
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

If that doesn't help, we'll need to know more, probably seeing your own XAML. Your description doesn't make it very clear to me what your actual visual tree is.

Related Topic