Accessing Elements and Their Attributes
XAML elements are accessed from the JavaScript code as for JavaScript objects
and elements of an HTML page.
A difference exists for event handlers.
Event handlers
These are the functions that are assigned by their name to the events defined
in XAML. For example to MouseLeftButtonDown, one assigns mouseDown 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 event handlers have defined parameters:
- sender, the name of the object to which the event is associated, for example
the rectangle inside which one clicks.
- args, a parameter whose nature depends on the event.
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 for use it to associate a name to the element, with
the attribute:
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 pointer sender.
As saw in the chapter Creating
a XAML project for the Web, one could create a global variable to access
the element of a ActiveX object with this line:
var app = document.getElementById("myControl");
The variable agControl, which actually one can name as one will want, 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 the properties
The properties of the objects are accessed as one does it in Javascript, by using the name of the property like 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 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 code