I am trying to make a custom control in WPF. I want it to simulate the behavior of a LED that can blink.
There are three states to the control: On, Off, and Blinking.
I know how to set On and Off through the code behind, but this WPF animation stuff is just driving me nuts!!!! I cannot get anything to animate whatsoever. The plan is to have a property called state. When the user sets the value to blinking, I want the control to alternate between green and grey. I'm assuming I need a dependency property here, but have no idea. I had more xaml before but just erased it all. it doesn't seem to do anything. I'd love to do this in the most best practice way possible, but at this point, I'll take anything. I'm half way to writing a thread that changes the color manually at this point.
<UserControl x:Class="WpfAnimation.LED"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="300" Width="300">
<Grid>
<Ellipse x:Name="MyLight" Height="Auto" Width="Auto"/>
</Grid>
</UserControl>
To allow for greater control of the blink rate and such in your code behind, I'd suggest having a routed event in your UserControl called Blink:
In your code behind you can set up a timer to raise the event however often you like (this also gives you the opportunity to blink the light a single time whenever you want:
Now in XAML, the following code would make a glow visible, and set the fill property of your ellipse (ledEllipse) to a bright green radial gradient, then return the fill value to a dim 'unlit' green (which you could change to gray if you like). You can simply change the duration to make the blink last longer.
Also, I am directly referencing the ellipse 'ledEllipse' and it's corresponding DropShadowEffect 'glow' which are defined in the ledControl as following (redLight is just another radial gradient brush that I start my led's fill property at):
Note: The DropShadowEffect was introduced in .Net 3.5, but you could remove that if you don't want a glow effect (but it looks nice on a solid color contrasting background).
You can do this with an animation that auto-reverses and repeats (this is for Silverlight):
and then start the animation when the control loads or when a property is set - you don't need a dependency property unless you
or on startup:
Here is another way to do it in WPF - using the VisualStateManager - that will also work in Silverlight:
and then have the IsBlinking property switch the visual state: