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

前端 未结 2 1654
情书的邮戳
情书的邮戳 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条回答
  • 2021-02-20 13:07

    Implementing the INotifyPropertyChanged interface is very simple. Here is a sample that shows an object with a single public field...

    public class Demo : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
    
        private void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(info));
        }
    
        private string _demoField;
    
        public string DemoField
        {
            get {return demoField; }
    
            set
            {
                if (value != demoField)
                {
                    demoField = value;
                    NotifyPropertyChanged("DemoField");
                }
            }
        }
    }
    

    Then you would create a Binding instance to bind a control property to a property (DemoField) on your source instance (instance of Demo).

    0 讨论(0)
  • 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: <propertyname>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.

    0 讨论(0)
提交回复
热议问题