Silverlight and DOM events

Posted by: Malcolm Sheridan , on 4/23/2009, in Category Silverlight 2, 3, 4 and 5
Views: 28792
Abstract: Recently I have been focusing on how Silverlight and JavaScript work well together, and the following article shows how to attach Document Object Model (DOM) events to .NET event handlers in Silverlight.
Silverlight and DOM events
Recently I have been focusing on how Silverlight and JavaScript work well together, and the following article shows how to attach Document Object Model (DOM) events to .NET event handlers in Silverlight.
I want to demonstrate this by showing the mouse’s X and Y coordinates in a Silverlight Grid. The DOM event to connect to is the MouseMove event. I will connect to the BODY HTML MouseMove event. This means anywhere the user moves their mouse, it will display the corresponding X and Y coordinates. This can all happen thanks to the HtmlWindow.AttachEvent method. This method attaches a .NET Framework event handler to an event on the current Document Object Model (DOM).
To begin with open Visual Studio 2008 and choose File > New > Project > Silverlight > Silverlight Application. In the web application open the SilverlightApplication1TestPage.aspx markup and replace the body tag with the following code:
<body id="htmlBody">
Assigning an id to the body tag allows us to program against this tag. That’s all we need to do for the web application. Open the Silverlight project and add the following xaml to the Page UserControl:
<UserControl x:Class="SilverlightApplication1.Page"
    Width="200" Height="100">
    <Grid x:Name="LayoutRoot" Background="White">       
        <StackPanel Orientation="Vertical" Margin="5">
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="Mouse Coordinates" Margin="5" FontSize="14" Foreground="Blue" />
            <StackPanel Orientation="Horizontal">
                <TextBlock x:Name="txtClientX" Width="50" Height="25" Text="ClientX:" />
                <TextBlock x:Name="txtClientXValue" Width="50" Height="25" Foreground="Red" />
            <StackPanel Orientation="Horizontal">
                <TextBlock x:Name="txtClientY" Width="50" Height="25" Text="ClientY:" />
                <TextBlock x:Name="txtClientYValue" Width="50" Height="25" Foreground="Red" />
In the xaml above I have created a parent StackPanel that contains three children StackPanel’s. The last two StackPanel’s both contain two TextBlock controls and these will display the X and Y mouse coordinates. 
The next step is to add code that attaches to the DOM event and handle the event with a .NET event handler. Open the Page.xaml.cs file and add the following code to the constructor:
public Page()
      HtmlElement element = HtmlPage.Document.GetElementById("htmlBody");
      if (element != null)
element.AttachEvent("mousemove", new EventHandler<HtmlEventArgs>(RaiseHtmlEvent));  
Public Sub New()
       Dim element As HtmlElement = HtmlPage.Document.GetElementById("htmlBody")
       If element IsNot Nothing Then
element.AttachEvent("mousemove", New EventHandler(Of HtmlEventArgs)(AddressOf RaiseHtmlEvent))
       End If
End Sub
The GetElementById property returns an HtmlElement object which is the BODY tag in the ASPX page. To connect to the MouseMove event, you call the AttachEvent method. The first parameter is the name of the event in the DOM object. The second parameter is a delegate that will be called each time the event is fired. For the event names, the MSDN help file states:
·         For Internet Explorer: If eventName does not start with the string "on", the string is prepended to the event name (for example, "click" is changed to "onclick"). This enables developers who want to use Firefox naming conventions to attach their events automatically in Internet Explorer.
·         For other browsers: If eventName starts with the string "on", the string is removed from the event name to support browsers that have different naming conventions. (For example, "onclick" is changed to "click, and "onblur" is changed to "blur".)
You should be aware that if the DOM event is not found, nothing will happen, so it is a good idea to familiarise yourself with the DOM events. You can look here for more information about DOM events.
Returning to the code, add the following code to create the RaiseHtmlEvent delegate:
public void RaiseHtmlEvent(object sender, HtmlEventArgs e)
      txtClientXValue.Text = e.ClientX.ToString();
      txtClientYValue.Text = e.ClientY.ToString();
Public Sub RaiseHtmlEvent(ByVal sender As Object, ByVal e As HtmlEventArgs)
      txtClientXValue.Text = e.ClientX.ToString()
       txtClientYValue.Text = e.ClientY.ToString()
End Sub
The RaiseHtmlEvent method receives the HtmlEventArgs parameter. The HtmlEventArgs parameter provides details about the event that was raised. The HtmlEventArgs object contains two properties, ClientX and ClientY, that returns the x and y coordinate mouse position in pixels relative to the client area of the window. These will be displayed to the user and updated each time they move their mouse. Run the project and move the mouse around the page. You’ll see your X and Y mouse coordinates.
Silverlight DOM
What I wanted to show you in this article is how well Silverlight and JavaScript work together. Hopefully you can take this knowledge and start creating powerful Silverlight applications that interact smartly with JavaScript. 
The source code of this article can be downloaded from here

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Malcolm Sheridan is a Microsoft awarded MVP in ASP.NET, a Telerik Insider and a regular presenter at conferences and user groups throughout Australia and New Zealand. Being an ASP.NET guy, his focus is on web technologies and has been for the past 10 years. He loves working with ASP.NET MVC these days and also loves getting his hands dirty with jQuery and JavaScript. He also writes technical articles on ASP.NET for SitePoint and other various websites. Follow him on twitter @malcolmsheridan

Page copy protected against web site content infringement 	by Copyscape

Feedback - Leave us some adulation, criticism and everything in between!






jQuery CookBook