Поделиться через


Property-Changed Events

If you want your control to send notifications when a property named PropertyName changes, define an event named PropertyNameChanged and a method named OnPropertyNameChanged that raises the event. The naming convention in Windows Forms is to append the word Changed to the name of the property. The associated event delegate type for property-changed events is EventHandler, and the event data type is EventArgs. The base class Control defines many property-changed events, such as BackColorChanged, BackgroundImageChanged, FontChanged, LocationChanged, and others. For background information about events, see Handling and Raising Events and Events in Windows Forms Controls.

Property-changed events are useful because they allow consumers of a control to attach event handlers that respond to the change. If your control needs to respond to a property-changed event that it raises, override the corresponding OnPropertyNameChanged method instead of attaching a delegate to the event. A control typically responds to a property-changed event by updating other properties or by redrawing some or all of its drawing surface.

The following example shows how the FlashTrackBar custom control responds to some of the property-changed events that it inherits from Control. For the complete sample, see Windows Forms Control Sample.

Protected Overrides Sub OnTextChanged(ByVal e As EventArgs)
   MyBase.OnTextChanged(e)
   Invalidate()
End Sub 'OnTextChanged

Protected Overrides Sub OnBackColorChanged(ByVal e As EventArgs)
   MyBase.OnTextChanged(e)
   If Not (baseBackground Is Nothing) And Not showGradient Then
      baseBackground.Dispose()
      baseBackground = Nothing
   End If
End Sub
[C#]protected override void OnTextChanged(EventArgs e) {
   base.OnTextChanged(e);
   Invalidate();
}

protected override void OnBackColorChanged(EventArgs e) {
   base.OnTextChanged(e);
   if ((baseBackground != null) && (!showGradient)) {
      baseBackground.Dispose();
      baseBackground = null;
   }
}

See Also

Handling and Raising Events | Events in Windows Forms Controls | Properties in Windows Forms Controls