开发者

Two Controls Reference One-Another Correctly

I have a ComboBox and a DateTimePicker control in a .net forms application. The desired functionality for the relationship of the two controls is that a modification to one will change the value in the other. Logic to modify the other control is in each controls change event; ComboBox "SelectedIndexChanged" and DateTimePicker "Changed" and it looks something like the following:

othercontrol.value = value;

Is there a clear way I can isolate change events from the respective controls to determine whether they were sent by the UI vs. the other control's change event to head off the loop the current setup will cause?

As I write this I realize I could probably change the other controls v开发者_开发问答alue by invoking the change event and passing some variation in the arguments from the corresponding change event instead of simply setting the other control's value.


You can remove the control's eventhandler before settings it's value and add it back immediately after setting the value.

othercontrol.SelectedChanged -= othercontrol_SelectedChanged;
othercontrol.value = value;
othercontrol.SelectedChanged += othercontrol_SelectedChanged;


Try this then.

Ok, it's a bit hacky but this would work:

private bool eventBubbledDate = false;
private bool eventBubbleCombi = false;

protected override MyCombi_OnChange(object sender, eventargs e)
{
  if (eventBubbledDate)
  {
    eventBubbledDate = false;
    return;
  }
  eventBubbleCombi = true;
  myDateTime.Value = myCombi.SelectedValue;
}

protected override MyDateTime_OnChange(object sender, eventargs e)
{
  if (eventBubbleCombi )
  {
     eventBubbleCombi = false;
     return;
  }

  // process DateStuff here
  // update other control
  eventBubbledDate = true;
}

Alternatively, you could use an Enumeration to track state instead of using boolean 'flags' but I think bools are easier to demonstrate.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜