Accessing objects and their attributes

XAML elements are accessed from the JavaScript code as JavaScript objects and HTML elements of a document. But a difference exists for event handlers.

Event handlers

There are functions that are assigned by their name to the events defined in XAML. For example to MouseLeftButtonDown, mouseDown is assigned which is the name of a function having to be executed when the event occurs, in other words when the user depresses the left button of the mouse.
These events handlers have required parameters:

Accessing inner elements

To reach the subelements of an element, the method findName is used, which is similar in operation to getElementById of DOM.
It is necessary before to use it, to associate a name to the element, with the attribute Name:

x: Name

Example:

<Canvas  MouseLeftButtonDown="javascript:clicRect">
    <Rectangle x:Name="rect" />
    <Ellipse x:Name="ell" />
</Canvas>

The Javascript function:

function clicRect(sender, args)
{
  var r = sender.FindName("rect");
}

Accessing a XAML element anywhere

If one wants to access a XAML element anywhere in the file, it could not be reached from the sender pointer.
A global variable may be created to access the element of a ActiveX object with this line:

var app = document.getElementById("myControl"); 

The variable myControl, which actually one can name as one wants, will replace sender, thus the following instruction is equivalent to that which uses sender in the preceding example:

function aFunction()
{
  var r = app.content.FindName("rect");
}

Accessing properties

Properties of the objects are accessed as for HTML elements in Javascript, by using the name of the property for the index, and that works even if it as an attached property:

<Canvas  MouseLeftButtonDown="javascript:clicRect">
    <Rectangle 
         x:Name="rect" 
         Canvas.Top="10" 
         Canvas.Left="20"
    </Rectangle>
</Canvas>

And the JavaScript function:

function clicRect(sender, args)
{
  var r = sender.FindName("rect");
  alert("Top=" + r["Canvas.Top"]);
 }

The Canvas.Top property is index of the object "r" which points on the Rectangle element named "rect", and the function alert thus displays the vertical position of the rectangle inside Canvas.

Demonstration

The full code

<Canvas  
xmlns="http://schemas.microsoft.com/client/2007"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
MouseLeftButtonDown="clicRect"
>
<Rectangle
x:Name="rect"
Canvas.Top="10"
Canvas.Left="20"
Stroke="Black"
Width="100"
Height="30"
Fill="LightBlue"
/>
</Canvas> function clicRect(sender, args)
{
var r = sender.FindName("rect");
alert("Top=" + r["Canvas.Top"]);
}