我正在尝试使用 MVVM 在 WPF 中创建一个简单的数字时钟。我有一个带有装订的标签。背后的代码很简单,每秒都会引发一个属性更改事件,并且我有一个 stackoverflow 异常。有人可以帮忙吗?
public partial class MainWindow : Window, INotifyPropertyChanged
{
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
}
private string _lblValue;
public string LabelValue
{
get
{
UpdateLabel();
return _lblValue;
}
set
{
_lblValue = value;
OnPropertyChanged(LabelValue);
}
}
private void UpdateLabel()
{
_lblValue = System.DateTime.Now.ToString();
//System.Threading.Thread.Sleep(2000);
OnPropertyChanged("LabelValue");
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propName)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propName));
}
}
}
正如 har07 所解释的,这是一个无限的 UI 循环。这是我对这个问题的修复。
public partial class MainWindow : Window, INotifyPropertyChanged
{
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
Task.Run(() => UpdateLabel());
}
private string _lblValue;
public string LabelValue
{
get
{
return _lblValue;
}
set
{
_lblValue = value;
OnPropertyChanged();
}
}
private void UpdateLabel()
{
while (true)
{
LabelValue = System.DateTime.Now.ToString();
System.Threading.Thread.Sleep(1000);
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propName = null)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propName));
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)