Page 1

First Look: Microsoft Silverlight 3 ®

Laurence Moroney


PUBLISHED BY Microsoft Press A Division of Microsoft Corporation One Microsoft Way Redmond, Washington 98052-6399 Copyright Š 2009 by Laurence Moroney Information in this document, including URL and other Internet Web site references, is subject to change without notice. Unless otherwise noted, the example companies, organizations, products, domain names, email addresses, logos, people, places, and events depicted herein are fictitious, and no association with any real company, organization, product, domain named, e-mail address, logo, person, place, or event is intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without express written permission of Microsoft Corporation. 1 2 3 4 5 6 7 8 9 QWT 4 3 2 1 0 9 Microsoft, Microsoft Press, IntelliSense, Silverlight, Visual Studio and Windows are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries. This book expresses the author's views and opinions. The information contained in this book is provided without any express, statutory, or implied warranties. Neither the authors, Microsoft Corporation, nor its resellers or distributors will be held liable for any damages caused or alleged to be caused either directly or indirectly by this book.

Body Part No. X15-53872


Some of the New Features in Silverlight 3 If you’re familiar with Silverlight 2, you will already have a grounding in .NET and how it can be used to build Rich Interactive Internet applications using Silverlight. But Silverlight 3 adds a whole host of new features to Silverlight, some of which are discussed here. If you aren’t familiar with Silverlight, some of the code and XAML here might look a little strange, so it might be a good idea to skip over this section and read the rest of the book first. If you already are familiar with Silverlight, then go ahead and enjoy this section! In this section we’ll look at some of the hotter new functions in SL3, including 3D effects, animation easing, H.264 Video support, Pixel Shaders and Out-of-Browser applications.

3D Effects with Perspective Transforms One of the most exciting features in Silverlight 3 is the addition of perspective transforms. Perspective transforms, in a nutshell, are transforms that can be applied to XAML elements to simulate rotation in a 3D space. Note that it isn’t true 3D as it doesn’t have 3D mesh models, shading, hidden line removal and so on, but it’s good for simulating 3D effects with your XAML. Let’s take a look at how this works: <Grid x:Name="LayoutRoot" Background="White"> <Image Source="bull.jpg"> </Image> </Grid>

Here we see XAML that defines the image of a bull. (If I told you the story of where and how I took this picture, you probably wouldn’t believe me!) If we execute this in the browser with Silverlight we’ll see an image like that in Figure 1. Now, consider the screen to be a 3D space with the X axis running left to right, the Y axis running up and down and the Z axis running in and out. If you want to rotate the image so that it appears to be in 3D, with the perspective being that the left side of the image is “inside” the screen, and the right side of the image is “outside” the screen, you would rotate the image around the Y axis. Similarly, if you want to rotate the image so that the top or bottom of the image is “inside” the screen, and the rest is “outside,” then you’d rotate it around the X-axis.

55


56

Introducing Microsoft Silverlight 3

FIGURE 1

Viewing the bull image without perspective

Think about it for a moment. At first, you may think that the image needs to rotate around the Z axis, but that’s the “in-out” plane, so a rotation on that axis, in 3D space, will change only the angle at which the picture is viewed. So, here’s how to rotate the picture to give it perspective, with a 45 degree rotation on the Y axis: <Grid x:Name="LayoutRoot" Background="White"> <Image Source="bull.jpg"> <Image.Projection> <PlaneProjection RotationY="45"></PlaneProjection> </Image.Projection> </Image> </Grid>

You can see the results of this in Figure 2.


Some of the New Features in Silverlight 3.0

57

FIGURE 2 Rotating the image around the Y axis.

Similarly you can rotate the image around the X axis to produce a 3D perspective effect where the top or bottom of the image is “inside” the screen and the other side is “outside.” Here’s an example: <Grid x:Name="LayoutRoot" Background="White"> <Image Source="bull.jpg" Width="640" Height="480" Canvas.Top="150" Canvas.Left="0"> <Image.Projection> <PlaneProjection RotationX="45"></PlaneProjection> </Image.Projection> </Image> </Grid>

You can see the effect of this in Figure 3. Do note that Silverlight treats the image as if it were transparent so that if you rotate the image in 3D in such a way that it would appear flipped and you are now looking at its back, you would see the inverse of the image. So if we were to change the Rotation to 135 degrees, you would see something like Figure 4.


58

Introducing Microsoft Silverlight 3

FIGURE 3 Rotation around the X Axis.

FIGURE 4 Viewing the “back” of the image with a Perspective transform.


Some of the New Features in Silverlight 3.0

59

A neat trick that you can use is to animate the rotation property using a Storyboard. You’ll read more about how to use Storyboards in Chapter 5, “XAML Transformation and Animation,” so if this code looks a little odd, it will make more sense later. <UserControl x:Class="sl3dtest.Page" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="800" Height="600"> <UserControl.Resources> <Storyboard x:Name="Storyboard1"> <DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="img" Storyboard.TargetProperty="(UIElement.Projection).(RotationX)" RepeatBehavior="Forever"> <SplineDoubleKeyFrame KeyTime="00:00:00" Value="0"/> <SplineDoubleKeyFrame KeyTime="00:00:02" Value="360"/> </DoubleAnimationUsingKeyFrames> </Storyboard> </UserControl.Resources> <Grid x:Name="LayoutRoot" Background="White"> <Image x:Name="img" Source="bull.jpg" Width="640" Height="480" Canvas.Top="150" Canvas.Left="0"> <Image.Projection> <PlaneProjection RotationX="0"></PlaneProjection> </Image.Projection> </Image> </Grid> </UserControl>

This simply creates a Storyboard that executes for 2 seconds, changing the RotationX from 0 to 360 and then repeating. This has the effect of rotating the image through its X axis in 3D space constantly.

Animation Easing Easing functions are designed to allow you to create and use a variety of specialized animation effects, including bouncing or “spring” effects. Silverlight 3 ships with a number of built-in easing functions in the System.Windows.Media.Animation namespace. These will be discussed in more detail in Chapter 5, “XAML Transformation and Animation.” The use of Animation Easing functions makes it a lot easier for you to animate objects with realistic behavior without having to figure out the physics yourself. So, for example, if you want your animation to provide a realistic “bounce,”, you can either do the physics for yourself and program it that way or you can use the built-in bounce easing function, which is achieved using the new EasingFunction child of the animation tag. Consider this scenario. With Silverlight, if you want to animate the movement of an ellipse from the top to the bottom of the screen, you would use a <Storyboard> object that contains


60

Introducing Microsoft Silverlight 3 a <DoubleAnimation> targeting the ‘Top’ property of the ellipse. To add easing to this, you’d simple add the definition of the easing function, as shown here: <Canvas x:Name="LayoutRoot" Background="White"> <Canvas.Resources> <Storyboard x:Name="bounce"> <DoubleAnimation From="0" To="300" Duration="0:0:10" Storyboard.TargetName="myCircle" Storyboard.TargetProperty="(Canvas.Top)"> <DoubleAnimation.EasingFunction> <BounceEase Bounces="10" EasingMode="EaseOut" Bounciness="2"></BounceEase> </DoubleAnimation.EasingFunction> </DoubleAnimation> </Storyboard> </Canvas.Resources> <Ellipse x:Name="myCircle" Width="40" Height="40" Fill="Red" Canvas.Top="0" Canvas.Left="50"></Ellipse> </Canvas>

The EasingFunction definition (in bold) then contains the type of ease that you want to use, and each type will have different parameters to definite the ease. So, for example, to simulate a falling object bouncing, you just specify the starting and ending positions (top from 0 to 300), and use the ease to define the bouncing behavior. In this case it’s set to bounce ten times and to bounce at the end of the animation (the EasingMode is set to EaseOut). Note that Easing can take place in 3 modes: EaseIn, in which the ease takes place at the end of the animation; EaseOut, in which it takes place at the beginning of the animation; and EaseInOut, in which both take place (you EaseIn to about half way and then you EaseOut). So if you can imagine a bounce effect like we saw earlier where a value is being animated from 0 to 100 with a Bounce ease, the following will happen: x

EaseIn will start the value at 0 and move towards 100. Before it gets there it will turn back and head towards 0 again. Before it reaches 0, it will turn and head towards 100, repeating this several times until it gets to 100.

x

EaseOut will start the value at 0 and move past 100 before turning around and moving back to 100, going past it again, turning again and moving back towards 100. It will repeat this overshooting and bouncing back a few times, based on your configuration before it reaches 100.

x

EaseInOut will have a strange combination of the two, where the value bounces both at the beginning and at the end.

You can see in the earlier example that we used EaseOut as it has the more natural effect of having the ball ‘bounce’ when it hits the hard surface beyond 100. The built-in Easing functions are found in the System.Windows.Media.Animation namespace. In the following descriptions, the descriptions will be based on the EaseIn mode. You can


Some of the New Features in Silverlight 3.0

61

deduce the EaseOut and EaseInOut effects from these. While this text gives a brief description of the functions, the differences between the ease modes can be subtle. It’s best to experiment with them to get the best results. The built-in Easing functions are: x

BackEase This moves the animation backwards a little before continuing. It’s a little bit like starting a car on a hill, you roll back a little before you move forward.

x

BounceEase

x

CircleEase This accelerates the animation based on a circular function, where the initial acceleration is slower and the latter acceleration is higher.

x

CubicEase This is similar to the CircleEase, but is based on the cubic formula of time causing a slower acceleration in the beginning and a more rapid one towards the end of the animation.

x

ElasticEase to a rest.

x

ExponentialEase Similar to the Circle and Cubic ease in that it is an exponential acceleration from one value to the next.

x

PowerEase This is an exponential acceleration where the value of the ease is proportional to the power of the time.

x

QuadraticEase This is very similar to the CubicEase except that in this case the value is based on the square of the time.

x

QuarticEase the time.

x

QuinticEase Again, similar to Quadratic, Cubic and Quartic. This time the value is based on the time to the power of 5.

x

SineEase

As we saw in the previous example, this creates a bouncing effect.

This is similar to the BounceEase in that it oscillates the value until it comes

Similar to Quadratic and Cubic. This time the value is based on the cube of

This accelerates the value along a sine wave.

Note that these are Classes so each has its own relevant properties that allow you to configure and fine-tune it. So, for example, if you look at BounceEase, you see that it has properties for the number of bounces that it will provide and the “bounciness” of the animation (for example, the variation in value bounds as it changes direction). When using an Ease, check out the API documentation carefully in order to get it just right.


62

Introducing Microsoft Silverlight 3

H264 Video Support Silverlight 3 adds H264 decoder support so that the <MediaElement> within Silverlight can play back H264 encoded content. This is an important step for companies that have invested in digitizing their assets with this format, and who would like to take advantage of Silverlight for building rich user interfaces. If you haven’t played with H264 before, you can do so with the full version of Expression Encoder 2, which, with Service Pack 1, added supports encoding into this format. If you don’t have Expression Encoder 2, there’s a free encoder at http://www.h264encoder.com. For the rest of this section we’ll look at encoding files using Expression Encoder. With Expression Encoder you can import a file from many different formats. In this case, I’m using a MOD file as commonly produced by many camcorders. Launch Expression Encoder and select the Import button at the bottom. Point it at your file and you’ll see the file being loaded and prepared by Expression Encoder. Before you Encode, you can select the Encoder profile to use on the Encoder tab at the upper-right side. You can see the video profiles in Figure 5.

FIGURE 5 Expression Encoder Video Profiles

You can see that there are two profiles for H.264, Large and Small. Select the large one.


Some of the New Features in Silverlight 3.0

63

To select the range of video that you want to encode (should you want to clip the video), drag the yellow marker across the timeline that’s just under the video window. Right-click and select Mark In to clip everything before the marker or Mark Out to clip everything after the marker. Then click Encode. When encoding is complete, you’ll have an H.264-encoded MP4 file. This can then easily be played back using the Silverlight MediaElement. Note that Expression Encoder 2 SP1, when encoding to H.264 does not support Silverlight. This support will be available in a later release. Here’s a simple example, note that the extension used is .MP4: <UserControl x:Class="Sl3BladH264.Page" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="400" Height="300"> <Grid x:Name="LayoutRoot" Background="White"> <MediaElement AutoPlay="True" Width="400" Height="400" Source="MOV0AC.mp4"></MediaElement> </Grid> </UserControl> This will play back the H264 content using the Silverlight MediaElement. We’ll explore this further in Chapter 10. You can see an example of this in Figure 6.

FIGURE 6 Playing back H.264 content


64

Introducing Microsoft Silverlight 3

Pixel Shaders You may be familiar with Pixel Shaders from WPF. Pixel Shaders are a set of software instructions that are used to calculate the color of individual pictures onscreen. They typically execute on the GPU and, as such, operate very quickly. They are written in a shading language called HLSL, which is similar in syntax to C. The System.Windows.Media.Effects library contains built-in shaders for blurring and drop shadowing, and they can be added to an image using its Effect property in code or XAML. Hereâ&#x20AC;&#x2122;s an example: <UserControl x:Class="Sl3BladEffects.Page" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="300" Height="800"> <Canvas x:Name="LayoutRoot" Background="White"> <Image x:Name="img1" Source="bull.jpg" Width="200" Height="200" Canvas.Top="0" Canvas.Left="50"> </Image> <Image x:Name="img2" Source="bull.jpg" Width="200" Height="200" Canvas.Top="250" Canvas.Left="50"> <Image.Effect> <BlurEffect Radius="10"></BlurEffect> </Image.Effect> </Image> <Image x:Name="img3" Source="bull.jpg" Width="200" Height="200" Canvas.Top="450" Canvas.Left="50"> <Image.Effect> <DropShadowEffect ShadowDepth="10"></DropShadowEffect> </Image.Effect> </Image> </Canvas> </UserControl>

You can see how this looks in Figure 7


Some of the New Features in Silverlight 3.0

FIGURE 7 Using the Blur and Drop Shadow built-in effects.

You can code your own shaders using HLSL. Detail on how to do this is beyond the scope of this book, but for the purposes of demonstration we’ll look at a simple example here. In WPF (and Silverlight) the effects are usually coded as an .FX file. Here’s an example of one that has a “gray” effect on an image: sampler2D implicitInput : register(s0); float4 main(float2 uv : TEXCOORD) : COLOR { float4 color = tex2D(implicitInput, uv); float4 complement; complement.rgb = color.r*.3 + color.g*.59 + color.b*.11; complement.a = color.a;

return complement; }

65


66

Introducing Microsoft Silverlight 3 It produces the gray effect by finding the color of the pixel and multiplying its Red, Green and Blue values by a fraction. This example reduces the Red channel to 30% of its intensity, the Green to 59% of its intensity, and the Blue to 11% of its intensity. This HLSL is compiled into a PS file (the source is usually stored in a .fx file) which needs to be available to your Silverlight application. This is achieved using the ‘fxc’ tool in the DirectX SDK. You can then create a class that derives from ShaderEffect and create a Brush from it like the follow example. Note that the URISource for the PixelShader points to the compiled ps. public class ApplyGreyEffect : ShaderEffect { private static PixelShader _pixelShader = new PixelShader() { UriSource = new Uri("ps/Greyeffect.ps", UriKind.RelativeOrAbsolute) }; public static readonly DependencyProperty InputProperty = ShaderEffect.RegisterPixelShaderSamplerProperty("Input", typeof(ApplyGreyEffect), 0); public ApplyGreyEffect() { PixelShader = _pixelShader; UpdateShaderValue(InputProperty); } public Brush Input { get { return (Brush)GetValue(InputProperty); } set { SetValue(InputProperty, value); } } }

You can now use the custom class as a Shader in code. ApplyGreyEffect _effect = new ApplyGreyEffect(); Img1.Effect = _effect;

Out-of-Browser Applications Starting with Silverlight 3 you can now write out-of-browser applications in SIlverlight. This allows you to create an application that encapsulates its own window and that can be added to the Start menu or the Desktop. Doing so is very straightforward as you’ll see in a moment—you simply add some configuration to the application manifest to inform it that you want it to also run offline. Create a new Silverlight application called SlOOB. Add something simple, like a “Hello World” TextBlock to the default page and execute it. You’ll see it running in the browser as usual. However, if you right-click the Silverlight content, you’ll see a new menu item, Save for Offline Use, which is greyed out. You can see this in Figure 8.


Some of the New Features in Silverlight 3.0

67

FIGURE 8 Out of Browser is disabled.

To enable this functionality, you’ll have to make some changes to the Application manifest. You can find this as AppManifest.xml in the Properties folder. It will look something like this: <Deployment xmlns="http://schemas.microsoft.com/client/2007/deployment" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" > <Deployment.Parts> </Deployment.Parts> </Deployment>

The first thing you need to add is the EntryPointAssembly and EntryPointType settings. For the SLOOB application these should be SLOOB and SLOOB.App respectively. Now your manifest should look like this: <Deployment xmlns="http://schemas.microsoft.com/client/2007/deployment" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" EntryPointAssembly="SLOOB" EntryPointType="SLOOB.App"> <Deployment.Parts> </Deployment.Parts> </Deployment>

Next, you’ll need to add an Application Identity section to the manifest. This contains the short name, title and blurb settings for your application. x

The Title is displayed in the Title bar for the standalone window that runs the application.

x

The Short name is displayed in the desktop and/or Start menu shortcuts.

x

The Blurb is used in the ‘Comments’ section for the file. You can view this if you view the properties of the application in Windows Explorer.


68

Introducing Microsoft Silverlight 3 You can see these in the manifest here: <Deployment xmlns="http://schemas.microsoft.com/client/2007/deployment" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" EntryPointAssembly="SLOOB" EntryPointType="SLOOB.App"> <Deployment.Parts> </Deployment.Parts> <Deployment.ApplicationIdentity> <ApplicationIdentity ShortName="My Cool App's Short Name" Title="My Cool App's Title"> <ApplicationIdentity.Blurb> Do really cool stuff at home or on the go. </ApplicationIdentity.Blurb> </ApplicationIdentity> </Deployment.ApplicationIdentity> </Deployment>

Now, if you run the application youâ&#x20AC;&#x2122;ll see that the Save for Offline Use menu item is no longer grayed out. Right-click the application to see this. When you select Save for Offline Use, Silverlight will present you with the dialog box shown in Figure 9.

FIGURE 9 Saving for Offline Use.

Note that this is a very early version of the dialog, and it may change before the final release of Silverlight. This dialog box gives you options to save your application for offline use on either the Start Menu or the Desktop. In this case, Iâ&#x20AC;&#x2122;ve selected both. Click Confirm to allow it, or No to disallow it.


Some of the New Features in Silverlight 3.0

69

If you click Confirm the icons will be saved and the application will launch in its own window. You can see this in Figure 10.

FIGURE 10 Application running in its own window

Note that you can right-click this application to get a Remove This Application option, which removes it from wherever you’ve installed it. These samples show the application with the default icons that Silverlight provides. You can override these with PNG files that represent four different icon sizes. So you need to provide a 16x16, a 32x32, a 64x64, and a 128x128 PNG that represent the desired icons. You’ll need to add a definition to the Application manifest that defines these sizes and file locations and set the Icons Build Action in Visual Studio to ‘Content’. Here’s the Application Manifest: <Deployment xmlns="http://schemas.microsoft.com/client/2007/deployment" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" EntryPointAssembly="SLOOB" EntryPointType="SLOOB.App"> <Deployment.Parts> </Deployment.Parts> <Deployment.ApplicationIdentity> <ApplicationIdentity ShortName="My Cool App's Short Name" Title="My Cool App's Title"> <ApplicationIdentity.Blurb> Do really cool stuff at home or on the go. </ApplicationIdentity.Blurb> <ApplicationIdentity.Icons> <Icon Size="16x16">sl16.png</Icon> <Icon Size="32x32">sl32.png</Icon> <Icon Size="64x64">sl64.png</Icon> <Icon Size="128x128">sl128.png</Icon> </ApplicationIdentity.Icons> </ApplicationIdentity> </Deployment.ApplicationIdentity> </Deployment>

So now, when you run the application and save it for offline use, it will have your icon!


70

Introducing Microsoft Silverlight 3

Save File Dialog Box Silverlight 3 now includes a Save File dialog box to allow your users to save content to their hard disk. They aren’t limited to isolated storage when using this. Here’s a simple example of using the Save File dialog box in your applications. First, create a new Silverlight application called SFDialog. Amend the default Page.xaml to have a Text Box and a Button. Wire a click event up to the button. By the time you’re done, your XAML should look something like this: <UserControl x:Class="SFDialog.Page" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="400" Height="300"> <Grid x:Name="LayoutRoot" Background="White"> <StackPanel Orientation="Horizontal" Height="30"> <TextBox x:Name="tts" Text="Type Text here..."></TextBox> <Button x:Name="btn" Content="Save me!" Click="btn_Click"></Button> </StackPanel> </Grid> </UserControl>

Upon clicking the button, you’re going to get a Save File dialog box. When the user selects a file using this dialog, a text file containing the text that was typed into the Text Box will be written to the file system. This all takes place in the ‘btn_Click’ event. Here’s the code: private void btn_Click(object sender, RoutedEventArgs e) { SaveFileDialog mySaveDialog = new SaveFileDialog(); bool? ret = mySaveDialog.ShowDialog(); if (ret == true) { using (Stream fs = (Stream)mySaveDialog.OpenFile()) { byte[] info = (new UTF8Encoding(true)).GetBytes(tts.Text); fs.Write(info, 0, info.Length); fs.Close(); } } }

This, of course is for illustrative purposes, and doesn’t have a lot of the validation and error checking that you’d need in a real application. It assumes the user always enters a valid path.


Some of the New Features in Silverlight 3.0

71

The code creates a new instance of the SaveFileDialog class and calls its ShowDialog() method. This shows it, and when the user clicks OK or Cancel will return flow to the program with the state of the dialog box stored in this instance of the class. So if the user clicks OK after typing a file, the OpenFile() method will actually open that file for writing. The rest of the code then serializes the contents of the Text Box into a byte stream that can be written. Letâ&#x20AC;&#x2122;s take a look at this in action. Figure 11 shows the application:

FIGURE 11 The application containing the text to be saved

When the Save Me button is clicked, the Save File dialog box is displayed. You can see that in Figure 12. As I am running Windows 7, you can see that it is the standard Windows 7 dialog box.


72

Introducing Microsoft Silverlight 3

FIGURE 12 The Save File dialog box

I didn’t give a default file name or type, so these are empty. If testing this, enter a valid file name such as Test.txt, and ignore the type, and then click Save. Your file will be written to the desired location. In this case you can see that I have selected the desktop as my destination, so the text file is written to the desktop. Open the file and you’ll see that it has the content that was typed into the text box earlier. The SaveFileDialog class has properties that allow you to set a list of file filters as well as the currently selected one. The format for the filters is a bar separated list containing textual description followed by the filter followed by the next textual description, and so on. So the classic Save dialog that allows you to pick a text file (*.txt) or all files (*.*) would be defined like this: mySaveDialog.Filter = "Text Files (.txt)|*.txt|All Files|*.*";

You can also specify the default filter to use. This is an integer value denoting the entry in the Filter list that will be the default. Note that it isn’t zero based, so if you want ‘Text files (.txt)’ to be the default, you would set the ‘FilterIndex’ property, like this: mySaveDialog.FilterIndex = 1;

Figure 13 now shows your new and improved Save File dialog box.


Some of the New Features in Silverlight 3.0

73

FIGURE 13 Save As dialog box with filters

So now you can give your users the ability to save information out to the hard drive in whatever location they desire.

XAML Element Databinding When binding components in XAML together, you usually need a developer to get involved. So if you want to set the width of an object using a slider, some code is needed to pull the value of the slider, find the appropriate object by name (the designer may not name all visual elements so the coder has to add a name) and set its width property. This leads to lots of scenarios in which code has to be written to handle very mundane tasks. Silverlight 3 introduces element data binding. This allows you to bind elementâ&#x20AC;&#x2122;s properties to each other so that when one changes, the bound elements change, too. Consider the above scenarioâ&#x20AC;&#x201D;you can now do this codelessly with a little data binding in XAML. Take a look at this code block. Here we have a Slider control called slider, and a blue rectangle: <StackPanel Orientation="Vertical"> <Slider Width="400" Minimum="0" Maximum="400" Value="200" x:Name="slider"></Slider> <Rectangle Height="100" Fill="Blue" Width="{Binding Value, ElementName=slider}"></Rectangle> </StackPanel>


74

Introducing Microsoft Silverlight 3 You can see that the rectangle is 100 pixels high, but its width is set to a Binding value. The ElementName that it is bound to is â&#x20AC;&#x153;slider,â&#x20AC;? and the value that it gets from this element is its Value property. Thus, whenever the slider is moved, the width of the rectangle will change. You can see its default state in Figure 14.

FIGURE 14 Databinding between XAML elements

If I move the Slider to the right, its Value property will increase and so will the width of the rectangle. You can see this in Figure 15.

FIGURE 15 Widening the rectangle with the slider

Conversely, if I move the slider to the left, the Value goes down, and thus the rectangle gets narrower. You can see this in Figure 16.


Some of the New Features in Silverlight 3.0

75

FIGURE 16 Shortening the rectangle with the slider

You’ll see more on data binding and the data binding syntax in Chapter 14. This is a consistent language syntax that can be used for all data as well as for element behavior as shown here.

Conclusion In this chapter you’ve seen a few of the new and exciting things that Silverlight 3 adds to your Silverlight toolbox. This isn’t a full list by any means, and you’ve just touched the surface of some of the possibilities, in particular the Out Of Browser option. This chapter is written to give you a taste of what is possible. Be sure to check back on the full book when it is published later this year for more details.

test  

test a pdf

Read more
Read more
Similar to
Popular now
Just for you