views:

36

answers:

2

I'd like to bind dynamic properties to WinForms control properties.

In the following example I bind the IsAlive property of a thread to the Enabled of a button.

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)
    {
      // ...
    }
  }
}

This only works on start up. The "Stop" button is disabled because the thread is not alive. When I click on button "Start" I would expect to change button "Stop" to enabled. But it does not.

Am I missing something or is this just not possible?

+3  A: 

Thread does not implement INotifyPropertyChanged, nor does it have an "IsAliveChanged" event, so there is no way for the data binding to recognize that IsAlive has changed.

This blog entry has some tips and tricks for making data binding work in WinForms. The main requirement is that the classes to which you're binding must be designed with data binding in mind if you want to support dynamic updates from the data source to the control.

Dan Bryant
+1  A: 

Data binding in WinForms are rather broken, because automagically they only work in one way (when you change the UI, the object gets updated). If you own the object used for binding, you should implement INotifyPropertyChanged interface on it. In your case you have to manually reset the bindings to make it work (so the binding is not giving you anything really)

Grzenio