【问题标题】:How do I animate image content in WPF?如何在 WPF 中为图像内容设置动画?
【发布时间】:2011-02-16 12:54:25
【问题描述】:

我有一个非常基本的用户控件,带有一个带有图像的按钮。我想通过将按钮的图像更改为不同的图像来制作动画。

<UserControl.Resources>
    <Image x:Key="GlyphDefault" Source="pack://application:,,,/X;component/images/Glyphs_Default.png" Height="8" Width="8" />
    <Image x:Key="GlyphClicked" Source="pack://application:,,,/X;component/images/Glyphs_Click.png" Height="8" Width="8"  />

</UserControl.Resources>
    <Grid>
    <VisualStateManager.VisualStateGroups>
        <VisualStateGroup Name="MouseStates">
            <VisualState Name="MouseHover" >
                <Storyboard>
                    <ObjectAnimationUsingKeyFrames
                                Storyboard.TargetName="GlyphButton"
                                Storyboard.TargetProperty="Content"
                                Duration="0:0:1" >
                        <ObjectAnimationUsingKeyFrames.KeyFrames>
                            <DiscreteObjectKeyFrame KeyTime="0:0:1">
                                <DiscreteObjectKeyFrame.Value="{StaticResource GlyphClicked}" />
                            </DiscreteObjectKeyFrame>
                        </ObjectAnimationUsingKeyFrames.KeyFrames>
                    </ObjectAnimationUsingKeyFrames>
                </Storyboard>
            </VisualState>
            <VisualState Name="MouseNotHover" >
            </VisualState>
        </VisualStateGroup>

    </VisualStateManager.VisualStateGroups>
    <Button x:Name="GlyphButton" 
            MouseLeave="GlyphButton_MouseLeave"
            MouseEnter="GlyphButton_MouseEnter"
            Content="{StaticResource GlyphDefault}"
            />
</Grid>

不幸的是,当我运行它并将鼠标悬停在按钮上时,我得到“Freezable 不能被冻结”异常(鼠标事件处理程序更改状态)。它似乎正在尝试冻结当前图像,但由于某种原因无法冻结。

我也尝试过不使用静态资源(只是将图像内联),但同样的错误。奇怪的是,我几乎找不到关于在 Content 属性上制作动画的文档或博客。我不得不想象这将是一个常见的场景。关于我做错了什么有什么想法吗?

非常感谢您在这方面的帮助!

【问题讨论】:

    标签: c# wpf animation storyboard


    【解决方案1】:

    这可能不是解决此问题的最佳(或最简单)方法。 Content 属性绝对不是 WPF 设计者对动画的想法。下面是我将如何做到这一点:

    1. Button.Content 设置为Grid,两个图像都放在里面(因此,相互重叠)。
    2. Image 上的Opacity 设置为初始可见的Image 上的1.0 和0.0 初始隐藏。
    3. 使用DoubleAnimation 而不是ObjectAnimationOpacity 设置动画-您可以通过将一个不透明度设置为0.0 并同时将另一个设置为1.0 来切换图像。此外,根据持续时间,这会给你一个很好的淡入淡出过渡。

    【讨论】:

    • 谢谢查理。我曾考虑过这一点,但认为这感觉很骇人听闻。不过,我正在使用 WPF 学习的一件事是一些感觉有点骇人听闻的东西实际上是最佳实践 :-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 2012-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多