Providing an OnChange Event
Go Up to Navigating Days
Now that users of the calendar can change the date within the calendar, it makes sense to allow applications to respond to those changes.
Add an OnChange event to TSampleCalendar.
- Declare the event, a field to store the event, and a dynamic method to call the event: type
TSampleCalendar = class(TCustomGrid) private FOnChange: TNotifyEvent; protected procedure Change; dynamic; . . . published property OnChange: TNotifyEvent read FOnChange write FOnChange; . . .
class PACKAGE TSampleCalendar : public TCustomGrid { private: TNotifyEvent FOnChange; . . . protected: virtual void __fastcall Change(); __published: __property TNotifyEvent OnChange = {read=FOnChange, write=FOnChange}; . . . }
Write the Change method:
procedure TSampleCalendar.Change; begin if Assigned(FOnChange) then FOnChange(Self); end;
void __fastcall TSampleCalendar::Change() { if(FOnChange != NULL) FOnChange(this); }
Add statements calling Change to the end of the SetCalendarDate and SetDateElement methods:
procedure TSampleCalendar.SetCalendarDate(Value: TDateTime); begin FDate := Value; UpdateCalendar; Change; { this is the only new statement } end; procedure TSampleCalendar.SetDateElement(Index: Integer; Value: Integer); begin . { many statements setting element values } . . FDate := EncodeDate(AYear, AMonth, ADay); UpdateCalendar; Change; { this is new } end; end;
void __fastcall TSampleCalendar::SetCalendarDate(TDateTime Value) { FDate = Value; UpdateCalendar(); Change(); // this is the only new statement } void __fastcall TSampleCalendar::SetDateElement(int Index, int Value) { . . . // many statements setting element values FDate = TDateTime(AYear, AMonth, ADay); UpdateCalendar(); Change(); // this is new }
Applications using the calendar component can now respond to changes in the date of the component by attaching handlers to the OnChange event.