所以我简化了这个例子。我有一个按钮,在它的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>