代码之家  ›  专栏  ›  技术社区  ›  Jan Deinhard

是否可以将动态属性绑定到WinForms控件属性?

  •  4
  • Jan Deinhard  · 技术社区  · 16 年前

    我想将动态属性绑定到WinForms控件属性。

    在下面的示例中,我将线程的isalive属性绑定到启用按钮。

    using System;
    using System.Windows.Forms;
    using System.Threading;
    
    namespace ThreadTest
    {
      public partial class Form1 : Form
      {
        Thread thread;
    
        public Form1()
        {
          InitializeComponent();
    
          thread = new Thread(() =>
            {
              while (true)
                Thread.Sleep(125);
            }
          );
    
          button2.DataBindings.Add("Enabled", thread, "IsAlive");
        }
    
        private void buttonStart_Click(object sender, EventArgs e)
        {
          thread.Start();
        }
    
        private void buttonStop_Click(object sender, EventArgs e)
        {
          // ...
        }
      }
    }
    

    这只在启动时有效。由于线程没有活动,“停止”按钮被禁用。当我单击按钮“开始”时,我希望将按钮“停止”更改为启用。但事实并非如此。

    我是错过了什么,还是这不可能?

    2 回复  |  直到 16 年前
        1
  •  3
  •   Dan Bryant    16 年前

    线程未实现 INotifyPropertyChanged 也没有“isalive changed”事件,因此数据绑定无法识别isalive已更改。

    This blog entry 有一些使数据绑定在WinForms中工作的提示和技巧。主要要求是,如果要支持从数据源到控件的动态更新,则必须在设计要绑定到的类时考虑数据绑定。

        2
  •  1
  •   Grzenio    16 年前

    WinForms中的数据绑定相当中断,因为自动绑定只能以一种方式工作(更改UI时,对象会得到更新)。如果您拥有用于绑定的对象,那么应该实现 INotifyPropertyChanged 接口。在您的情况下,您必须手动重置绑定以使其正常工作(这样绑定就不会真正为您提供任何东西)。