How to have bindable properties of a UserControl which work with OnPropertyChanged

前端 未结 2 1662
情书的邮戳
情书的邮戳 2021-02-20 12:48

I have a simple usercontrol (WinForms) with some public properties. When I use this control, I want to databind to those properties with the DataSourceUpdateMode set to

2条回答
  •  萌比男神i
    2021-02-20 13:15

    I think I've got this figured out. I didn't understand how change notifications were sent from control to bound datasource.

    Yes, calling OnValidating() is the wrong way.

    From what I've pieced together, there are two ways a control can notify the datasource that a property has changed.

    One way is for the control to implement INotifyPropertyChanged. I had never done this from the control side before, and I thought only the datasource side of the binding had to implement it.

    When I implemented INotifyPropertyChanged on my user control, and raised the PropertyChanged event at the appropriate time, it worked.

    The second way is for the control to raise a specific change event for each property. The event must follow the naming convention: Changed

    e.g. for my example it would be

    public event EventHandler ControlPropertyChanged

    If my property was called Foo, it would be FooChanged.

    I failed to notice the relavent part of the MSDN documentation, where it says:

    For change notification to occur in a binding between a bound client and a data source, your bound type should either:

    Implement the INotifyPropertyChanged interface (preferred).

    Provide a change event for each property of the bound type.

    This second way is how all existing WinForms controls work, so this is how I'm doing it now. I use INotifyPropertyChanged on my datasource, but I raise the Changed events on my control. This seems to be the conventional way.

提交回复
热议问题