标签动画写为代码而不是故事板

时间:2014-03-03 23:00:51

标签: c# wpf xaml

如果值低于阈值,我正在使用事件处理程序检查每秒。如果是,它将标签文本显示为红色。我想让这个标签闪现。我可以使用故事板,但这将写在xaml部分和固定的类型。有没有办法让标签在MainWindow部分写的代码上闪烁?

public MainWindow()
{
    InitializeComponent();
    CalculateEvent += CPUHandler;
}

void Handler(object sender, MyEventArgs args)
{
    if (args.TotalSum < 5000)
    {
        label11.Foreground = Brushes.Red;
    }
    else
    {
        label11.Foreground = Brushes.White;
    }
}

2 个答案:

答案 0 :(得分:0)

你知道xaml部分中的标签也只是csharp类吗?

当然可以使用Storyboard类!符号略有不同。

Check the example at the bottom of this page

答案 1 :(得分:0)

您不需要故事板。只需将(可修改的)SolidColorBrush分配给Label的Foreground,然后在其ColorAnimation属性上启动Color

var colorAnimation = new ColorAnimation
{
    To = Colors.Red,
    Duration = TimeSpan.FromSeconds(0.1),
    AutoReverse = true,
    RepeatBehavior = new RepeatBehavior(3)
};

var foreground = label.Foreground as SolidColorBrush;

if (foreground == null || foreground.IsFrozen)
{
    foreground = new SolidColorBrush(Colors.White);
    label.Foreground = foreground;
}

foreground.BeginAnimation(SolidColorBrush.ColorProperty, colorAnimation);

您当然可以使用动画的属性,例如DurationAutoReverseRepeatBehaviour,以获得所需的闪烁效果。


如果直接在XAML中指定SolidColorBrush,请执行以下操作:

<Label x:Name="label" ...>
    <Label.Foreground>
        <SolidColorBrush Color="White"/>
    </Label.Foreground>
</Label>

您无需在代码中检查它:

label.Foreground.BeginAnimation(SolidColorBrush.ColorProperty,
    new ColorAnimation
    {
        To = Colors.Red,
        Duration = TimeSpan.FromSeconds(0.1),
        AutoReverse = true,
        RepeatBehavior = new RepeatBehavior(3)
    });
相关问题