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 Item'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 ItemPresenter and associate a custom template with the new class. For more information on how to create custom templates, check Creating New Item TemplateCreating New Item 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 : ItemPresenter |
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, you need to associate the presenter with an item. In order to do this, you have to define a new Item class and associate MyPresenter with it using the ItemPresenterAttribute. To see the new presenter in action, create an item of type MyAppointment and add it to the displayed schedule.
C# Copy Code |
---|
[ItemPresenter(typeof(MyPresenter))] |
Visual Basic Copy Code |
---|
<ItemPresenter(GetType(MyAppointmentPresenter))> _ |
For an extensive example on how to create custom item presenters, check the new CustomItemTemplate sample.