08.01.2015 Views

Beginning Web Development, Silverlight, and ASP.NET AJAX

Beginning Web Development, Silverlight, and ASP.NET AJAX

Beginning Web Development, Silverlight, and ASP.NET AJAX

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

396<br />

CHAPTER 16 ■ PROGRAMMING SILVERLIGHT WITH XAML AND JAVASCRIPT<br />

In this case, the txtBlock var is set to a reference to the TextBlock called txt. Now that<br />

you have this, you can just change its Text property using the st<strong>and</strong>ard dot syntax.<br />

In addition to the dot syntax, you can use the setValue <strong>and</strong> getValue methods on the<br />

object. When using attached properties, you have to use this methodology. Here’s an<br />

example:<br />

txtBlock.setValue("Canvas.Top",200);<br />

Using Common Methods<br />

There are a number of methods that all XAML elements have in common. We’ll first summarize<br />

them, <strong>and</strong> then look into the more important methods that exist on specific<br />

controls.<br />

The AddEventListener <strong>and</strong> RemoveEventListener Methods<br />

One of the nice things about <strong>Silverlight</strong> is how it separates the design <strong>and</strong> developer artifacts<br />

to allow them to work together more efficiently. You can specify an event h<strong>and</strong>ler for<br />

an item by using a XAML attribute to define the name of the function that will have the<br />

code to run in response to the event. For example, you can use the syntax MouseLeftButton<br />

= "h<strong>and</strong>leClick" to declare that you want to use the JavaScript function h<strong>and</strong>leClick when<br />

this element is clicked. The drawback with this is that it involves a developer editing the<br />

XAML from the designer directly, thus breaking the separation.<br />

<strong>Silverlight</strong> allows you to avoid this by using AddEventListener to declare the h<strong>and</strong>ler at<br />

runtime. You’ll typically do this as part of <strong>Silverlight</strong> loading. Your h<strong>and</strong>ler function will<br />

take two parameters: sender, which contains a reference to the control that the event was<br />

raised on; <strong>and</strong> args, which contains any arguments associated with the event. Here’s an<br />

example:<br />

function h<strong>and</strong>leLoad(control, context, sender)<br />

{<br />

var txtBlock=control.content.findName("txt");<br />

txtBlock.addEventListener("mouseLeftButtonDown", h<strong>and</strong>leTxtClick);<br />

}<br />

function h<strong>and</strong>leTxtClick(sender,args)<br />

{<br />

alert("You clicked the Text Block");<br />

}

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!