Search code examples
c#wpfdatatriggerwpf-style

Datatrigger auto reverse color


I want to change the background color to red instantly if a property is true. Then revert slowly back to default background color.

My first attempt, problem: Default color appears instantly and not reverting slowly over time

 <DataTrigger Binding="{Binding HasValueChanged}" Value="True">
            <Setter Property="Background" Value="Red" />
        </DataTrigger>
        <DataTrigger Binding="{Binding HasValueChanged}" Value="False">
            <DataTrigger.EnterActions>
                <BeginStoryboard>
                    <Storyboard>
                        <ColorAnimation  Storyboard.TargetProperty="Background.(SolidColorBrush.Color)" Duration="0:0:5" />
                    </Storyboard>
                </BeginStoryboard>
            </DataTrigger.EnterActions>
        </DataTrigger>

My second attempt, problem: Color reverses like it should, but never goes red again if the property remains true

<DataTrigger Binding="{Binding HasValueChanged}" Value="True">
                <DataTrigger.EnterActions>
                    <BeginStoryboard>
                        <Storyboard>
                            <ColorAnimation To="Red" AutoReverse="True"  Storyboard.TargetProperty="Background.(SolidColorBrush.Color)" Duration="0:0:5" />
                        </Storyboard>
                    </BeginStoryboard>
                </DataTrigger.EnterActions>
            </DataTrigger>

Solution

  • As long as you don't set a Timeline's FillBehavior to Stop, it keeps holding the final property value until it is replaced by another Timeline.

    So this works:

    <DataTrigger Binding="{Binding HasValueChanged}" Value="True">
        <DataTrigger.EnterActions>
            <BeginStoryboard>
                <Storyboard>
                    <ColorAnimation Storyboard.TargetProperty="Background.Color"
                                    To="Red" Duration="0"/>
                </Storyboard>
            </BeginStoryboard>
        </DataTrigger.EnterActions>
        <DataTrigger.ExitActions>
            <BeginStoryboard>
                <Storyboard>
                    <ColorAnimation Storyboard.TargetProperty="Background.Color"
                                    From="Red" Duration="0:0:1"/>
                </Storyboard>
            </BeginStoryboard>
        </DataTrigger.ExitActions>
    </DataTrigger>