简体   繁体   中英

How to set custom properties on a Winforms control bindable?

I have some properties like OverlayColor, etc that I want to bind to an instance of a different type, but the bound data just doesn't change.

I use this:

[Bindable ( true )]
public Color OverlayColor { get; set; }

The UI changes but not the bound data. Bound data's property name is Color.

As I understand the Bindable attribute is to add the property under the (DataBindings) for the current control.

To resolve the issue that you have where the OverlayColor is not updated on the binding, you have to implement the INotifyPropertyChanged interface on the object that you're binding to. When the binded object is changed you have to Raise the NotifyPropertyChanged event.

In the example below I created a Data class which I use to bind to and call the ChangeColor() method to change the color.

public class Data : INotifyPropertyChanged
{
  Color overlayColor = Color.Teal;

  public event PropertyChangedEventHandler PropertyChanged;

  public Data()
  {
  }

  public Color OverlayColor
  {
    get
    {
      return overlayColor;
    }
    set
    {
      overlayColor = value;
      NotifyPropertyChanged( "OverlayColor" );
    }
  }

  public void ChangeColor()
  {
    if ( OverlayColor != Color.Tomato )
      OverlayColor = Color.Tomato;
    else
      OverlayColor = Color.DarkCyan;
  }

  private void NotifyPropertyChanged( string propertyName )
  {
    if ( PropertyChanged != null )
      PropertyChanged( this, new PropertyChangedEventArgs( propertyName ) );
  }
}

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