c# wpf change DoubleAnimation "To" when load (in <Window.Resources>)

551 Views Asked by At

I use this code to animate an Image from left to right but I want To="100" to window width how to change DoubleAnimation "To" when window load or resize ?

xaml :

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525" ResizeMode="CanResize" WindowState="Normal" WindowStyle="ToolWindow" Loaded="Window_Loaded">

  <Window.Resources>
    <Storyboard x:Key="PlayAnimation" Storyboard.TargetProperty="(Canvas.Left)">
        <DoubleAnimation   From="0" Duration="0:0:1" RepeatBehavior="Forever" To="100" />
    </Storyboard>
  </Window.Resources>

  <Grid>
    <Grid.Background>
      <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
        <GradientStop Color="White" Offset="1" />
        <GradientStop Color="#FF5AC0FF" Offset="0" />
      </LinearGradientBrush>
    </Grid.Background>


    <Canvas>            
      <Image  Cursor="Hand" Height="205" HorizontalAlignment="Left" Margin="74,78,0,0" Name="image2" Source="I:\a.png" Stretch="Fill" VerticalAlignment="Top" Width="200" />
    </Canvas>     
  </Grid>    
</Window>

C# code :

private void Window_Loaded(object sender, RoutedEventArgs e)
{
  Storyboard sb = this.FindResource("PlayAnimation") as Storyboard;        
  Storyboard.SetTarget(sb, this.image2);
  sb.Begin();
}
1

There are 1 best solutions below

0
On

If I understand your question correctly, you want to change the To to some different value in codebehind, something like this:

Storyboard sb = this.FindResource("PlayAnimation") as Storyboard;        
(sb.Children[0] as DoubleAnimation).To = 200;
Storyboard.SetTarget(sb, this.image2);
sb.Begin();