Brien Foss
Brien Foss

Reputation: 3367

WPF TextBlock refresh in real time

My goal is to have the TextBlock.Text value continually refresh.

When I add the while(true) to the code, no window is shown when I start the application.

using System;
using System.Windows;

namespace daysAliveWPF
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DateTime myBirthday = new DateTime(1984, 01, 01);
            while (true)
            {
                TimeSpan daysAlive = DateTime.Now.Subtract(myBirthday);
                MyTextBlock.Text = daysAlive.TotalDays.ToString();
            }
        }

    }
}

Similar code has worked in a Console Application, so I don't understand what's going on here. Console Application code snip that did work is:

using System;

namespace DisplayRealTime
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime myBirthday = new DateTime(1984, 01, 01);
            while (true)
            {
                TimeSpan daysAlive = DateTime.Now.Subtract(myBirthday);
                Console.Write("\rTotal Days Alive: {0}"
                    , daysAlive.TotalDays.ToString(".#####"));
            }

        }
    }
}

Upvotes: 3

Views: 2583

Answers (1)

GetFuzzy
GetFuzzy

Reputation: 2148

It's a threading issue. Your loop is blocking the UI from updating.

namespace ThrowAway
{

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DoCrazyLoop();
    }

    public void DoCrazyLoop()
    {
        DateTime myBirthday = new DateTime(1984, 01, 19);
        bool breakLoop = false;
        Timer t = new Timer(o =>
        {
            breakLoop = true;
        }, null, 10000, 100);

        while (breakLoop == false)
        {
            TimeSpan daysAlive = DateTime.Now.Subtract(myBirthday);
            MyTextBlock.Text = daysAlive.TotalDays.ToString();
        }
    }
 }
}

Notice that if you run this code, nothing will happen until the allotted time-span passes. This is because WPF can't update the UI until it breaks from the loop. Your code never got out of the loop, so was never able to update the UI. Check out the MVVM pattern with property binding. INotifyPropertyChange with a data binding will make life easier in this instance... However, you probably still want some way to break out of your loop :)

Upvotes: 2

Related Questions