FrameBased Animation
Along with the property-based animation system, Silverlight provides a way to create frame-based animation using nothing but code. All you need to do is respond to the static CompositionTarget.Rendering event, which is fired to get the content for each frame. This is a far lower-level approach, which you won't want to tackle unless you're sure the standard property-based animation model won't work for your scenario for example, if you're building a simple side-scrolling game, creating...
A Browser History Example
Using the techniques you've just learned about, you can tackle a true Silverlight challenge integrating your application with the history list in the web browser. Ordinarily, Silverlight content exists inside a single page. Thus, no matter what takes place in that page the browser history list never changes. This can confuse users, who often expect that clicking the back button will bring them back to the previous visual in your Silverlight application, whereas it will actually end the current...
Text Selection
As you already know, you can select text in any text box by clicking and dragging with the mouse or holding down Shift while you move through the text with the arrow keys. The TextBox class also gives you the ability to determine or change the currently selected text pro-grammatically, using the SelectionStart, SelectionLength, and SelectedText properties. SelectionStart identifies the zero-based position where the selection begins. For example, if you set this property to 10, the first...
Binding to a LINQ Expression
One of Silverlight's many surprises is its support for Language Integrated Query, which is an all-purpose query syntax that was introduced in .NET 3.5. LINQ works with any data source that has a LINQ provider. Using the support that's included with Silverlight, you can use similarly structured LINQ queries to retrieve data from an in-memory collection or an XML file. The LINQ to SQL feature, which allows you to query information from a database, isn't included in Silverlight because Silverlight...
Handled Suppressed Events
When the button in Figure 4-3 receives the MouseLeftButtonDown event, it takes an extra step and marks the event as handled. This prevents the event from bubbling up the control hierarchy any further. Most Silverlight controls use this handling technique to suppress MouseLeftButtonDown and MouseLeftButtonUp so they can replace them with more useful, higher-level events like Click. However, there are a few elements that don't handle MouseLeftButtonDown and Mouse-LeftButtonUp The Image class used...
The Messenger Client
So far, you've focused exclusively on the server-side .NET application that powers the messaging server. Although this is the most complex piece of the puzzle, the Silverlight socket client also requires its fair share of code. The messaging client has three basic tasks to connect to the server, to send messages, and to receive and display them. The actual code is similar to the socket server, but requires slightly more work. That's because Silverlight doesn't have a TcpClient class, but forces...
Instantiating Silverlight Objects in the Browser
The previous example demonstrated how you can call a Silverlight method for JavaScript code. Silverlight has one more trick for code interaction it allows JavaScript code to instantiate a Silverlight object. As before, you start with a scriptable type that includes scriptable methods. Here's an example of a very basic Silverlight class that returns random numbers private Random random new Randoi ScriptableMembe public int GetRandomNumberInRange int from, int to As with the previous example, you...
The Base Class
The most straightforward way to animate a transition between pages is to code it directly in the App class, using a custom Navigate method. However, it's far more flexible and just a bit more effort to place the animation code in a separate class. And if you standardize your animations with an abstract class or an interface, you'll gain far more flexibility to swap in the new effects. In this example, all transitions inherit from an abstract class named PageTransitionBase. This class stores the...
Template Bindings
Although the revised button template respects the content of the button, it ignores most other properties. For example, consider this instance that uses the template lt Button Template StaticResource ButtonTemplate Content A Templated Button Margin 10 This markup gives the button a Margin value of 10 and a Padding of 20. The element that holds the button is responsible for paying attention to the Margin property. However, the Padding property is ignored, leaving the contents of your button...
Polygon
The Polygon is virtually the same as the Polyline. Like the Polyline class, the Polygon class has a Points collection that takes a list of coordinates. The only difference is that the Polygon adds a final line segment that connects the final point to the starting point. If your final point is already the same as the first point, the Polygon class has no difference. You can fill the interior of this shape using the Fill brush. Figure 7-7 shows the previous Polyline as a Polygon with a yellow...
Static Text
Silverlight doesn't include a Label control. The lynchpin for text display is the TextBlock element, which you've seen at work in many of the examples over the past four chapters. The TextBlock element is refreshingly straightforward. It provides a Text property, which accepts a string with the text you want to display. lt TextBlock Text This is the Alternatively, you can supply the text as nested content lt TextBlock gt This is the content. lt TextBlock gt The chief advantage of this approach...
The Bomb User Control
The next step is to create the graphical image of the bomb. Although you could use a static image as long as it has a transparent background , it's always better to deal with more flexible Silverlight shapes. By using shapes, you gain the ability to resize the bomb without introducing distortion, and you can animate or alter individual parts of the drawing. The bomb shown in this example is drawn straight from Microsoft Word's online clipart collection. The bomb was converted to XAML by...
Sending Messages
The messages in the chat application are slightly more detailed than simple strings. Each message includes three details the text, the sender's chosen name, and the sender's time when the message was submitted. These three details are encapsulated in a custom Message class public string MessageText get set public string Sender get set public DateTime SendTime get set public Message string messageText, string sender MessageText messageText Sender sender To send a message, the user enters some...
Silverlight Control Has Focus
In the Windows world, a user works with one control at a time. The control that is currently receiving the user's key presses is the control that has focus. Sometimes this control is drawn slightly differently. For example, the Silverlight button uses blue shading to show that it has the focus. To move the focus from one element to another, the user can click the mouse or use the Tab and arrow keys. In previous development frameworks, programmers have been forced to take great care to make sure...
Items Controls
Controls that wrap collections of items generally derive from the ItemsControl class. Silverlight provides just three list-based controls the ListBox, the ComboBox, and the TabControl. The ItemsControl class fills in the basic plumbing that's used by all list-based controls. Notably, it gives you two ways to fill the list of items. The most straightforward approach is to add them directly to the Items collection, using code or XAML. This is the approach you'll see in this chapter. However, if...
ASPNET and Web Services
I n Chapter 1, you learned that there were two ways to build a Silverlight project in a standalone project with an HTML test page, or alongside an ASP.NET test website. So far, most of the examples you've seen have used the first approach, which assumes that your Silverlight application is a distinct piece of programming functionality. It may exist on the same page as some server-generated content, but it doesn't need to interact with server-side code. This is often exactly the design you want....
The Core Element Events
Elements inherit their basic set of events from two core classes UIElement and FrameworkElement. As Figure 4-2 shows, all Silverlight elements derive from these elements. Figure 4-2. The hierarchy of Silverlight elements The UIElement class defines the most important events for handling user input and the only events that use event bubbling. Table 4-1 provides a list of all the UIElement events. Occurs when the focus changes to this element when the user clicks it or tabs to it . The element...
Splash Screens
If a Silverlight application is small, it will be downloaded quickly and appear in the browser. If a Silverlight application is large, it may take a few seconds to download. As long as your application takes longer than 500 milliseconds to download, Silverlight will show an animated splash screen. The built-in splash screen isn't too exciting it simply displays a ring of blinking circles and the percentage of the application that's been downloaded so far see Figure 6-4 . Tpct Ppgp Fnr ' pl h...
The ComboBox
The ComboBox is similar to the ListBox control. It holds a collection of ComboBoxItem objects, which are created either implicitly or explicitly. As with the ListBoxItem, the ComboBoxItem is a content control that can contain any nested element. Unlike combo boxes in the Windows world, you can't type in the Silverlight ComboBox control to select an item or edit the selected value. Instead, you must use the arrow keys or the mouse to pick from the list. The key difference between the ComboBox...
Mouse Movements
Along with the obvious mouse clicking events MouseLeftButtonDown and MouseLeftButtonUp , Silverlight also provides mouse events that fire when the mouse pointer is moved. These events include MouseEnter which fires when the mouse pointer moves over the element , MouseLeave which fires when the mouse pointer moves away , and MouseMove which fires at every point in between . All of these events provide your code with the same information a MouseEventArgs object. The MouseEventArgs object includes...
The Wipe Transition
To actually use a page transition, you need at least one derived class that creates animations. In this section, you'll consider one example a WipeTransition class that wipes away the old page, revealing the new one underneath. The trick to creating a wipe effect is animating a brush that uses an opacity mask. As you learned in Chapter 8, an opacity mask determines what portions of an image or element should be visible, and which ones should be transparent. To use an animation as a page...
The Storyboard Class
The storyboard manages the timeline of your animation. You can use a storyboard to group multiple animations, and it also has the ability to control the playback of animation pausing it, stopping it, and changing its position. However, the most basic feature provided by the Storyboard class is its ability to point to a specific property and specific element using the TargetProperty and TargetName properties. In other words, the storyboard bridges the gap between your animation and the property...
Data Conversion
In an ordinary binding, the information travels from the source to the target without any change. This seems logical, but it's not always the behavior you want. Often, your data source might use a low-level representation that you don't want to display directly in your user interface. For example, you might have numeric codes you want to replace with human-readable strings, numbers that need to be cut down to size, dates that need to be displayed in a long format, and so on. If so, you need a...
Transforming Shapes
To transform a shape, you assign the RenderTransform property to the transform want to use. Depending on the transform object you're using, you'll need to fill in properties to configure it, as detailed in Table 8-3. For example, if you're rotating a shape, you need to use the RotateTransform, the angle in degrees. Here's an example that rotates a square by 25 degrees lt Rectangle Width 80 Height 10 Stroke Blue Fill Yellow Canvas.Left 100 Canvas.Top 100 gt lt Rectangle.RenderTransform gt lt...
Creating a Deep Zoom Image Set
To get started, load Deep Zoom Composer and click New Project. There are three steps to building a Deep Zoom image set with Deep Zoom composer. First, you import the picture or pictures you plan to use. Next, you arrange the pictures. If you have a single picture, this won't take long. If you have multiple pictures, this is when you tile them together by hand. Finally, you export the Deep Zoom image set and create the Sil-verlight project. You can switch from one step to another using the three...
The Popup
The Popup control has a great deal in common with the ToolTip control, although neither one derives from the other. Like the ToolTip, the Popup can hold a single piece of content, which can include any Silverlight element. This content is stored in the Popup.Child property, rather than the ToolTip.Content property. Also, like the ToolTip, the content in the Popup can extend beyond the bounds of the page. Lastly, the Popup can be placed using the same placement properties and shown or hidden...
Multithreading
One of Silverlight's least expected surprises is its support for multithreading the fine art of executing more than one piece of code at the same time. It's a key part of the full .NET Framework, and a commonly used feature in rich client applications built with WPF and Windows Forms. However, multithreading hasn't appeared in the toolkit of most browser-based developers, and it's a notably absent from both JavaScript and Flash. The second surprise is how similar Silverlight's threading tools...
Key Modifiers
When a key press occurs, you often need to know more than just what key was pressed. It's also important to find out what other keys were held down at the same time. That means you might want to investigate the state of other keys, particularly modifiers such as Shift and Ctrl, both of which are supported on all platforms. Although you can handle the events for these keys separately and keep track of them in that way, it's much easier to use the static Modifiers property of the Keyboard class....
Placing the Silverlight Control Next to an HTML Element
Much as you can resize the Silverlight control using style properties, you can also reposition it. The trick is to use a CSS style that specifies absolute positioning for the Silverlight control or the lt div gt element that wraps it . You can then place the Silverlight control at the appropriate coordinates by setting the left and top style properties. For example, in Figure 12-11 the goal is to pop up the Silverlight application in a floating window overtop of the page, but next to a specific...
Video Encoding
To get the best results, you should prepare your files with Silverlight in mind. For example, you should use video files that won't overwhelm the bandwidth of your visitors. This is particularly true if you plan to use large media files for example, to display a thirty-minute lecture . Typically, the WMV files that you use in your Silverlight application will be a final product based on larger, higher-quality original video files. Often, the original files will be in a non-WMV format. However,...
Routed Events
Every .NET developer is familiar with the idea of events messages that are sent by an object such as a Silverlight element to notify your code when something significant occurs. WPF enhanced the .NET event model with a new concept of event routing, which allows an event to originate in one element but be raised by another one. For example, event routing allows a click that begins in a shape to rise up to that shape's container and then to the containing page before it's handled by your code....
Storing Objects with the XmlSerializer
As you've already seen, you can write to files in isolated storage using the same classes you use for ordinary file access in a .NET application, such as StreamWriter and BinaryWriter. To read from them, you use the corresponding StreamReader and BinaryReader classes. Although this approach gives you the most direct control over your files, it's not the only option. The XmlSerializer provides a higher-level alternative that allows you to serialize and deserialize objects rather than write and...
Requesting More Space
Initially, each Silverlight application gets 1MB of space in its isolated store. You can examine the IsolatedStorageFile.AvailableFreeSpace property to find out how much free space is remaining. If your application needs more space, there is an option you can use the IsolatedStorageFile IncreaseQuotaTo method. When you call this method, you request the number of bytes you want. Silverlight then shows a message box with the current number of bytes the application is using in isolated storage not...
Full Screen
Silverlight applications also have the capability to enter a full-screen mode, which allows them to break out of the browser window altogether. In full-screen mode, the Silverlight plug-in fills the whole display area, and is shown overtop of all other applications, including the browser. Full-screen mode has some serious limitations You can only switch into full-screen mode when responding to a user input event. In other words, you can switch into full-screen mode when the user clicks a button...
Customized ToolTips
If you want to supply more ambitious tooltip content, such as a combination of nested elements, you need to break the ToolTipService.ToolTip property out into a separate element. Here's an example that sets the ToolTip property of a button using more complex nested content lt Button Content I have a fancy tooltip gt lt ToolTipService.ToolTip gt lt StackPanel gt lt TextBlock Margin 3 Text Image and text gt lt TextBlock gt lt Image lt TextBlock Margin 3 Text Image and text gt lt TextBlock gt lt...
Running the BackgroundWorker
The first step to using the BackgroundWorker with the prime number search example is to create a custom class that allows you to transmit the input parameters to the Background-Worker. When you call BackgroundWorker.RunWorkerAsync , you can supply any object, which will be delivered to the DoWork event. However, you can supply only a single object, so you need to wrap the to and from numbers into one class, as shown here public FindPrimesInput int from, int to To start the BackgroundWorker on...
Opacity Masks
You can use the OpacityMask property to make specific regions of an element transparent or partially transparent. The OpacityMask allows you to achieve a variety of common and exotic effects. For example, you can use it to fade a shape gradually into transparency. The OpacityMask property accepts any brush. The alpha channel of the brush determines where the transparency occurs. For example, if you use a SolidColorBrush that's set to a transparent color for your OpacityMask, your entire element...
Counting Bombs and Cleaning Up
As you've seen, the BombDropper uses storyboards in two ways to animate a falling bomb and to animate a defused bomb. You could handle the completion of these storyboards with different event handlers, but to keep things simple the BombDropper uses just one. It tells the difference between an exploded and a rescued bomb by examining the Bomb.IsFalling property. End the game when 5 bombs have fallen. private int maxDropped 5 private void storyboard_Completed object sender, EventArgs e Storyboard...
Dropping the Bombs
To drop the bombs, the application uses a DispatcherTimer, a timer that plays nicely with Silverlight user interface because it triggers events on the user interface thread saving you the effort of marshalling or locking, two multithreaded programming techniques that are described in Chapter 16 . You choose a time interval, and then the DispatcherTimer fires a periodic Tick event at that interval. private DispatcherTimer bombTimer new DispatcherTimer InitializeComponent bombTimer.Tick...
ASPNET Controls That Use Silverlight
As you saw in Chapter 1, it's easy to build a simple ASRNET web application that includes Silverlight content. You simply need to create a website that includes an HTML or an .aspx test page. Although this approach allows you to place Silverlight and ASRNET pages side by side on the same website, they aren't in any way integrated. You can navigate from one page to another for example, use a link to send a user from an ASRNET web form to a Silverlight entry page , but there's no interaction...
Event Bubbling
Bubbling events are events that travel up the containment hierarchy. For example, MouseLeft-ButtonDown is a bubbling event. It's raised first by the element that is clicked. Next, it's raised by that element's parent, and then by that element's parent, and so on, until Silverlight reaches the top of the element tree. Event bubbling is designed to support composition in other words, to let you build more complex controls out of simpler ingredients. One example is Silverlight's content controls,...
Page Transitions
In Chapter 6, you saw how to support page navigation in a Silverlight application. The basic technique is to use some sort of layout container as your application's root element. You can then add user controls to this container and remove them when needed. Navigating from one page to another consists of removing the user control for the current page and adding the user control for the next page. With this framework in place, it takes just a bit more work to use an animation that switches...
Encapsulating Animations
When you create animations dynamically in code, there's a fair bit of boilerplate code required to create the animations, set the storyboard properties, and handle the Completed event to clean up. For this reason, Silverlight developers often wrap animations in higher-level classes that take care of the low-level details. For example, you might create an animation class named FadeElementEffect. You can then fade an element out of view using code like this FadeElementEffect fade new...
Storing Application Settings
A common pattern with isolated storage is to load it when the application starts or as needed , and then save it automatically when the application ends and the Application.Exit event fires. Silverlight has a higher-level class that allows you to implement this pattern to store miscellaneous pieces of information typically, application settings . This class is IsolatedStorageSettings. The IsolatedStorageSettings class provides two static properties, both of which hold collections of information...
Markers
Markers are text annotations that are embedded in a media file and linked to a particular time. Technically, the WMV format supports text markers and script commands used to do things like launch web pages while playback is underway , but Silverlight treats both of these the same, as timed bookmarks with a bit of text. Markers provide some interesting possibilities for creating smarter Silverlight-based media players. For example, you could embed captions as a set of markers, and display them...
Changing Volume Balance and Position
The MediaElement exposes a number of properties that allow you to control your playback. The most fundamental are Volume. Sets the volume as a number from 0 completely muted to 1 full volume . The default value is 0.5. To temporarily mute playback without pausing it or changing the volume setting, set IsMuted to true. Balance. Sets the balance between the left and right speaker as a number from -1 left speaker only to 1 right speaker only . CurrentState. Indicates whether the player is...
Supported File Types
Because Silverlight needs to ensure compatibility on a number of different operating systems and browsers, it can't support the full range of media files that you'll find in a desktop application like Windows Media Player. Before you get started with Silverlight audio and video, you need to know exactly what media types it supports. For audio, Silverlight supports the following Windows Media Audio WMA , versions 7, 8, and 9 MP3, with fixed or variable bit rates from 8 to 320 kbps Note Unlike...
Curves and Lines with PathGeometry
PathGeometry is the superpower of geometries. It can draw anything that the other geometries can, and much more. The only drawback is a lengthier and somewhat more complex syntax. Every PathGeometry object is built out of one or more PathFigure objects which are stored in the PathGeometry.Figures collection . Each PathFigure is a continuous set of connected lines and curves that can be closed or open. The figure is closed if the end of the last line in the figure connects to the beginning of...
The ContentPresenter
The previous example creates a rather unhelpful button that displays hard-coded text. What you really want to do is take the value of the Button.Content property and display it in your custom template. To pull this off, you need a specially designed placeholder called Content-Presenter. The ContentPresenter is required for all content controls it's the insert content here marker that tells Silverlight where to stuff the content. Here's how you can add it to the current example lt...
The TwoStep Layout Process
Every panel uses the same plumbing a two-step process that's responsible for sizing and arranging children. The first stage is the measure pass, and it's at this point that the panel determines how large its children want to be. The second stage is the layout pass, and it's at this point that each control is assigned its bounds. Two steps are required because the panel might need to take into account the desires of all its children before it decides how to partition the available space. You add...














