In certain scenarios creating a new template is not sufficient. For example the case when you want to add an interactive control, such as Button in the cell's presenter and want to attach an event handler to this button so that you can perform specific action when it is pressed. In order to implement the above scenario, you have to derive from CellPresenter and associate a custom template with the new class. For more information on how to create custom templates, check Creating New Cell TemplateCreating New Cell Template. Somewhere within the newly created template, there will be a button definition similar to the one below.
XAML Copy Code |
---|
<Button x:Name="myButton" /> |
It is important to name the button so that it can be accessed in the template class.
The definition of the custom presenter class will look similar to the following.
C# Copy Code |
---|
class MyPresenter : CellPresenter |
Visual Basic Copy Code |
---|
Class MyPresenter |
In order to attach an event handler to the button myButton, you have to override the OnApplyTemplate method, obtain a reference to the button through the GetTemplateChild method and attach an event handler to the button's Click event. Make sure to call the method of the base class in the OnApplyTemplate override. The following code illustrates how.
C# Copy Code |
---|
public override void OnApplyTemplate() |
Visual Basic Copy Code |
---|
Public Overrides Sub OnApplyTemplate() |
Now that the custom presenter and its template are ready, the presenter has to be associated with a cell. This can be done in the CellPresenterCreating event handler of the Calendar class.
C# Copy Code |
---|
private void calendar_CellPresenterCreating(object sender, CellPresenterCreatingEventArgs e) |
Visual Basic Copy Code |
---|
Private Sub calendar_CellPresenterCreating(ByVal sender As Object, ByVal e As CellPresenterCreatingEventArgs) |
For an extensive example on how to create custom cell presenters, check the new Holidays sample.