Click here to Skip to main content
15,346,659 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to show a live clock in my WPF project. I'm using the MVVM pattern. The problem is that the clock is not shown. I debugged _currentTime and it was getting a time value every second. How can I fix it?

What I have tried:

The ViewModel is:
MainPageViewModel
public class MainPageViewModel : INotifyPropertyChanged
    {
        private string _currentTime;
        private string _currentDate;
        public string currentTime
        {
            get
            {
                return _currentTime;
            }
            set
            {
                _currentTime = value;
                OnPropertyChanged("currentTime");
            }
        }

        public MainPageViewModel()
        {
            #region RealTime Clock
            System.Windows.Threading.DispatcherTimer Timer = new System.Windows.Threading.DispatcherTimer();

            Timer.Tick += new EventHandler(Timer_Click);

            Timer.Interval = new TimeSpan(0, 0, 1);

            Timer.Start();
            #endregion
        }
        #region RealTime Clock
        public void Timer_Click(object sender, EventArgs e)
        {
            DateTime d;
            d = DateTime.Now;
            _currentTime = string.Format("{0}:{1}:{2}", d.Hour.ToString("00"), d.Minute.ToString("00"), d.Second.ToString("00"));
        }
        #endregion


The view is:
MainWindow.xaml

.
.
<Label Grid.Column="4" HorizontalAlignment="Right" Name="Clock" Foreground="WhiteSmoke" Opacity="0.7" VerticalAlignment="Center" Content="{Binding currentTime}" />
.
.
.


Behind code for the MainView is:
C#
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        MainPageViewModel mvm = new MainPageViewModel();
        this.DataContext = mvm;
    }
}
Posted
Updated 25-Apr-22 22:28pm

1 solution

The problem is here:
_currentTime = string.Format("{0}:{1}:{2}", d.Hour.ToString("00"), d.Minute.ToString("00"), d.Second.ToString("00"));

You're setting the backing value of the property directly, rather than setting the property itself. You need to change this to:
currentTime = string.Format("{0}:{1}:{2}", d.Hour.ToString("00"), d.Minute.ToString("00"), d.Second.ToString("00"));

When you call the setter on the property, that's going to both update the _currentTime field but more importantly it's going to raise the PropertyChanged event. It's this event that's necessary for a WPF binding to know that the value has changed.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900