Search code examples
c#wpfdata-bindingeventtriggercoloranimation

How can I animate bound data from an event trigger?


I have a rectangle that has a LinearGradientBrush. one of the brush's colors is bound to an external resource. The rectangle looks like:

<Rectangle
    Width="40"
    Height="40"
    RadiusX="5"
    RadiusY="5"
    Fill="white"
    Opacity="0.6">
    <Rectangle.OpacityMask>
        <LinearGradientBrush
            x:Name="UpperShading"
            StartPoint="0,0.2"
            EndPoint="0,0"
            MappingMode="RelativeToBoundingBox">
            <GradientStop
                Color="Transparent" Offset="0"/>
            <GradientStop
                x:Name="UpperShadingColor"
                Color="{Binding
                        Source={StaticResource PlaybackResource},
                        Path=UpperLeftColor}"
                Offset="1"/>
        </LinearGradientBrush>
    </Rectangle.OpacityMask>
</Rectangle>

The bound data is a simple color property:

public Color UpperLeftColor
{
    get
    {
        return _upperleftColor;
    }
    set
    {
        _upperleftColor = value;
        SetPropertyChanged("UpperLeftColor");
    }
}

I actually have several rectangles stacked on top of each other and on the topmost rectangle I would like to create an animation to change the value of the bound color when the top rectangle is clicked (MouseDown). I tried:

<Rectangle
    Width="40"
    Height="40"
    RadiusX="5"
    RadiusY="5"
    Fill="Transparent">
    <Rectangle.Triggers>
        <EventTrigger RoutedEvent="MouseDown">
            <EventTrigger.Actions>
        <BeginStoryboard>
            <Storyboard>
                <ColorAnimation
                    Storyboard.TargetName
                        ="{Binding Source={StaticResource PlaybackResource}}"
                    Storyboard.TargetProperty="UpperLeftColor"
                    To="{Binding Source
                        ={StaticResource PlaybackResource}, Path=LowlightColor}"
                    Duration="0:0:1"/>
            </Storyboard>
            </BeginStoryboard>
        </EventTrigger.Actions>
    </EventTrigger>
    </Rectangle.Triggers>
</Rectangle>

but this produced the the error: (PlaybackResource is the key for the class PlaybackButtonReources)

"'PlaybackButtonResources' name cannot be found in the name scope of 'System.Windows.Shapes.Rectangle'."

I tried to add the resource to the rectangle, but got the same error message.

This boils down to "How can I animate bound data from an event trigger?"

Any pointers are welcome.


Solution

  • You need to set the Storyboard target to the GradientStop that you want to animate, not the bound value.

    Try changing your ColorAnimation to the following:

    <ColorAnimation Storyboard.TargetName="UpperShadingColor"
                Storyboard.TargetProperty="Color"
                To="{Binding Source={StaticResource PlaybackResource}, Path=LowlightColor}"
                Duration="0:0:1"/>