1
votes

I have a custom control that has a Value property that supports two-way binding and also a ValueChanged event:

public event EventHandler ValueChanged;

[Bindable(BindableSupport.Yes, BindingDirection.TwoWay)]
public virtual MyObject Value
{
    get { return this.value; }
    set 
    {
        this.value = value;
        OnValueChanged(new EventArgs());
    }
}

private void OnValueChanged(EventArgs e)
{
    EventHandler handler = ValueChanged;
    if (handler != null)
        handler(this, e);
}

This control works fine when placed on a form and the data bindings set in the designer. The bindingsource subscribes to the event correctly and the underlying datasource gets updated accordingly.

Now, I'm creating the control dynamically by doing the following:

MyControl ctl = new MyControl();
ctl.DataBindings.Add(new Binding("Value", this.bindingSource, "SomeField", true, DataSourceUpdateMode.OnPropertyChanged));

However, by doing this, the bindingsource does not subscribe to the ValueChanged event. I checked the code generated by the designer, and there is not that makes the bindingsource register to event. I assume that adding the binding to the data bindings should do this, but it doesn't.

What could be missing here?

1

1 Answers

0
votes

Everything is fine.

Just the data binding occurs later - basically when the control is created and made visible for the first time. Btw, it's the data binding infrastructure that subscribes to the source/target events. In that regard, binding source is - well, as any other data source.

Note that if you control is never made really visible - for instance residing in an inactive tab page, the data binding will not be initialized and will not work. I guess this is supposed to be a some sort of an optimization which can cause problems if you don't know it (and even knowing it).

Anyway, if you want to be sure that your ValueChanged event is wired, you can change the code like this:

EventHandler valueChanged;
public event EventHandler ValueChanged
{
    add { valueChanged += value; }
    remove { valueChanged -= value; }
}

private void OnValueChanged(EventArgs e)
{
    EventHandler handler = valueChanged;
    if (handler != null)
        handler(this, e);
}

and put a breakpoint at the event add method.