Did You Know That… You can put events into your XAML or into the code behind?

There are two common idioms for creating events (and wiring up their handlers) for XAML objects.

One is to place the name of the event and the name of its handler in the XAML itself

<Canvas
 Canvas.Top="180"
 Canvas.Left="200"      
 MouseLeftButtonDown="onMouseDown"
 MouseLeftButtonUp="onMouseUp"
 MouseMove="onMouseMove">

The other is to create a link between a reference to the XAML object and its handler in the code-behind; typically in the handler for page load

this.button.addEventListener("MouseLeftButtonDown", Silverlight.createDelegate(this, this.handleMouseDown));
this.button.addEventListener("MouseLeftButtonUp", Silverlight.createDelegate(this, this.handleMouseUp));
this.button.addEventListener("MouseLeave", Silverlight.createDelegate(this, this.handleMouseLeave));

The CreateDelegate method ensures that the event is correctly routed. This method is created for you by the Silverlight 1.0 template in Visual Studio.

Silverlight.createDelegate = function(instance, method)
{
    return function() 
    {
        return method.apply(instance, arguments);
    }
}

kick it on DotNetKicks.com

About Jesse Liberty

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen Pluralsight & LinkedIn Learning courses. He was a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Xamarin Certified Mobile Developer and a Xamarin MVP and a Microsoft MVP.
This entry was posted in z Silverlight Archives and tagged . Bookmark the permalink.