How to update a property in regular intervals following mvvm pattern in WPF c#?

Boom Ba 166 Reputation points
2022-12-22T13:49:36.11+00:00

I have defined a property in my viewmodel which is supposed to basically check if todays date from the internet is same as the system date and store it in the property as some string so that I can bind it to a textblock text or a label content. But this check must run every 5 second as long as the app is open, that means the value of the property can change and it should reflect on the view accordingly. How can I do this following mvvm pattern ?

Currently I've done

 public class VM : INotifyPropertyChanged  
 {  
 private static System.Timers.Timer chkDate;  
  
 public string msg {get;set;}  
  
 public VM()  
 {  
 chkDate = new System.Timers.Timer();  
  
 chkDate.Interval = 5000; // every five seconds  
  
 chkDate.Elapsed += VerifyDate;  
  
 chkDate.AutoReset = true;  
  
 chkDate.Enabled = true;  
 }  
  
  
 public void VerifyDate(Object source, System.Timers.ElapsedEventArgs e)  
 {  
 if (IsInternetAvailable())  
 {  
 if (DateTime.Today.ToString("dd-MMM-yyyy") == GetInternetTime().ToString("dd-MMM-yyyy"))  
 {  
 msg="Machine date verified!";  
 }  
  
 else  
 msg="Machine date is not correct!";  
 }  
  
 else  
  
 {  
 msg="Machine date cannot be verified! Check internet connectivity !!!";  
 }  
  
 OnPropertyChanged("msg");  
 }  
 }  

Then in the label : <Label Content="{Binding msg}" Foreground="{Binding msg, Converter={StaticResource TextToColorConverter}}" ... />

I've also added an IValueConverter to convert the color of the text depending of whether msg is equal to a certain text or not:

public class TextToColorConverter : IValueConverter  
 {  
 public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)  
 {  
 string str = value as string;  
 if (value == null || str=="Machine date verified!")  
 return new SolidColorBrush(Colors.LightGreen);  
  
 else  
 return new SolidColorBrush(Colors.Red);  
 }  
  
 public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)  
 {  
 return null;  
 }  
  
 }  

But it is not working as intended.

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,185 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
7,001 questions
No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Peter Fleischer (Freelancer) 17,571 Reputation points
    2022-12-22T15:51:16.893+00:00

    Hi,
    your code works. Please, check your methods IsInternetAvailable() and GetInternetTime().

    My demo:

    <Window x:Class="WpfApp1.Window037"  
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"  
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  
            xmlns:local="clr-namespace:WpfApp037"  
            mc:Ignorable="d"  
            Title="Window037" Height="200" Width="400">  
      <Window.DataContext>  
        <local:VM/>  
      </Window.DataContext>  
      <Window.Resources>  
        <local:TextToColorConverter x:Key="TextToColorConverter"/>  
      </Window.Resources>  
      <StackPanel>  
        <Label Content="{Binding msg}" Foreground="{Binding msg, Converter={StaticResource TextToColorConverter}}"/>  
      </StackPanel>  
    </Window>  
      
      
    using System;  
    using System.ComponentModel;  
    using System.Runtime.CompilerServices;  
    using System.Windows;  
    using System.Windows.Data;  
    using System.Windows.Media;  
      
    namespace WpfApp037  
    {  
    	public class VM : INotifyPropertyChanged  
    	{  
    		private static System.Timers.Timer chkDate;  
      
      
      
    		public string msg { get; set; }  
      
    		public VM()  
    		{  
    			chkDate = new System.Timers.Timer();  
      
    			chkDate.Interval = 500; // every five seconds  
      
    			chkDate.Elapsed += VerifyDate;  
      
    			chkDate.AutoReset = true;  
      
    			chkDate.Enabled = true;  
    		}  
      
      
    		public void VerifyDate(Object source, System.Timers.ElapsedEventArgs e)  
    		{  
    			if (IsInternetAvailable())  
    			{  
    				if (DateTime.Today.ToString("dd-MMM-yyyy") == GetInternetTime().ToString("dd-MMM-yyyy"))  
    				{  
    					msg = "Machine date verified!";  
    				}  
      
    				else  
    					msg = "Machine date is not correct!";  
    			}  
      
    			else  
      
    			{  
    				msg = "Machine date cannot be verified! Check internet connectivity !!!";  
    			}  
      
    			OnPropertyChanged(nameof(msg));  
    		}  
      
      
      
    		Random rnd = new();  
    		private bool IsInternetAvailable() => rnd.NextDouble() > .5;  
    		private DateTime GetInternetTime() => DateTime.Today.AddDays(rnd.Next(0, 2));  
    		  
    		  
    		#pragma warning disable CS8612  
    		public event PropertyChangedEventHandler PropertyChanged;  
    		public event EventHandler? CanExecuteChanged;  
    		public void OnPropertyChanged([CallerMemberName] String info = "") =>  
    			PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(info));  
    	}  
      
    	public class TextToColorConverter : IValueConverter  
    	{  
    		public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)  
    		{  
    			string str = value as string;  
    			if (value == null || str == "Machine date verified!")  
    				return new SolidColorBrush(Colors.LightGreen);  
    			else  
    				return new SolidColorBrush(Colors.Red);  
    		}  
      
    #pragma warning disable CS8603  
    		public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)  
    			=> null;  
    	}  
    }  
    

    273432-x.gif