C# XAML Metro Image dynamic Source

2019-07-19 01:08发布

问题:

I like to do simple animation using one Image control in XAML and swaping Source of Image to other in interval 1 second.

But when I do that, the image is flickering. I using this code (at Tick event handler of Timer):

Uri uri = new Uri("ms-appx:/Sprites/Running/" + y++ + ".png", 
              UriKind.RelativeOrAbsolute);
BitmapImage textureBitmap = new BitmapImage(uri);

this.ImageHolder.Source = textureBitmap;

Where can the problem be ? Should I cache BitmapImages?

Thank you for your help.

回答1:

Try to declare a StoryBoard in your xaml:

    <Storyboard>
        <ObjectAnimationUsingKeyFrames BeginTime="0:0:0" 
            Storyboard.TargetName="ImageHolder" Storyboard.TargetProperty="Source">
            <DiscreteObjectKeyFrame KeyTime="0:0:0" 
               Value="{Binding Source={StaticResource Frame1Image}"/>
            <DiscreteObjectKeyFrame KeyTime="0:0:1" 
               Value="{Binding Source={StaticResource Frame2Image}"/>
            <DiscreteObjectKeyFrame KeyTime="0:0:2" 
               Value="{Binding Source={StaticResource Frame3Image}"/>
            <!-- etc -->
        </ObjectAnimationUsingKeyFrames>
    </Storyboard>

So, you have to add sprites to static resources, and run a StoryBoard.