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 online courses. His latest book, Building APIs with .NET will be released early in 2025. Liberty is a Senior SW Engineer for CNH and 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 Microsoft MVP.
This entry was posted in z Silverlight Archives and tagged . Bookmark the permalink.