在StoryBoard期间更改图像的来源

时间:2016-08-24 09:26:24

标签: c# wpf xaml storyboard

我试图在我的主页(大约30个)上有多个图像,使用StoryBoard淡入和淡出。目前,我将动画完美地放在一张照片上,它看起来像这样;

private void OnDashboardPageLoaded(object sender, RoutedEventArgs e)
{
    Storyboard storyboard = new Storyboard();
    TimeSpan duration = new TimeSpan(0, 0, 10);

    // Create a DoubleAnimation to fade the not selected option control
    DoubleAnimation animation = new DoubleAnimation();

    animation.From = 0.0;
    animation.To = 1.0;
    animation.Duration = new Duration(duration);

    // Configure the animation to target de property Opacity
    Storyboard.SetTargetName(animation, testImage.Name);
    Storyboard.SetTargetProperty(animation, new PropertyPath(OpacityProperty));

    // Add the animation to the storyboard
    storyboard.Children.Add(animation);

    storyboard.RepeatBehavior = RepeatBehavior.Forever;
    animation.AutoReverse = true;

    // Begin the storyboard
    storyboard.Begin(this);
}

我的XAML;

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition />
    </Grid.RowDefinitions>
    <Image Source="http://www.online-image-editor.com/styles/2013/images/example_image.png" x:Name="testImage" Stretch="Uniform" />
</Grid>

正如您所看到的,我在这里设置了一个静态源,但最终我要做的是将所有图像加载到目录中并在每个动画结束时更改源,以便每次都显示一个新图像时间(直到显示全部30个),我该怎么做?

编辑:完成故事板后;

storyboard.Completed += new EventHandler(Story_Completed); // In OnDashboardPageLoaded method

private void Story_Completed(object sender, EventArgs e)
{
    storyboard.Begin(this);
}

1 个答案:

答案 0 :(得分:0)

以下方法淡出图像控件,更改其Source属性,并再次淡入。您可以使用另一个ImageSource参数循环调用它(例如,由DispatcherTimer控制)。

public static void ShowNextImage(Image image, ImageSource source, TimeSpan fadeTime)
{
    if (image.Source == null) // no fade out
    {
        image.Source = source;
        image.BeginAnimation(UIElement.OpacityProperty,
            new DoubleAnimation(0d, 1d, fadeTime));
    }
    else
    {
        var fadeOut = new DoubleAnimation(0d, fadeTime);

        fadeOut.Completed += (s, e) =>
        {
            image.Source = source;
            image.BeginAnimation(UIElement.OpacityProperty,
                new DoubleAnimation(1d, fadeTime));
        };

        image.BeginAnimation(UIElement.OpacityProperty, fadeOut);
    }
}