I'm trying to create a simple change in the background color of a border based on a timer.
I have this XAML:(That I pretty much copied from
However, what I want to do is to trigger the animation based on a custom event.
In the code behind I made a timer with a 1000ms interval. I want to trigger the animation on the timer's 'Elapsed' event.
public partial class LedIndicator : UserControl
{
private System.Timers.Timer _timer;
public Timer Timer { get => _timer; set => _timer = value; }
public LedIndicator()
{
InitializeComponent();
Timer = new System.Timers.Timer
{
AutoReset = true,
Interval = 1000
};
Timer.Elapsed = OnTimerElapsed;
Timer.Start();
}
public void OnTimerElapsed(object? sender, System.Timers.ElapsedEventArgs e)
{
Debug.WriteLine($"Timer elapsed");
}
}
I wrapped the timer in a Property in the hope of somehow exposing its Elapse
event to the XAML. But I have no idea how to do it.
CodePudding user response:
Here is a rough example
Create a storyboard in code somewhere:
private myAnimation = new ColorAnimation(Colors.LightGreen, new Duration(new TimeSpan(0, 0, 1)), FillBehavior.Stop);
myAnimation.AutoReverse = true;
Setup the timer:
private System.Threading.Timer animationTimer = new Timer(_ =>
{
//need dispatcher to execute on UI thread
Dispatcher.Invoke(() =>
{
ledColor.BeginAnimation(Button.BackgroundProperty, myAnimation);
});
}, 0, 1000); //start immediately, and elapse every 1 second
CodePudding user response:
This is a small modification of @Ginger Ninja's answer to a working example.
When I tried his answer out, I got an exception saying that you can't animate the background property of type Brush
with ColorAnimation
.