【问题标题】:Label text not updating when bound to property绑定到属性时标签文本不更新
【发布时间】: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


【解决方案1】:

两种形式都在同一个线程上运行,即 UI 线程。正在发生以下情况:

  1. 按钮被点击
  2. 将文本更改为 i
  3. 通知界面
  4. 增加 i
  5. 转到2。如果我
  6. 刷新用户界面

只要循环没有完成,UI 线程就不会重绘,因为它仍在做一些“繁重”的工作。

您当然可以让新线程处理“计算”并让该线程更改值。要启动新线程,请使用 backgroundworker 或使用 Thread 类启动新线程。

您使用的绑定实际上是有效的。

编辑:永远记住,所有直接在 UI 线程上完成的计算都会在计算需要的时间内阻塞 UI。始终使用其他线程进行耗时的计算。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-02
    • 2016-12-30
    • 1970-01-01
    • 1970-01-01
    • 2012-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多