Fire
Fire

Reputation: 397

wpf dynamic change image source using timer

In WPF, I have 2 images, and I need to create a blinking effect (not using opacity). Assume that I have a.png and b.png, first step showing a.png, after 0.5 seconds, it will show b.png, then after 0.5 seconds, it will show a.png, and repeat non-stop.

I've go through the forum, but I still have no luck to get example in vb, please help.

Upvotes: 3

Views: 2019

Answers (2)

Clemens
Clemens

Reputation: 128060

You may use an appropriate animation without any code behind:

<Window.Resources>
    <BitmapImage x:Key="Image1" UriSource="C:\Users\Public\Pictures\Sample Pictures\Koala.jpg"/>
    <BitmapImage x:Key="Image2" UriSource="C:\Users\Public\Pictures\Sample Pictures\Jellyfish.jpg"/>
</Window.Resources>
...
<Image x:Name="image" Source="{StaticResource Image1}">
    <Image.Triggers>
        <EventTrigger RoutedEvent="Loaded">
            <BeginStoryboard>
                <Storyboard>
                    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Source"
                                                   Duration="0:0:1"
                                                   RepeatBehavior="Forever">
                        <DiscreteObjectKeyFrame Value="{StaticResource Image2}" 
                                                KeyTime="0:0:0.5"/>
                    </ObjectAnimationUsingKeyFrames>
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
    </Image.Triggers>
</Image>

Perhaps replace the Loaded event by one that better suits your needs.

If you really want to do it in code behind, you may create a DispatcherTimer with an Interval set to half a second, and in the timer's Tick event handler alternately set the image's Source property to one of the two images.

Upvotes: 5

Tomtom
Tomtom

Reputation: 9394

I'm not fit in vb.net, but in c# you can do with something like

public ImageSource GetImageSourceFromImage(Bitmap pngFile)
        {
            MemoryStream imageStream = new MemoryStream();
            pngFile.Save(imageStream, ImageFormat.Png);
            imageStream.Seek(0, SeekOrigin.Begin);
            return BitmapFrame.Create(imageStream);
        }

This function gives you an imagesource which you can just assign to your image-object.

Upvotes: 0

Related Questions