如何动态添加ObjectAnimationUsingKeyFrames
我想实现一个点击按钮时触发一个切换图片的功能。图片被包装在xap文件里面了。
代码如下。
<Grid x:Name="LayoutRoot" Background="White" Loaded="LayoutRoot_Loaded"><Image Margin="82,112,81,124" Grid.Column="1" x:Name="imgTest"> </Image> <TextBlock Margin="101,60,108,68" Grid.Column="1" Grid.Row="1" Text="TextBlock" TextWrapping="Wrap" d:LayoutOverrides="Width, Height"/> <Button Click="btnShow_Click" x:Name="btnShow" Width="20" Height="20"></Button> <StackPanel x:Name="MyPanl"> <StackPanel.Resources> <Storyboard x:Name="MyStory" > </Storyboard> </StackPanel.Resources> </StackPanel></Grid>
private void LayoutRoot_Loaded(object sender, RoutedEventArgs e) { BitmapImage bitmapImages = new BitmapImage(); bitmapImages.UriSource = new Uri("/Test/Te/Dnode.png", UriKind.RelativeOrAbsolute); imgTest.Source = bitmapImages; BitmapSource source; ImageSource im; var keyFrames = new ObjectAnimationUsingKeyFrames(); BitmapImage bitmapImage = new BitmapImage(); bitmapImage.UriSource = new Uri("/Test/Te/Dnode.png", UriKind.RelativeOrAbsolute); source = bitmapImage; im = bitmapImage; //BitmapSource source = bitmapImage; //DiscreteObjectKeyFrame keyFrame = new DiscreteObjectKeyFrame(); //keyFrame.Value = bitmapImage; //keyFrame.KeyTime = TimeSpan.FromSeconds(0.2); keyFrames.KeyFrames.Add(new DiscreteObjectKeyFrame { Value = im, KeyTime = new TimeSpan(0, 0, 0, 1) }); bitmapImage = new BitmapImage { UriSource = new Uri("/Test/Te/Dnode2.png", UriKind.RelativeOrAbsolute) }; //source.ClearValue(Image.SourceProperty); im = bitmapImage; //source = bitmapImage; keyFrames.RepeatBehavior = RepeatBehavior.Forever; keyFrames.KeyFrames.Add(new DiscreteObjectKeyFrame { Value = im, KeyTime = new TimeSpan(0, 0, 0, 1) }); MyStory.Children.Add(keyFrames); Storyboard.SetTarget(keyFrames, imgTest); Storyboard.SetTargetProperty(keyFrames, new PropertyPath(Image.SourceProperty)); } private void btnShow_Click(object sender, RoutedEventArgs e) { MyStory.Begin(); }
<StackPanel x:Name="MyPanl"> <StackPanel.Resources> <Storyboard x:Name="MyStory" > <ObjectAnimationUsingKeyFrames Duration="00:00:00.4" RepeatBehavior="Forever" Storyboard.TargetName="imag" Storyboard.TargetProperty="Source"> <DiscreteObjectKeyFrame KeyTime="00:00:00.2" x:Name="Run"> <DiscreteObjectKeyFrame.Value> <BitmapImage UriSource="/Test/Te/Dnode.png"></BitmapImage> </DiscreteObjectKeyFrame.Value> </DiscreteObjectKeyFrame> <DiscreteObjectKeyFrame KeyTime="00:00:00.2" x:Name="Stop"> <DiscreteObjectKeyFrame.Value> <BitmapImage UriSource="/Test/Te/Dnode2.png"></BitmapImage> </DiscreteObjectKeyFrame.Value> </DiscreteObjectKeyFrame> </ObjectAnimationUsingKeyFrames> </Storyboard> </StackPanel.Resources> </StackPanel>