When a property is changed, it may be necessary to update other dependent properties, or the control may need to perform actions such as redrawing some or all of the display area. Any logic that you want the control to perform when a property is changed should be implemented by overriding the protected OnPropertyChanged method that your custom control inherits from System.WinForms.Control. The data for the property changed event is stored in the PropertyChangedEventArgs class.
The code fragment below shows how the OnPropertyChanged method is overriden in the custom control FlashTrackBar. The complete source code is in Win Forms Control Sample. The Text, BackColor, and BackgroundImage properties are inherited from RichControl. The showGradient
variable is a private member that is set and retrieved by the ShowGradient
custom property of FlashTrackBar.
The variable baseBackground
is a private member of type
System.Drawing.Brush.
[C#]
public class FlashTrackBar : RichControl {
……..
private bool showGradient = true;
private Brush baseBackground = null;
..
[
Category("Flash"),
Description("Determines if the track bar should display a color gradient indicating the current value.")
]
public bool ShowGradient {…}
// Looks for specific properties that have changed and updates the control.
protected override void OnPropertyChanged(PropertyChangedEventArgs e)
{
// Call the method of the base class so that regeistered delegates will //receive the event.
base.OnPropertyChanged(e);
//If the text property is changed, redraw the control
if (e.PropertyName.Equals("Text")) {
Invalidate();
}
//Free the brush resource after changing the backgroung color or image,
//else redraw the control if the trackbar is displying progress.
else if (!showGradient) {
if (e.PropertyName.Equals("BackColor") ||
e.PropertyName.Equals("BackgroundImage")) {
if (baseBackground != null) {
baseBackground.Dispose();
baseBackground = null;
}
Invalidate();
}
}
}
}