【发布时间】:2015-09-14 10:18:30
【问题描述】:
我必须更新Label 的文本。我已经将Label 的Text 属性绑定到一个属性并实现了INotifyPropertyChanged 事件。
我的代码如下:
public partial class MyClass : UserControl, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _text;
public string ucText
{
get
{
return _text;
}
set
{
_text = value;
NotifyPropertyChanged("ucText");
}
}
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public MyClass()
{
InitializeComponent();
lblText.DataBindings.Add(new Binding("Text", this, "ucText"));
}
}
在另一种形式的Button点击事件中,我更新Label的文本如下:
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < 10000; i++)
{
myClass1.ucText = i.ToString();
}
}
这里 myClass1 是上面发布的UserControl 的对象。
在Button点击事件中,UI在更新标签时挂起,然后一旦循环完成,显示最终值:
9999
为什么我的 UI 没有反应性?我也试过了
lblText.DataBindings.Add(new Binding("Text", this, "ucText", false, DataSourceUpdateMode.OnPropertyChanged));
【问题讨论】:
-
您的 UI 线程在您处于该循环时被阻塞,并且仅在您从点击处理程序返回时更新。你到底想做什么?
-
@CharlesMager 我相信他只是在测试绑定,并希望看到他的标签实时更新。
-
我必须更新标签值。我已经编写了 for 循环来测试我的代码
-
@Abhishek 您的问题已经解决了很多次。您必须在单击事件处理程序中使用 Thread.Run 或 BackgroundWorker。
标签: c# winforms inotifypropertychanged