I'm trying to put together a simple demo project of blinking "Hello World" text with the least code possible in C#/WPF. What I have written compiles and runs, but does not actually blink the text (it's based off of a timer that fires every 2 seconds and changes the visibility of the label. Any thoughts on why the text isn't blinking or what a more efficient approach would be? Code:
using System;
using System.Timers;
using System.Windows;
namespace BlinkingText
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
static Timer _timer;
static MainWindow window = new MainWindow();
public MainWindow()
{
InitializeComponent();
Start();
}
public static void Start()
{
var timer = new Timer(2000);
timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
timer.Enabled = true;
_timer = timer;
}
public static void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
if (window.HelloWorldLabel.Visibility == Visibility.Hidden)
{
Application.Current.Dispatcher.Invoke((Action)delegate
{
window.HelloWorldLabel.Visibility = Visibility.Visible;
});
}
else
{
Application.Current.Dispatcher.Invoke((Action)delegate
{
window.HelloWorldLabel.Visibility = Visibility.Hidden;
});
}
}
}
}
The text in your application does not blink because you change the Visibility of a Label in a hidden MainWindow instance, which is not identical to the one that you see on screen.
It is created by
static MainWindow window = new MainWindow();
but never shown.
Besides that, you should use a DispatcherTimer like this:
public partial class MainWindow : Window
{
private readonly DispatcherTimer timer =
new DispatcherTimer { Interval = TimeSpan.FromSeconds(2) };
public MainWindow()
{
InitializeComponent();
timer.Tick += Timer_Tick;
timer.Start();
}
private void Timer_Tick(object sender, EventArgs e)
{
HelloWorldLabel.Visibility = HelloWorldLabel.Visibility == Visibility.Visible
? Visibility.Hidden : Visibility.Visible;
}
}
You may also do something similar entirely in XAML, e.g. like this:
<TextBlock Text="Hello, World.">
<TextBlock.Triggers>
<EventTrigger RoutedEvent="Loaded">
<BeginStoryboard>
<Storyboard>
<ObjectAnimationUsingKeyFrames
Storyboard.TargetProperty="Visibility"
Duration="0:0:4" RepeatBehavior="Forever">
<DiscreteObjectKeyFrame
KeyTime="0:0:0"
Value="{x:Static Visibility.Visible}"/>
<DiscreteObjectKeyFrame
KeyTime="0:0:2"
Value="{x:Static Visibility.Hidden}"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</TextBlock.Triggers>
</TextBlock>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With