Search code examples
c#wpfxamlresourcedictionary

Apply the same style to multiple buttons in a XAML page


I am trying to add a background color to a button whenever it is clicked and restoring to its original color after some time. I tried to create a ResourceDictionary.xaml and added my style set and added its reference to a XAML page. Seems something is wrong in my code. If I add the style directly into the button tags, it works.. But not via ResourceDictionary . Please help.

ResourceDictionary.xaml

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:FantasyPlay">

<Style TargetType="Button">
    <Setter Property="Background" Value="Gainsboro" />
    <Style.Triggers>
        <Trigger Property="IsPressed" Value="True">
            <Trigger.EnterActions>
                <BeginStoryboard>
                    <Storyboard>
                        <ColorAnimation Storyboard.TargetProperty="(Button.Background).(SolidColorBrush.Color)" From="Orange" To="Gainsboro" Duration="0:0:0.50" AutoReverse="True" />
                        <ColorAnimation Storyboard.TargetProperty="(Button.Background).(SolidColorBrush.Color)" From="Gainsboro"  To="Orange" Duration="0:0:0.1" AutoReverse="True" />
                    </Storyboard>
                </BeginStoryboard>
            </Trigger.EnterActions>
        </Trigger>
    </Style.Triggers>
</Style>

MyXAML:

I have referenced it like

<Window.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="ResourceDictionary.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Window.Resources>

Solution

  • Good day, let try this

    <Trigger Property="IsPressed" Value="True">
                    <Trigger.ExitActions>
                        <BeginStoryboard>
                            <Storyboard  AutoReverse="True" >
                                <ColorAnimation Storyboard.TargetProperty="(Button.Background).(SolidColorBrush.Color)" Duration="0:0:0"/>
                                <ColorAnimation Storyboard.TargetProperty="(Button.Background).(SolidColorBrush.Color)" To="Orange" Duration="0:0:0.50"/>
                            </Storyboard>
                        </BeginStoryboard>
                    </Trigger.ExitActions>
                </Trigger>