WPF TextBlock refresh in real time
Posted
by
TheOnlyBrien
on Programmers
See other posts from Programmers
or by TheOnlyBrien
Published on 2014-05-26T22:32:45Z
Indexed on
2014/05/27
3:40 UTC
Read the original article
Hit count: 447
I'm new to C#, in fact, this is one of the first projects I've tried to start on my own. I am curious why the TextBlock will not refresh with the following code? The WPF window does not even show up when I add the "while" loop to the code. I just want this to have a real time display of the days since I was born.
Please help me out or give me constructive direction.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace daysAliveWPF
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DateTime myBirthday = new DateTime(1984, 01, 19);
while (true)
{
TimeSpan daysAlive = DateTime.Now.Subtract(myBirthday);
MyTextBlock.Text = daysAlive.TotalDays.ToString();
}
}
}
}
Similar code has worked in a Console Window application, so I don't understand what's going on here. Console Application code snip that did work is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DisplayRealTime
{
class Program
{
static void Main(string[] args)
{
DateTime myBirthday = new DateTime(1984, 06, 19);
while (true)
{
TimeSpan daysAlive = DateTime.Now.Subtract(myBirthday);
Console.Write("\rTotal Days Alive: {0}", daysAlive.TotalDays.ToString(".#####"));
}
}
}
}
Thank you!
© Programmers or respective owner