Mapping Template Parts in OnApplyTemplate

OnApplyTemplate is called whenever ApplyTemplate is invoked on a control. Normally, the Silverlight rendering framework handles invoking this method at the appropriate time. Custom controls that wish to take advantage of the Template Part Model need to perform the logic to find each Template Part within OnApplyTemplate. Finding the matching element can be accomplished with a call to GetTemplateChild:

// The Name of the Element expected for our Click Region private const string ClickRegionPartName = "ClickRegion";

// Private member to hold our Click Region Template Part private FrameworkElement _clickRegionElement;

public override void OnApplyTemplate() {

base.OnApplyTemplate();

// Find our Click Region Template Part _clickRegionElement =

GetTemplateChild(ClickRegionPartName) as FrameworkElement;

Hooking Up Event Handlers to Template Parts

In the case of our PartButton, we are going to want to hook up an event handler for when the Template Part is clicked. Be mindful that ApplyTemplate can be called multiple times, so it is important to clear out any existing event handlers before grabbing the Template Part.

Silverlight controls are expected to gracefully handle missing Template Parts, so make sure to add some null reference checks after looking for a particular part.

public override void OnApplyTemplate() {

base.OnApplyTemplate();

// Clear out event hanlders if this is not the first template applied if (_clickRegionElement != null) {

_clickRegionElement.MouseLeftButtonUp -=

new MouseButtonEventHandler(clickRegion_MouseLeftButtonUp);

// Find our Click Region Template Part _clickRegionElement =

GetTemplateChild(ClickRegionPartName) as FrameworkElement;

if (_clickRegionElement != null) {

// Hook up a new event handler for the Mouse LeftButtonUp _clickRegionElement.MouseLeftButtonUp +=

new MouseButtonEventHandler(clickRegion_MouseLeftButtonUp);

private void clickRegion_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)

// Mouse Click Logic

Before moving on, let's finally make this control exhibit the most basic functionality of a button, the Click event:

// Click Event public event EventHandler<EventArgs> Click;

private void clickRegion_MouseLeftButtonUp(object sender,

MouseButtonEventArgs e)

this.Click(this, EventArgs.Empty);

0 0

Post a comment

  • Receive news updates via email from this site