Reputation: 20195
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?
Upvotes: 4
Views: 1971
Reputation: 184
Calling DataBindings broken is just not right. Broken means, something does not work as designed - but looking at the source, it works exactly the way it's designed. And with tools like Fody's ProperyChanged weaver, you can make virtually every class using INotifyPropertyChanged
Upvotes: 0
Reputation: 36649
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)
Upvotes: 1
Reputation: 27495
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.
Upvotes: 3