在可见性更改时激活故事板

时间:2014-03-14 06:35:15

标签: c# wpf xaml mvvm storyboard

目前我有一个Image,我在加载时会发出脉冲。我想在更改图像的可见性时激活故事板。但我发现Image.Triggers必须是EventTriggers

我需要加入哪个事件?

<Image.Triggers>
    <EventTrigger RoutedEvent="Image.Loaded">
        <BeginStoryboard>
             <Storyboard>
                 <DoubleAnimation Storyboard.TargetName="MandateErrorImage"
                                  Storyboard.TargetProperty="Opacity"
                                  From="1.0" To="0.1" Duration="0:0:0.5"
                                  AutoReverse="True" RepeatBehavior="0:0:2" />
             </Storyboard>
        </BeginStoryboard>
    </EventTrigger>
</Image.Triggers>

2 个答案:

答案 0 :(得分:6)

在WPF中有一个事件UIElement.IsVisibleChanged,但它是一个CLR事件,而不是路由事件,因此无法使用EventTrigger

在这种情况下,使用DataTrigger中的IsVisible属性,如下所示:

<Window.Resources>
    <Style x:Key="AnimationImageStyle" TargetType="{x:Type Image}">
        <Style.Triggers>
            <DataTrigger Binding="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=IsVisible}" 
                         Value="True">

                <DataTrigger.EnterActions>
                    <BeginStoryboard>
                        <Storyboard>
                            <DoubleAnimation Storyboard.TargetProperty="Opacity"
                                             From="1.0" To="0.1"
                                             Duration="0:0:0.5"
                                             AutoReverse="True"
                                             RepeatBehavior="0:0:2" />
                        </Storyboard>
                    </BeginStoryboard>
                </DataTrigger.EnterActions>
            </DataTrigger>
        </Style.Triggers>
    </Style>
</Window.Resources>

<Grid>
    <Image Name="TestImage" 
           Style="{StaticResource AnimationImageStyle}" 
           Source="Enter.jpg"
           Width="400"
           Height="400" />        
</Grid>

答案 1 :(得分:1)

如果要为DependencyProperty或绑定值设置动画,则需要为图像创建Style并将动画放入样式中。

当您的图片的Style设置为Visibility时,以下Visible会执行动画:

    <Style x:Key="FlashingImageStyle" TargetType="{x:Type Image}">
        <Style.Triggers>
            <Trigger Property="Visibility" Value="Visible">
                <Trigger.EnterActions>
                    <BeginStoryboard>
                        <Storyboard>
                            <DoubleAnimation
                                  Storyboard.TargetProperty="Opacity"
                                  From="1.0" To="0.1" Duration="0:0:0.5"
                                  AutoReverse="True" RepeatBehavior="0:0:2" />
                        </Storyboard>
                    </BeginStoryboard>
                </Trigger.EnterActions>
            </Trigger>
        </Style.Triggers>
    </Style>