如何在WPF中为控件模板的一部分设置动画?

时间:2014-07-01 18:09:36

标签: wpf xaml wpf-controls wpf-animation

所以我只是为了这个例子简化了这个。我有一个按钮,在它的ControlTemplate中我有一个红色椭圆。单击按钮(MouseDown事件)时,我希望Ellipse在1秒后动画显示为透明。这是我的xaml

<Button>
  <Button.Template>
    <ControlTemplate>
      <Grid Width="{TemplateBinding Width}"
            Height="{TemplateBinding Height}"
            ClipToBounds="True">
        <Ellipse x:Name="ripple" 
                 Height="20" Width="20" 
                 Fill="Red"
                 HorizontalAlignment="Center"
                 VerticalAlignment="Center"
                 Opacity="1"/>
        <ContentPresenter HorizontalAlignment="Center"
                          VerticalAlignment="Center" />
      </Grid>
    </ControlTemplate>
  </Button.Template>
  <Button.Triggers>
    <EventTrigger RoutedEvent="Button.MouseDown">
      <BeginStoryboard>
        <Storyboard>
          <DoubleAnimation Storyboard.TargetName="ripple"
                           Storyboard.TargetProperty="Opacity"
                           From="1" To="0" Duration="0:0:1"/>
        </Storyboard>
      </BeginStoryboard>
    </EventTrigger>
  </Button.Triggers>
</Button>

问题是当我点击按钮时椭圆不会透明。我的猜测是,由于某种原因,它无法找到名为“涟漪”的对象,但我不知道为什么。我做错了什么?

1 个答案:

答案 0 :(得分:2)

EventTrigger移至ControlTemplate.Triggers并使用PreviewMouseDown事件,因为Button处理MouseDown事件

<Button>
    <Button.Template>
        <ControlTemplate TargetType="{x:Type Button}">
            <Grid 
                Width="{TemplateBinding Width}" 
                Height="{TemplateBinding Height}" 
                ClipToBounds="True">
                <Ellipse 
                    x:Name="ripple" 
                    Height="20" 
                    Width="20" 
                    Fill="Red"
                    HorizontalAlignment="Center"
                    VerticalAlignment="Center"
                    Opacity="1"/>
                <ContentPresenter 
                    HorizontalAlignment="Center" 
                    VerticalAlignment="Center" />
            </Grid>
            <ControlTemplate.Triggers>
                <EventTrigger RoutedEvent="PreviewMouseDown">
                    <BeginStoryboard>
                        <Storyboard>
                            <DoubleAnimation 
                                Storyboard.TargetName="ripple" 
                                Storyboard.TargetProperty="Opacity" 
                                From="1" 
                                To="0" 
                                Duration="0:0:1"/>
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger>
            </ControlTemplate.Triggers>
        </ControlTemplate>
    </Button.Template>
</Button>