简体   繁体   中英

Winforms Databinding on a generic property in a custom control

I have a generic custom control that contains a property as seen below:

public T Editing
{
    get { return _editing; }
    set
    {
        if (object.ReferenceEquals(value, _editing))
            return;
        BeginInvoke(new MethodInvoker(() => UpdateOnGuiThread(value)));
    }
}

I have tried databinding this property to a property on my controller object as seen below:

_customCtrl.DataBindings.Add(new Binding("Editing", _controller, "CurrentItem"));

The controller class implements INotifyPropertyChanged and exposes the property like this:

public SpecialData CurrentItem
{
    get { return _currentItem; }
    set
    {
        _currentItem= value;
        OnPropertyChanged("CurrentItem");
    }
}

But as I broadcast PropertyChanged from my controller class the debugger will never enter in the setter of the Editing property. I've also tried the databinding below to no avail.

_customCtrl.DataBindings.Add(new Binding("Editing", _controller, "CurrentItem", false, DataSourceUpdateMode.OnPropertyChanged));

I've read https://msdn.microsoft.com/en-us/library/ms233813(v=vs.80).aspx and tried using the DefaultBindingPropertyAttribute but it doesn't help either.

Does anybody know how to get this binding to work? I thought that the binding manager would propagate the value from the controller to the control's property as PropertyChanged is broadcast in the controller class (just like a simple textbox text binding).

Any ideas?

Thanks, Sean

You should always create your bindings with FormattingEnabled property set to true . Note that FormattingEnabled=false is just for backward compatibility and unfortunately is the default.

Either use one of the Binding constructor (or ControlBindingsCollection.Add ) overloads that have a formattingEnabled parameter or set the property afterwards. In your case, something like this

_customCtrl.DataBindings.Add("Editing", _controller, "CurrentItem", true);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM