wpf使用定时器动态改变图像源

Fir*_*ire 3 vb.net wpf image

在 WPF 中,我有 2 个图像,我需要创建闪烁效果(不使用不透明度)。假设我有a.png和b.png,第一步显示a.png,0.5秒后显示b.png,然后0.5秒后显示a.png,不停地重复。

我已经浏览过论坛,但我仍然没有运气获得 VB 中的示例,请帮助。

Cle*_*ens 5

您可以使用适当的动画,而无需任何隐藏代码:

<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>
Run Code Online (Sandbox Code Playgroud)

也许可以Loaded用更适合您需求的活动来替换该活动。

如果您确实想在后面的代码中执行此操作,则可以创建一个Interval设置为半秒的 DispatcherTimer,并在计时器的Tick事件处理程序中交替将图像的Source属性设置为两个图像之一。