如何在 WPF 中对控件模板的一部分进行动画处理?



所以我简化了这个例子。我有一个按钮,在它的ControlTemplate中我有一个红色椭圆。当按钮被点击时(MouseDown事件),我想让椭圆在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>

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

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>

相关内容

  • 没有找到相关文章

最新更新