Question

I am using an event handler to check every second if the value falls below threshold. If yes, it will display the label text as red. I want to make this label flash. I could use a storyboard but that would be written on the xaml portion and kind of fixed. Is there a way to enable the label to flash on codes written on the MainWindow portion?

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

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

Solution

You don't need a Storyboard. Just assign a (modifiable) SolidColorBrush to the Label's Foreground, and start a ColorAnimation on its Color property:

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);

You may of course have to play around with the animation's properties like Duration, AutoReverse and RepeatBehaviour, in order to get the desired flashing effect.


If you assign the SolidColorBrush directly in XAML like this:

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

you don't need to check for it in code:

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

OTHER TIPS

Did you know the tags in the xaml portion are just csharp classes as well?

Sure you can use the Storyboard class! The notation is just a little different.

Check the example at the bottom of this page

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top