Search code examples
c#wpfstylesstoryboardshapes

How to Apply Storyboard as Style


I want to apply a Storyboard to my Rectangle Fill like this:

<Rectangle Name="MyRectangle"
  Width="100"
  Height="100">
  <Rectangle.Fill>
    <SolidColorBrush x:Name="MySolidColorBrush" Color="Blue" />
  </Rectangle.Fill>
  <Rectangle.Triggers>
    <EventTrigger RoutedEvent="Rectangle.MouseEnter">
      <BeginStoryboard>
        <Storyboard>
          <ColorAnimation 
            Storyboard.TargetName="MySolidColorBrush"
            Storyboard.TargetProperty="Color"
            From="Blue" To="Red" Duration="0:0:1" />  
        </Storyboard>
      </BeginStoryboard>
    </EventTrigger>
  </Rectangle.Triggers>
</Rectangle> 

But I want to insert the Storyboard in a Style, i tried this:

<Style xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:s="clr-namespace:System;assembly=mscorlib" 
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   TargetType="{x:Type Rectangle}">

<Style.Triggers>

    <EventTrigger RoutedEvent="Shape.Loaded">
        <BeginStoryboard>
            <Storyboard>
                <ColorAnimation 
            Storyboard.TargetName="MySolidColorBrush"
            Storyboard.TargetProperty="Color"
            From="Blue" To="Red" Duration="0:0:1" />
            </Storyboard>
        </BeginStoryboard>
    </EventTrigger>

</Style.Triggers>

<Setter Property="Shape.Fill" Value="Blue" x:Name="MySolidColorBrush"/>

</Style>

Using this code:

var rect = new Rectangle();

using (FileStream stream = new FileStream("myStyle.xaml", FileMode.Open))
   rect.Style = XamlReader.Load(stream) as Style;

But it does not work and throws an exception. How I have to change my Style?


Solution

  • Change this in your Storyboard

    Storyboard.TargetProperty="Color" 
    

    to

    Storyboard.TargetProperty="Fill.Color"
    

    and remove

    Storyboard.TargetName="MySolidColorBrush"