[英]How do I animate image content in WPF?
我有一个带有图像按钮的非常基本的用户控件。 我想通过将按钮图像更改为其他图像来为按钮图像添加动画效果。
<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无法冻结”异常(Mouse事件处理程序更改状态)。 看来它正在尝试冻结当前图像,但是由于某种原因而无法。
我也尝试过不使用静态资源(只是将Image嵌入),但是存在相同的错误。 奇怪的是,我很少在Content属性上找到有关制作动画的文档或博客。 我不得不想象这将是一个常见的情况。 关于我在做什么错的任何想法吗?
非常感谢您的帮助!
这可能不是实现此目的的最佳(或最简单)方法。 WPF设计师对于动画绝对不是Content
属性。 这是我的替代方法:
Button.Content
设置为一个Grid
其中两个图像都放置在内部(因此彼此重叠)。 Image
上的Opacity
设置为最初要隐藏的Image
上的1.0和0.0。 DoubleAnimation
而不是ObjectAnimation
对Opacity
进行动画ObjectAnimation
-您可以通过将一个人的不透明度降低到0.0的动画来切换图像,同时将另一个人的不透明度提高到1.0。 此外,根据持续时间,这将为您提供良好的淡入淡出过渡。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.