How can I prevent infinite recursion when using events to bind UI elements to fields?
- by Billy ONeal
The following seems to be a relatively common pattern (to me, not to the community at large) to bind a string variable to the contents of a TextBox.
class MyBackEndClass
{
public event EventHandler DataChanged;
string _Data;
public string Data
{
get { return _Data; }
set
{
_Data = value;
//Fire the DataChanged event
}
}
}
class SomeForm : // Form stuff
{
MyBackEndClass mbe;
TextBox someTextBox;
SomeForm()
{
someTextBox.TextChanged += HandleTextBox();
mbe.DataChanged += HandleData();
}
void HandleTextBox(Object sender, EventArgs e)
{
mbe.Data = ((TextBox)sender).Text;
}
void HandleData(Object sender, EventArgs e)
{
someTextBox.Text = ((MyBackEndClass) sender).Data;
}
}
The problem is that changing the TextBox fires the changes the data value in the backend, which causes the textbox to change, etc. That runs forever.
Is there a better design pattern (other than resorting to a nasty boolean flag) that handles this case correctly?
EDIT: To be clear, in the real design the backend class is used to synchronize changes between multiple forms. Therefore I can't just use the SomeTextBox.Text property directly.
Billy3