使用动画制作WPF标签(或其他元素)

Dav*_*ave 11 wpf animation triggers datatrigger

我有一个标签,我只根据我的一个ViewModel属性显示.这是XAML:

<Label  HorizontalAlignment="Center" VerticalAlignment="Center"
        HorizontalContentAlignment="Center" 
        VerticalContentAlignment="Center" 
        FontSize="24" Width="200" Height="200" >
    <Label.Content >
        Option in the money! 
    </Label.Content>
    <Label.Style>
        <Style TargetType="{x:Type Label}">
            <Setter Property="Visibility" Value="Hidden" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding OptionInMoney}" Value="True">
                    <Setter Property="Visibility"
                Value="Visible" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Label.Style>

</Label>
Run Code Online (Sandbox Code Playgroud)

我不确定这是最好的方法,但无论如何,我也想让标签闪烁.显然,我只希望它在可见时闪烁.有人能指点我一些示例代码,或写一个快速示例来做到这一点?我假设我需要某种触发器和动画.据推测,当标签不再可见时我还需要一个触发器,以便停止动画?

谢谢,戴夫PS是否有一本好的书或网站所有这些WPF技巧?像那些记得那本书的人那样的"MFC答案书".

sa_*_*213 32

您可以添加一个Storyboard动画Style.Resources并在该EnterActions部分中启动它DataTrigger.

一个简单DoubleAnimationOpacity应该工作正常

像这样的东西:

<Label.Style>
    <Style TargetType="{x:Type Label}">
        <Style.Resources>
            <Storyboard x:Key="flashAnimation" >
                <DoubleAnimation Storyboard.TargetProperty="Opacity" From="1" To="0" AutoReverse="True" Duration="0:0:0.5" RepeatBehavior="Forever" />
            </Storyboard>
        </Style.Resources>

        <Setter Property="Visibility" Value="Hidden" />
        <Style.Triggers>
            <DataTrigger Binding="{Binding OptionInMoney}" Value="True">
                <Setter Property="Visibility" Value="Visible" />
                <DataTrigger.EnterActions>
                    <BeginStoryboard Name="flash" Storyboard="{StaticResource flashAnimation}" />
                </DataTrigger.EnterActions>
                <DataTrigger.ExitActions>
                    <StopStoryboard BeginStoryboardName="flash"/>
                </DataTrigger.ExitActions>
            </DataTrigger>

        </Style.Triggers>
    </Style>
</Label.Style>
Run Code Online (Sandbox Code Playgroud)


小智 5

StoryBoard当然是WPF的方式,但也可以通过简单的代码来实现。在这里,让标签背景闪烁:

lblTimer是表单上的一个标签,其中包含一些文本,例如“我在眨眼”

这可以应用于任何属性,例如可见性。

// Create a timer.
private void Window_Loaded(object sender, RoutedEventArgs e)
{
    DispatcherTimer timer = new DispatcherTimer();
    timer.Tick += timer_Tick;
    timer.Interval = new TimeSpan(0, 0, 0, 0, 500);
    timer.Start();
}

// The timer's Tick event.
private bool BlinkOn = false;
private void timer_Tick(object sender, EventArgs e)
{
    if (BlinkOn)
    {
        lblTimer.Foreground = Brushes.Black;
        lblTimer.Background = Brushes.White;
    }
    else
    {
        lblTimer.Foreground = Brushes.White;
        lblTimer.Background = Brushes.Black;
    }
    BlinkOn = !BlinkOn;
}
Run Code Online (Sandbox Code Playgroud)