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?
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
then your set should be
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
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'stry
blockand with this I have added a new method for timer
Now it is working