Current Time display with continuous display in WP

2019-08-04 19:34发布

I want to display current time on my screen with continuous updating in WPF screen using MVVM pattern.

I am writing this code in my view model

// creating a property
private string _currentDateTime;
public string CurrentDateTime
{
    get
    {
        return _currentDateTime;
    }
    set
    {
        if (value != _currentDateTime)
        {
            _currentDateTime = value;
            this.RaisePropertyChanged(() => this.CurrentDateTime);
        }
    }
}

and I wrote this method

 public string GetCurrentDateTime()
 {
     try
     {
         DispatcherTimer timer = new DispatcherTimer(new TimeSpan(0, 0, 1), 
             DispatcherPriority.Normal, 
             delegate
             {
                 this.CurrentDateTime = DateTime.Now.ToString("HH:mm:ss");
             },
             this.Dispatcher);

             return CurrentDateTime;
     }
     catch
     {
         return CurrentDateTime;
     }
}

I binded my text block with property but it is showing exception as this.CurrentDateTime is null.

Any suggestion why?

2条回答
相关推荐>>
2楼-- · 2019-08-04 19:38

I'm not sure what your intention is with RaisePropertyChanged(() => this.CurrentDateTime).

If it is to take care of MVVM property changed notifications, then this code should be in your VM

public event PropertyChangedEventHandler PropertyChanged;

protected void OnPropertyChanged(string propertyName)
{
    if (PropertyChanged != null)
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}

then your set should be

set
{
    if (value != _currentDateTime)
    {
        _currentDateTime = value;
        OnPropertyChanged("CurrentDateTime");
    }
}

to continually update your time, use a Timer

You can then set the interval to say 1 second and on each timer elapsed event set your CurrentDateTime

CurrentDateTime = DateTime.Now.ToString();
查看更多
来,给爷笑一个
3楼-- · 2019-08-04 20:00

I am not sure why this problem is occurring but I achieved the same functionality with this but slight change of code.

I changed the code in GetCurrentDateTime method's try block

try
{
    DispatcherTimer dispatcherTimer = new  System.Windows.Threading.DispatcherTimer();
    dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
    dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
    dispatcherTimer.Start();

    return CurrentDateTime;
}

and with this I have added a new method for timer

private void dispatcherTimer_Tick(object sender, EventArgs e)
{
    // Updating the Label which displays the current second
    this.CurrentDateTime = DateTime.Now.ToString(" HH:mm tt");

    // Forcing the CommandManager to raise the RequerySuggested event
    CommandManager.InvalidateRequerySuggested();
}

Now it is working

查看更多
登录 后发表回答