Your code looks good. The only thing missing is that you should call it periodically to update the UI.
Take a look at the example: https://learn.microsoft.com/en-us/dotnet/api/system.windows.threading.dispatchertimer?view=windowsdesktop-6.0
Important to note, since you want to update UI:
In order to access objects on the user interface (UI) thread, it is necessary to post the operation onto the Dispatcher of the user interface (UI) thread using Invoke or BeginInvoke. Reasons for using a DispatcherTimer as opposed to a System.Timers.Timer are that the DispatcherTimer runs on the same thread as the Dispatcher
Your only slightly modified code might then look something like this:
DispatcherTimer dispatcherTimer;
public MainWindow()
{
InitializeComponent();
DispatcherTimer_Tick(null, EventArgs.Empty);
dispatcherTimer = new DispatcherTimer();
dispatcherTimer.Interval = TimeSpan.FromSeconds(1);
dispatcherTimer.Tick += DispatcherTimer_Tick;
dispatcherTimer.Start();
}
private void DispatcherTimer_Tick(object? sender, EventArgs e)
{
PerformanceCounter upTime = new PerformanceCounter("System", "System Up Time");
upTime.NextValue();
TimeSpan ts = TimeSpan.FromSeconds(upTime.NextValue());
UpTime.Text = "UpTime: " + ts.Days + ":" + ts.Hours + ":" + ts.Minutes + ":" + ts.Seconds;
}
DispatcherTimer
to periodically call this code.