Friday, December 25, 2015

[WPF] Binding a Storyboard property relative to the target of the storyboard

In my search to achieve making application level storyboards with some changeable properties:

http://stackoverflow.com/questions/4472546/binding-a-storyboard-property-relative-to-the-target-of-the-storyboard


I have a storyboard which targets an element, and binds one of its own properties to a property on another element:

   
            Storyboard.TargetProperty="RenderTransform.X" 
            From="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=ActualWidth}" 
            To="0" 
            Duration="0:0:5"/>
 
This storyboard works when the storyboard is stored in the resources of the window which holds the storyboard target. The 'From' value is correctly bound to the ActualWidth of the host Window instance.

However, I need to store the storyboard in my application level resources. From here, the storyboard does not seem to be able to target the window to determine the 'From' property. This is understandable as from inside , the binding won't be able to find an 'ancestor' of type Window.

I guess I need to be able to bind the 'From' value, relative to the target of the animation, rather than relative to the storyboard's DoubleAnimation.

Is this possible, and if so, how?

Here is the sample MainWindow.xaml:


    
     x:Key="localStoryBoard">
         
            Storyboard.TargetProperty="RenderTransform.X" 
            From="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=ActualWidth}" 
            To="0" 
            Duration="0:0:5"/>
    
RoutedEvent="Button.Click"> Storyboard="{StaticResource centralStoryBoard}"/>
And here is an example app.xaml:
 x:Class="WpfApplication3.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml">
    
        
         x:Key="centralStoryBoard">
             
                Storyboard.TargetProperty="RenderTransform.X" 
                From="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=ActualWidth}" 
                To="0" 
                Duration="0:0:5"/>
        
    
This won't work, as the eventtrigger refers to the app.xaml version. If you change it to the local resource version, you can see it works.