The Source
When you set the Source property of a MediaElement, Silverlight decides what kind of source you have and creates an appropriate source object. For example, if your path starts with mms , Silverlight assumes that your source is a streaming source from a Windows Media Server. If the source property points to a simple WMV file, a MPEG4 file, or an audio file, Silverlight assumes that you have a progressive download source in your application. In all cases, Silverlight creates an object that is...
Scale Independent Layout
Both the TextBlock element and the Glyphs element change size uniformly when scaling an object by specified scale values. For example, if you scale a 100-pixel wide TextBlock by a factor of 1.5, the new display width will be 150 pixels. With other text systems, such as the Windows Graphics Device Interface GDI drawing system, scaling the same 100-pixel wide text by a factor of 1.5 can cause that text to become 180 pixels wide or 130 pixels wide. The key to uniform scaling is subpixel...
CrossPlatform Consistency
For the display to be consistent, you must select a font that is available in all operating systems and browsers on targeted machines. Obviously if the specified font is not available on the end user's machine, text would display differently than the application author had intended. To ensure consistent display across machines, Silverlight only accepts fonts from a known list that is available on all target platforms. This chapter will discuss this font list in a later section. There are...
H
H264 video media delivery and, 178 as media source, 182 Silverlight 3 media features, 9, 177 HD video, 8, 177 Height property automatic sizing and positioning of elements, 174 ImageElement, 62 MediaElement,181 High Level Shader Language. See HLSL High Level Shader Language pixel shader Hinting, TrueType program for, 112 Hit-testing, mouse events, 125-126 HLSL High Level Shader Language pixel shader applying, 237-238 binding parameters to dependency properties, 245-246 code for, 236 compiling,...
Silverlight Principles
With Silverlight, you can write applications that Deploy through a Web browser Run in a secure environment Are visually appealing media and rich Internet applications Are easy to develop and maintain Run on a variety of operating systems and Web browsers Silverlight applications will download and launch each time a user visits a Web page with Silverlight content. You can update your application to a new version by replacing the application on the Web server. Even when the application is run...
A
AAC Advanced Audio Coding media delivery and, 179 media source and, 182 Silverlight 3 audio formats, 9 Accessibility, input events and, 127 ActualHeight and ActualWidth properties, TextBlock element, 101-102 Adaptive bit-rate streaming, 177, 179 Adobe Illustrator, exporter for XAML files, 47 Advanced Streaming Redirector ASX media delivery and, 179 as media source, 182-183 Alignment Grid element properties, 166 TextAlignment property, 103 Alpha, 239-240 Animation applications, 37-38 changing...
The Visual State Manager Algorithm
The key function in the visual state manager is the implementation of the VisualStateManager.GoToState method. When you call GoToState, the visual state manager does the following 1. Finds the visual state group for the target. 2. Does no further work if the target state and the source state are the same. 3. Creates the storyboard for the new state. As a performance optimization, Silverlight does not parse storyboard XAML in visual state groups until they are first used. 4. Starts the new...
Text 1
The simplest method to display text in Silverlight is the TextBlock element. The TextBlock element has properties for setting the text, character formatting, color, wrapping, line breaks, and alignment. You can use the TextBlock element to overlay text on top of vector graphics, images, live video, or any other content. Silverlight also supports text editing with the TextBox element. For the purposes of text display, information on the TextBlock element also applies to the TextBox element. The...
C
CLR for writing code in, 2 defining event handler for input events, 119 writing application code, 5, 36 CacheMode property, UIElement, 254-259 Caching glyphs and character related information, 112 Canvas element BlurEffect nested in, 249 creating custom XAML elements, 27-28 limitations of and when to use, 158-159 measure and arrange passes and, 176 opacity and, 79 overview of, 72 positioning elements with, 158 RenderTransform example, 73 ClearType readability of text and, 113 support in...
Data Binding Collections with ItemsControl
In Chapter 9, Controls, you learned how to use an ItemsControl element. In this section, you learn how to bind data to your ItemsControl. To bind to a list, follow these steps 1. Provide a data source that is a collection of some object type. For proper synchronization, make sure your data source properly implements INotifyCollectionChanged. 2. Use an ItemsControl element as the display container for your list. 3. Create a DataTemplate to specify the display of each item. A DataTemplate is an...
Data Sources
Data comes in many forms including XML files, Common Language Runtime CLR objects in memory, custom formats from Web service queries, and so on. For the purposes of Silverlight data binding, a data source is a set of CLR objects. Silverlight includes technologies such as Microsoft Language Integrated Query LINQ that provide both an abstraction for the data source with multiple providers for different formats and a query language to filter, sort, and manipulate that data. You can use LINQ to SQL...
Asynchronously Firing Events
Silverlight fires some mouse and keyboard events asynchronously to your application. Silverlight fires input events after layout events or per-frame callback events but before Silverlight renders content to the screen. If there are other asynchronous events such as a download complete event , those are mixed with your input events. Generally, you can rely on the relative order of input events being the same as the order the user provided the input, but the order relative to other types of...
Animation Elements
To specify an animation in Silverlight, you need some way to do the following Specify the start time and duration of your animation Specify the property to animate Specify how that property will change For example, to move a rectangle from position 0,0 to position 300,0 in 5 seconds lt EventTrigger lt EventTrigger.Actions gt lt BeginStoryboard gt lt Storyboard gt lt Storyboard gt lt BeginStoryboard gt lt EventTrigger.Actions gt lt EventTrigger gt lt Canvas.Triggers gt lt Rectangle x Name rect1...
Technical Insight Gma
One side effect of the widening process is that local self-intersection can occur. For example, the process of widening a triangle generates several self-intersections as shown in Figure 3.25. One option is to run a loop removal algorithm to remove these intersections before rasterization. However, by simply filling the new geometry with the NonZero fill rule, these self intersections are not visible to the end user. Figure 3.25 The widening process applied to a triangle Figure 3.25 The...
Debugging Tip
There are currently no tools for stepping through your pixel shader inside a Silverlight application. You can debug pixel shaders in external shader developer tools such as NVIDIA's FxComposer or ATI's RenderMoney. Another debugging approach is to display internal values in your pixel shader as colors. For example, you can display the passed in elementPosition x,y position as r,g,b colors as shown in Figure 11.6. float4 main float2 elementPosition TEXCOORD COLOR outputColor.a 1.0f outputColor.r...
Input Principles
The goal of the Silverlight input system is to delegate input events to application event handlers. Many components could respond to a mouse or keyboard event including the Web browser frame, the HTML Web page, or the many controls in your application. The design goals of Silverlight input include the following Coordinate input between the Web browser and the Silverlight application Enable you to create applications composed of several controls through an event delegation system Provide...
Under the Hood Llr
Silverlight draws an effect in three steps 1. Compiles the pixel shader to SSE2 assembly the first time the pixel shader is used. 2. Renders the contents of the UIElement to a surface whenever the UIElement contents or resolution are changed. 3. Runs the compiled program to generate effect pixels whenever UIElement contents above or contents below are dirty. The built-in BlurEffect and DropShadowEffect use intermediate surfaces to run multi-pass algorithms to generate the effect results.
Diagnose Performance Problems
The most important indicators of your application performance are the application framerate and the total memory usage. Extremely high memory usage can lead you to use more video memory than is available on the graphics card. This causes the Silverlight runtime to fall back to rendering on the CPU on some operating systems. To see the framerate and memory usage, turn on the EnableFrame RateCounter flag on the Silverlight plug-in to get the display shown in Figure 12.4. If the framerate displays...
Figures
Figure 1.1 Example Silverlight sites shown at http silverlight.net showcase 2 Figure 1.2 Installing a Silverlight application so that it can run outside the Web browser 2 Figure 1.3 Visiting a Silverlight Web page without installing the Silverlight runtime 4 Figure 2.1 Visual Studio Silverlight application project 14 Figure 2.2 Hello World application 16 FiGuRE 2.3 Application install menu 22 Figure 2.4 Application install prompt 22 Figure 2.5 Application running outside the Web browser 23...
PERFORMANCE TIP Uyj
If your data source contains a list of items that are far greater than what Silverlight can display on the screen, the ItemsControl approach shown here generates many invisible elements and slows down the performance of your application. You should filter your ItemsSource to a collection containing only those items that are visible on the screen to improve performance. You can approximate the scroll thumb size for large lists based on typical item sizes. The ListBox element in Silverlight 3...
Value Converters
In the previous examples, we mapped data items directly to property values. You may need to convert a data value from one type to another before mapping to a property value. In our previous example, suppose you had a priority associated with each data item. Furthermore, suppose you want all high priority values to display in red. First, extend the list item definition to include the Priority property public MyDataItem String name, Priority priority this.name name this.priority priority private...
VisualStateManager
To customize a built-in control, you can set the ContentControl. ControlTemplate property or the ItemsControl.ItemsTemplate property to a different template. However, you also need to understand how to use the VisualStateManager class to customize Silverlight built-in controls. The visual state manager manages transitions of states for your control by defining a standard protocol for how you define those states and transitions. For example, if you want to customize a button element, the button...
Data Synchronization and Binding Modes
After establishing a binding between a data object and an element property, you may need to synchronize data values when the data object properties change or if the element property changes. For example, if the data that is bound to a control changes, the binding needs to notify the control to update its displayed value. If a control value changes, the binding may need to write the data back to a data store. To use data binding to synchronize your data with an element property, first ensure...
Starting an Animation
In the previous example, you learned how to start an animation using a Loaded event trigger. Another common way to start an animation is in response to a mouse event. For example, you may want a hover animation on a button when the mouse is over that button. Silverlight does not currently have triggers for mouse events. To begin an animation from a mouse event, first include the animation in the Resources section of your control to prevent it from automatically starting when your content is...
Data Validation
If your data source throws an exception or a built-in Silverlight converter throws an exception, Silverlight ignores these exceptions. In the case of the ItemsControl class, the items control omits that item from the list. You may want to show a visual indicator for malformed data so that your application user can correct that data. To receive these errors, set both the NotifyOnValidationError and ValidatesOnExceptions flags on the Binding to receive validation errors Text Binding Name,...
ContentControl and ItemsControl
If you understand how the ContentControl element and the ItemsControl element work, you understand how all controls work in Silverlight. The ContentControl element has a Content property and a Template property. The Content property specifies the content that is unique to each instance of a control, whereas the Template property specifies the common appearance for all your instances. For example, each instance of a button element usually has different content text or images or content elements,...
TimeBased Animation versus FrameBased Animation
Frame-based animation subdivides an animation into a set of discrete frames by defining the content to display on each frame. For example, you could draw a rectangle at position 0,0 in frame 1, position 10,10 in frame 2, and position 20,20 in frame 3 as shown in Figure 6.1 to create an animation. Animation authoring tools could theoretically generate those frames automatically. The main drawback of frame-based animation is that the smoothness of the animation no longer varies with the CPU and...
Font Fallback
After you specify a font family or font file for your text, it is possible that font does not contain the characters needed to render the text you specified in your TextBlock element. Missing characters from a font file is common when your application specifies the font file to use and the input comes from the user in a language you did not expect. To guarantee that your text will be visible, Silverlight has a font fallback list that finds an alternative font to use if the characters are not...
CrossPlatform Consistency 1
Different operating systems have different conventions for mouse and keyboard input. For example, shortcuts on Windows usually involve the control key, and shortcuts on the Mac usually involve the command key. Built-in Silverlight controls use conventions consistent with the target operating system. For example, a TextBox element uses control x for the cut command on Windows and command x for the cut command on the Mac. If you require custom shortcuts, you must write platform-specific versions...
PERFORMANCE TIP Ycg
For TextBlock elements with TextWrapping Wrap, it is typically better to ignore the case where the TextBlock element display exceeds the specified Width than to incur the performance penalty of setting the Clip property to guarantee this condition. For TextBlock elements with TextWrapping NoWrap that require clipping to a specific width, you can improve display performance by only setting a clip when the TextBlock.ActualWidth is greater than TextBlock.Width. You can also use layout elements,...
Layout Events
Two events indicate an element has changed size the SizeChanged event and the LayoutUpdated event. The SizeChanged event indicates that the current element has changed layout size for example, in the case that its container or content has changed size. The LayoutUpdated event indicates that some layout element in the application has changed size, and not necessarily the element listening to the event. If you are making decisions local to your element, you should always use the SizeChanged...
Create Custom Controls
Now that you have learned how to customize a built-in Silverlight control, you can also write your own control that others can customize. You can, for example create a SimpleButton control that has a click handler that behaves the same as the one shown in Figure 9.7. To create your own customizable control, inherit from either the ContentControl class or ItemsControl class and define your state names and transition states using VisualStateManager.GoToState public class SimpleButton...
Custom Animation Functions New in Silverlight
To create your own easing function, you can derive from EasingFunctionBase and include your own animation progress modifying function public class Quadratic EasingFunctionBase Progress is normalized from 0-1 value range. protected override double EaseInCore double progress The input is the progress of the animation that is a normalized value between zero and one. The output is a progress value in the zero to one space, but you can exceed that value to exceed the original animation start and end...
Screen Display
After Silverlight renders a frame, it needs to get to the screen. Chapter 3 discussed how content goes from a back buffer to the screen. The following are the two most important suggestions from Chapter 3 that will improve the quality of your animation 1. Do not set a transparent background color on the plug-in object. On some operation systems, this may cause significant slowdown in animation speed. Chapter 3 discusses the reason for this extreme slowdown. 2. Do not set the plug-in object to...
Application Principles
The goal of Silverlight is to let you easily develop visually appealing Web applications. This development model includes a set of platform libraries, the ability to use a variety of .NET languages, a security model that enables Web page access to your application without an install process, out of browser applications, and a mechanism to enable designers and developers to work concurrently to create production quality Web sites. You can host your Silverlight application on a Web page without...
Building a Custom Layout
In some cases, you may want different layout behavior than the built-in layout elements provided by Silverlight. For example, suppose you want an element that can stack elements horizontally until they no longer fit, and then wrap the next elements into further horizontal stacks in new rows as shown in Figure 7.18. lt RowDefinition Height Auto gt lt Grid.RowDefinitions gt lt RowDefinition Height Auto gt lt Grid.RowDefinitions gt This type of layout is a WrapPanel element and is not in the...
Automatic Sizing and Positioning
Chapter 3, Graphics, discussed how to position graphics elements such as the Path element in a Canvas to create your application display. Manually positioning elements and determining the appropriate size can be a cumbersome process. If content changes size within a Canvas element, you also need to write code to readjust the display size and position of the graphics elements. For example, to draw a rounded rectangle surrounding some text without the layout system, as shown in Figure 7.1, you...
Easing Functions New in Silverlight
In Silverlight 3, you can now specify new interpolation functions that are non-linear by setting the EasingFunction property on an animation. For example, if you want to create a bounce animation as shown in Figure 6.5, set the EasingFunction property to BounceEase for the Canvas.Left animation gt lt EventTrigger lt EventTrigger.Actions gt lt BeginStoryboard gt lt Storyboard gt lt BounceEase gt lt Storyboard gt lt BeginStoryboard gt lt EventTrigger.Actions gt lt EventTrigger gt lt...
Multiple Monitors
If your computer has multiple graphics adapters, Silverlight picks one graphics adapter and does all rendering with that one adapter. If you move your Silverlight window to a monitor that uses a different adapter, the operating system transfers the rendered frame to the other adapter. This transfer can be a slow operation. In full-screen scenarios, Silverlight uses the graphics adapter that corresponds to the location of the full-screen window to maximize full-screen performance.
Creating an Effect
To create a custom effect, you need to write a pixel shader in a language such as the DirectX High Level Shader Language HLSL . Pixel shaders limit the length of programs that run on each pixel and can only Read bitmap image colors using samplers. A sampler is the name of the component that allows reading colors from a brush. Take parameters that provide the position in the element. Do simple math and output a color as four floating-point numbers with each channel between 0 and 1. The pixel...
Technical Insight Rzq
This result is an artifact of sampling each primitive independently. An alternative anti-aliasing mode is full screen anti-aliasing that processes all samples from all shapes simultaneously. However, Silverlight does not currently use full screen anti-aliasing because it results in slower runtime performance. To avoid these seams, you should snap edges to pixel boundaries as shown in Figure 3.38. Snapping also produces a sharper edge between the Figure 3.38 Pixel snapped rasterization Figure...
The Animation Tick
A high precision timer is necessary to ensure accurate display times for smooth animation. The mechanism to set up that timer varies with the operating system. However, in all cases, Silverlight does the following 1. Receives a timer callback indicating it is time to draw a new frame 3. Evaluates all animation objects at the current time 5. Fires any layout events required 6. Fires the per-frame callback if required 7. Incrementally redraws the changes for the current timer tick. The timer tick...
Automatic Application Resize
In addition to layout elements sizing their child elements, the Silverlight plug-in can also size the root layout element to the plug-in size for automatic application resize behavior. For example, you can specify that the Silverlight plug-in match the browser window size lt param name source lt object gt The use of 100 as a size only works in some Web browsers. To create a fully cross-platform resize behavior, you need to set the Silverlight control width and height from JavaScript each time...
StackPanel
You can use the StackPanel element to arrange other elements in a horizontal or vertical stack. For example, to stack three button elements vertically, as shown in Figure 7.8 Figure 7.8 Vertical StackPanel example lt Button Content Button 1 gt lt Button Content Button 2 gt lt Button Content Button 3 gt lt StackPanel gt lt Canvas gt To stack items horizontally, set the Orientation property on the StackPanel element to get the result shown in Figure 7.9. Figure 7.9 Horizontal StackPanel example...
DataContext Inheritance
In the previous example, the MainPage constructor set the DataContext property, whereas its child TextBlock elements specified the binding. This usage pattern works because the DataContext property is an inherited property, that is, Silverlight determines the value of the property by finding the nearest parent element with the property explicitly set. You can reset a binding object connection by either calling the ClearValue method for the property or by setting the property to some other...
TextBlock
To display a paragraph of text, you can use the TextBlock element to get the result shown in Figure 4.1. lt Canvas The TextBlock element also lets you alter the layout, formatting, and fonts used in your text display. By default, the TextBlock element displays the contained text on a single line that can exceed the Width property. To wrap text to a specified width, set the TextWrapping property to get the result shown in Figure 4.2. Microsoft Silverlight Is a cross-browser, cross-platform...
Interpolation and Key Frame Animations
Silverlight has two types of animations interpolation animations and key frame animations. An interpolation animation takes a start value and an end value and smoothly interpolates from the start to the end. A key frame animation takes several key frames and interpolates from one key frame value to the next. DoubleAnimation, ColorAnimation and PointAnimation use linear interpolation based on From and To values to calculate an intermediate value at a given point in time. The progress of an...
Font Enumeration
Silverlight maps font attributes FontFamily, TextDecorations, FontWeight, and FontStyle to a particular font file on your local machine. For example, FontFamily Arial and FontWeight Bold maps to the bold version of the Arial font contained in file Windows Fonts arialbd.ttf on Windows XP. The process of mapping font properties on a TextBlock element to a font file requires enumerating the font files available on the system and querying their font attributes. Silverlight enumerates font files the...
16 Pixel Circle
Previous sections have discussed the graphics principles and the graphics API elements. This section goes under the hood to describe how Sil-verlight draws XAML content and displays it in the browser window. Understanding this process will help you understand the Silverlight runtime performance characteristics. Furthermore, you will understand the problems solved by the runtime and the problems your application must solve. In particular, this section discusses the following The draw loop...
Applying an Effect
To use an effect, you can set the UIElement.Effect property to the desired effect object to get the result shown in Figure 11.1. Figure 11.1 Drop shadow effect applied to text lt TextBlock FontSize 24 gt lt DropShadowEffect BlurRadius 5 Opacity 0.5 gt lt TextBlock.Effect gt Silverlight 3 has two built-in effects DropShadowEffect and BlurEffect. The drop shadow effect blurs the contents of an element, applies an offset transform, converts to grayscale, and draws underneath the original content....









