使用MVVM在WPF中连续显示当前时间 [英] Current Time display with continuous display in WPF using MVVM
问题描述
我想在屏幕上显示当前时间,并使用MVVM模式在WPF屏幕中进行连续更新。
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);
}
}
}
我写了这个方法
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;
}
}
我将文本块与属性绑定,但显示异常,例如 this.CurrentDateTime
为 null
。
I binded my text block with property but it is showing exception as this.CurrentDateTime
is null
.
任何
推荐答案
我不确定 RaisePropertyChanged(()=> ; this.CurrentDateTime)
。
如果要处理MVVM属性更改通知,则此代码应在您的VM中
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));
}
那么您的集合应该是
set
{
if (value != _currentDateTime)
{
_currentDateTime = value;
OnPropertyChanged("CurrentDateTime");
}
}
要不断更新时间,请使用 Timer
to continually update your time, use a Timer
然后您可以将间隔设置为1秒,并在每个计时器经过的事件上设置 CurrentDateTime
You can then set the interval to say 1 second and on each timer elapsed event set your CurrentDateTime
CurrentDateTime = DateTime.Now.ToString();
这篇关于使用MVVM在WPF中连续显示当前时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!