How can the current time be displayed in WPF?

In WPF, you can use the DateTime.Now property to get the current time, and then format it to display on the interface.

First, add a TextBlock control to the XAML file to display the time.

<TextBlock x:Name="txtTime" />

Next, locate the Loaded event handler for the window in the code-behind file and add the following code:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    DispatcherTimer timer = new DispatcherTimer();
    timer.Interval = TimeSpan.FromSeconds(1);
    timer.Tick += Timer_Tick;
    timer.Start();
}

private void Timer_Tick(object sender, EventArgs e)
{
    txtTime.Text = DateTime.Now.ToString("HH:mm:ss");
}

Create a DispatcherTimer object when the window loads, and set the interval to 1 second. Then, set the Timer_Tick method as the event handler for the timer’s Tick event. Every second, the timer will trigger this event, format the current time as a string in the format “HH:mm:ss”, and assign it to the Text property of a TextBlock control to display the current time on the interface.

Finally, link the Window_Loaded method with the Loaded event of the window by specifying the Loaded event handler in the XAML file or manually adding it in the code-behind file.

bannerAds