Adding Events to Objects
In the first chapter, we have added a line to insert a file containing the
JavaScript code in the page. This file now will be useful to us.
The goal of this chapter is to show how the user can interact with the page
and how actions such as a click of the mouse can be recognized and associated
to programs acting on the page.
How an action is added
One calls "event manager" a program which answers an action of
the user. XAML makes it possible to handle these events, and each type of
action of the user has a corresponding name in the language.
Here how the event is processed:
- In the XAML code one adds a line of the form:
eventName="functionname" - In the Javascript file one adds a corresponding function:
function functionname()
{
...
}
Main recognized events
MouseLeftButtonDown: When one clicks on the left button of the mouse.
MouseLeftButtonUp: When it is released.
MouseEnter: The mouse enters into the surface of the object.
MouseLeave: It leaves there.
MouseMove: It moves on the surface.
Loaded: When the page is loaded.
Example of code: displaying Hello
In this simple example, the action of clicking on the page will display the
message "Hello!".
One starts with a rectangle to which one the MouseLeftButtonDown event is
added:
<Canvas etc. <Rectangle Height="100" Width="100" Fill="Yellow" MouseLeftButtonDown="hello" /> </Canvas>the JavaScript code which displays the message:
function hello () { alert("Hello!"); }
Click on the yellow rectangle:
Example of code: changing color of a circle
The JavaScript event functions can receive two argument: sender, the object
in which the event occurs, and args, a parameter list passed to the function.
Thus on can use the attributes of the object by associating them to sender
which replaces the object inside the JavaScript function.
In this example, we will draw an ellipse and when the user clicks inside this
image, its color will change from yellow to blue.
To do that we will associate the Fill attribute to sender, and we will assign
to him the new color.
<Canvas xmlns="http://schemas.microsoft.com/client/2007" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Ellipse Height="100" Width="100" Stroke="Black" Strokethickness="10" Fill="Yellow" MouseLeftButtonDown="mouseclic" /> </Canvas>
And the JavaScript codes:
function mouseclic(sender, args) { sender.Fill="LightBlue"; }
In fact the circle should remain blue, so to restore the yellow color, an additional statement was added:
MouseLeftButtonDown="mouseclic" MouseLeftButtonDown="mouseup"
With another function Javascript:
function mouseup(sender, args) { sender.Fill="Yellow"; }
See full source code:
- Javascript file. (rename myscript-js.txt to myscript.js).
- XAML code of the program "hello".
- XAML code of the program "colors of the ellipse"