2010-05-06 64 views
0

我有一个非常基本的用户控件与一个图像的按钮。我想通过将其更改为不同的图像来为按钮的图像制作动画。如何为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> 

不幸的是,当我运行这一点,将鼠标悬停在按钮我得到“可冻结不能被冻结”的例外(鼠标事件处理程序改变状态)。它似乎试图冻结当前的图像,但不能出于某种原因。

我试着做它不使用静态资源(只是把图片在线)过,但同样的错误。奇怪的是,我可以找到关于在Content属性上做动画的文档或博客。我不得不想象这将是一种常见的情况。任何想法,我做错了什么?

我非常感谢您对这个帮助!

回答

3

这可能不是最好的(或最简单的)的方式来进行此事。 Content属性绝对不是WPF设计人员为动画设计的。下面是我会怎么做这个:

  1. Button.Content能够同时与置于其内的图像的Grid(因此,彼此覆盖)。
  2. 设置你想成为最初可见的1.0和0.0的Image最初将被隐藏ImageOpacity
  3. 使用DoubleAnimation而非ObjectAnimation动画显示Opacity - 你可以通过动画一个的不透明度降低到0.0,同时使另一种可达1.0切换图像。此外,根据持续时间,这会给你一个很好的衰落过渡。
+0

感谢查理。我已经考虑过了,但认为它感到ha。。有一件事,我正在与WPF学习虽然是有些事情觉得有点hackish实际上是最佳实践:-) – 2010-05-06 20:08:58