使用连续显示显示当前时间 WPF 使用 MVVM

我想在屏幕上显示当前时间,并在屏幕上连续更新。 WPF 使用模板 MVVM.

我在演示模型中编写了此代码


// 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

.

有假设为什么?
已邀请:

知食

赞同来自:

我不确定你的意图与之相关的
RaisePropertyChanged/// => this.CurrentDateTime/

.

如果我们谈论照顾 MVVM 修改后通知的属性,那么此代码应该在您的 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"/;
}
}


不断更新您的时间,使用
http://msdn.microsoft.com/en-u ... .aspx
然后你可以设置间隔,例如, 1 第二,在每次计时器时,安装你的
CurrentDateTime



CurrentDateTime = DateTime.Now.ToString//;

风见雨下

赞同来自:

我不确定为什么出现这个问题,但我达到了相同的功能,但代码的一个小变化。

我在块中更改了代码
GetCurrentDateTime

方法
try



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;
}


通过此,我为计时器添加了一种新方法


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//;
}


现在它有效

要回复问题请先登录注册