Silverlight Overviews and Reference

Introduction

You can use JavaScript to create Microsoft Silverlight-based applications that deliver rich, engaging user experiences with 2-D graphics, animation, images, media, and video. The following topics provide detailed information about these features:

  • Overviews provide information about working with the object model, using XAML, and adding multimedia, animation, and graphics.
  • Reference provides information about the objects, methods, properties, events, and enumerations you can use.

See Also

Other Resources

Windows Presentation Foundation SDK


Introduction to Silverlight 1.0

Silverlight SDK

Introduction to the Silverlight 1.0 SDK

Microsoft Silverlight is a cross-browser, cross-platform implementation of the .NET Framework for building and delivering the next generation of media experiences and rich interactive applications for the Web and devices. This SDK provides information for developing with the 1.0 release of Silverlight. Silverlight 1.0 utilizes the XAML markup language and JavaScript to create applications.

Note Silverlight 1.1 (currently available as an Alpha version) lets you use languages besides JavaScript, including .NET Framework languages such as C# and Visual Basic. See Microsoft Silverlight 1.1 Alpha QuickStart for more information.

This topic contains the following sections:

  • Silverlight Scenarios
  • Silverlight Features
  • Getting Started

Silverlight Scenarios

Silverlight is designed for Web page content that is connected to a host (that is, will not work offline), that deeply engages the user, and that can render on any browser. Silverlight can be used for the following Web application scenarios:

  • Web media - Branded playback with events, video, and marketing mix, dynamic videos with ads, audio playback, and so forth.
  • Rich islands on a page (mini applications) — Casual games and gadgets.
  • Web visualization elements — Navigation properties, data visualization, and ads.

For demonstrations of these types of Silverlight-based applications, see the Silverlight Showcase. For additional samples, including samples you can download, see Silverlight Samples.

Silverlight Features

Silverlight 1.0 (which uses JavaScript) provides the following features:

  • Rich content capabilities: With Silverlight, you can add a variety of rich content, including video, animations, text, 2-D graphics, and visual effects to your Web pages. These features will run in any browser and will deliver a richer customer experience than HTML alone.
  • XAML markup language: Silverlight-based applications use a powerful declarative markup language called Extensible Application Markup Language (XAML) as the foundation for creating engaging graphics, animation, and media. XAML is similar to HTML, but it is more powerful and extensible.
  • Tools: Tools such as Microsoft Expression Blend and Microsoft Expression Design improve the productivity and collaboration of designers and developers who create Silverlight-based applications.
  • Integration with the server: XAML integrates seamlessly with ASP.NET AJAX, and provides richer presentation capabilities than ASP.NET AJAX alone.
  • No compilation: JavaScript is interpreted by the browser rather than having to be compiled. You can embed JavaScript code directly in HTML files and simply refresh the Web page to test the changes you made.
  • Small download: All Silverlight-based applications require customers to download a small plug-in (1-3 MB) that is easy and fast to install.

Note For additional information about Silverlight architecture and a detailed list of features, see Silverlight Architecture Overview.

Getting Started

The following resources will help you get started creating Silverlight-based applications.

  • QuickStarts: These practical, hands-on examples help you get started creating your applications quickly, without going into a lot of detail.
    • Silverlight 1.0 QuickStart shows how to create Silverlight-based applications using XAML and JavaScript.
    • Silverlight QuickStart Using Microsoft Expression Blend demonstrates how to use Microsoft Expression Blend to create Silverlight-based applications. This design tool can greatly simplify and speed up common procedures such as drawing shapes, creating gradients, creating animations, applying transforms, and much more. A free trial of Expression Blend is available.
    • Silverlight 1.1 Alpha QuickStart shows how to create Silverlight-based applications by using Silverlight 1.1 Alpha. Like Silverlight 1.0, Silverlight 1.1 uses XAML. It also lets you use other languages (for example, C# and Visual Basic) besides JavaScript.
  • Samples: You can view and download Silverlight samples from the Silverlight Gallery. New samples are periodically added to this online resource. For larger, real-world samples, see the Silverlight Showcase.
  • Overviews: The Overviews section discusses various Silverlight development concepts such as object positioning, mouse and keyboard support, graphics, multimedia, and animations.
  • Reference: The Reference section provides documentation on all the individual objects, methods, properties, events, and enumerations used in Silverlight 1.0.


Silverlight 1.0 Architecture

This article provides a high-level overview of the Microsoft Silverlight architecture and focuses on how to build applications by using Silverlight 1.0. This document discusses only the Silverlight 1.0 feature set. (Silverlight 1.1 Alpha provides additional functionality, including common language runtime (CLR) support. See Silverlight Architecture for more information.)

This overview covers the following topics:

  • Introduction
  • Silverlight Architecture
  • Browser Plug-in
  • Element Tree
  • Javascript Programming Model
  • Rendering Engine
  • Input and Events
  • Animation System
  • Image Cache
  • Text Engine
  • Glyph Cache
  • Media Pipeline
  • Decoders
  • Downloader and Packaging
  • Ink Support

Introduction

Microsoft Silverlight is a cross-browser, cross-platform plug-in for delivering rich interactive content on the Web.

The Silverlight version 1.0 feature set includes the following:

  • Declarative content format based on Extensible Application Markup Language (XAML).
  • JavaScript-based programming model.
  • Deployment options for content: in-line with the HTML page, as loose files, or in a compressed zip package.
  • Media support, including support for Windows Media Video (WMV),Windows Media Audio (WMA), and MPEG Audio Layer-3 (MP3), delivered with Windows Media Services or progressive download. Also includes support for client-side playlists (ASX files).
  • Text.
  • Image (PNG and JPG) support.
  • Anti-aliased vector graphics engine.
  • Animation.
  • Mouse and keyboard input.
  • HTTP downloader.
  • Ink support.
  • Full-screen rendering support.

Note: You can find detailed information about many of these features in the Silverlight Overviews.

Silverlight Architecture

The Silverlight runtime enables users to integrate media, vector graphics, text, and images into an interactive application. This section discusses some of the key components provided in Silverlight 1.0.

The Silverlight 1.0 architecture
Silverlight 1.0 architecture

Browser Plug-in

At the top of the stack, a browser plug-in enables hosting in Microsoft Internet Explorer, Mozilla Firefox, or Apple Safari. The recommended hosting and deployment of the plug-in is provided in the SDK.

Primarily, the plug-in provides mechanisms for the following:

  • Setting and changing the XAML content to be executed by the runtime.
  • Retrieving objects from the runtime, for manipulation through JavaScript.
  • Downloading content incrementally.

The rendering performance of the plug-in varies with the hosting parameters specified and the complexity of the content. We recommend that you set the settings.EnableFrameRateCounter property to true during development to display the frame rate in the browser's status bar and identify performance bottlenecks.

Hosting parameters that affect the consistency and performance of your application include the following:

  • isWindowless – Setting this parameter to false will ensure the highest frame rate and will result in better visual display quality across various platforms. Windowed display is the best mode of operation for the plug-in.
  • Background – If windowless mode is required, use an opaque background instead of a translucent or fully transparent background for better performance. In particular, you should set the background to '#FF000000', where the first component is FF. The performance cost for transparent background comes from the browser re-rendering what's underneath the control each frame combined with the additional blending cost which can be orders of magnitude slower on some platform and browser combinations than others.

If your application requires the use of a windowless display and a transparent background, its performance will vary, depending on the operating system and and browser. We recommend that you test any application that uses a transparent background across all target operating systems and browsers. For additional suggestions for improving performance, see Performance Tips.

Element Tree

At the heart of a Silverlight-based application is a tree of objects, such as Path objects, Image objects, and MediaElement objects, that you compose to build an application. This tree, which is called the element tree, is conceptually similar to an HTML tree. However, it has a richer set of graphical elements than HTML, and the programming model is similar to the HTML Document Object Model (DOM). The traversal order of the tree controls the order in which the objects in the application are drawn. To build an element tree, you can use the XAML parser that is provided with Silverlight (by setting the source on the plug-in) or use the CreateFromXaml method.

You can make changes to the element tree as follows:

  • You can use the JavaScript API to change child relationships and to set properties on the content.
  • You can use the animation system to change the value of properties over time.

If your application relies on per-frame manipulation of the element tree, we recommend that you test its performance by using the various JavaScript engines that are available on different operating systems and browsers. The recommended method for manipulating the element tree over time is through the animation system. This approach is platform- and browser-independent and is the most efficient method.

For more information about the element tree, see Silverlight Object Models.

JavaScript Programming Model

All objects in Silverlight 1.0 can be manipulated through a JavaScript object model. The hosting Web page can call the content.FindName method to retrieve a named element and can subsequently set properties or call methods that are exposed by that element. In addition, you can attach keyboard and mouse event handlers to the elements or to the control. These event handlers enable the user to receive JavaScript callbacks and respond to user input.

Note When JavaScript is running, the plug-in will stop drawing. Typically, this is not an issue if minimal work is done in the event handlers. However, if your application requires substantial, CPU-intensive work on the JavaScript thread, we recommend that you split that work into smaller tasks. This will allow rendering to keep up with the desired frame rate. For additional suggestions for improving performance, see Performance Tips.

Rendering Engine

The Silverlight rendering engine is optimized for rasterizing the contents of the element tree at the desired frame rate indicated on the plug-in. In particular, the optimizations include the following:

  • Incremental redraw between frames, which reduces the number of pixels drawn based on the content that is changing.
  • Not rasterizing content that is completely or partially occluded.
  • Only rendering content that is visible. (That is, not rendering clipped content, opacity=0 content, and so on.)
  • Taking advantage of more CPU cores on the machine for significantly improved rendering performance.

The rendering engine feature set includes the following:

  • Per-primitive anti-aliasing support.
  • Support for basic shapes such as Rectangle (with optional rounded corners), Ellipse, and Image.
  • Path drawing support (see Shapes and Drawing in Silverlight Overview and Path Markup Syntax):
    • Path data: A set of segments, including arc segments, Bezier segments, line segments, poly-Bezier segments, polyline segments, poly-quadratic Bezier segments, quadratic Bezier segments.
    • Fill rules: Non-zero and odd/even.
    • Strokes: Variable-width pens.
    • Dashing: Custom dash arrays.
    • End caps: Round, flat, and miter.
  • Support for brushes (see Brushes Overview):
    • Solid color.
    • Image brush support with bilinear filtering.
    • Linear gradients.
    • Radial gradients.
    • Video brush with bilinear filtering.
  • Text rendering support (see Text and Fonts Overview):
    • Subpixel positioning.
    • Custom anti-aliasing for sharper text.
  • Transforms (see Transforms Overview):
    • Path transforms.
    • Brush transforms.
    • Text and graphics remain sharp when scaled. Image data will be resampled, and quality will vary based on the resolution of the source images.
  • Clipping:
    • Applied to a group of arbitrary drawing primitives, which could also include other nested clips, opacity effects, or opacity masks.
  • Opacity and opacity mask support:
    • Applied to a group of arbitrary drawing primitives, including other nested opacities or clips.

Although the rendering engine tries to do its best with the content it gets, you should reduce the number of primitives it processes by marking subtrees that are not visible. You can do this by setting the Visiblity property to Collapsed or by removing these subtrees from the tree. This optimization is particularly important when transitioning to full-screen mode. The windowed version of the content should be marked Visibility=Collapsed before the full-screen content is added to the tree. This practice will reduce both the content processed by the graphics engine and the number of elements walked per frame.

Input and Events

Silverlight provides a set of events that enable you to respond to actions such as changes in Silverlight state and user input (for example, mouse actions). For more information, see Silverlight Events.

Animation System

Animation can enhance your graphical creation by adding movement and interactivity. By animating a background color or applying an animated Transform, you can create dramatic screen transitions or provide helpful visual cues. You can create basic animations as well as more complex and powerful animations that use key frames. In addition, you can make these animations interactive by hooking them up to events. For more information, see Animation Overview.

Image Cache

When an image references a URL, the image is downloaded and cached in its decoded form for the duration of the application based on the URL that is specified. If you reference the image multiple times within your application, it will be retrieved from the image cache, and that usage pattern will run quickly. Referencing the same image from separate plug-ins takes advantage of the browser cache but requires the image to be decoded once for each Silverlight-based application.

For best results, the resolution of the image being downloaded should be close to the display size of the image. If the image resolution is significantly larger than the display size, bilinear filtering aliasing display artifacts can occur. If the image resolution is significantly smaller than the display size, the image will appear blurry.

In addition, picking an image resolution that is close to the display size will ensure minimum download times. If zoom effects are required where this is simply not possible, store multiple resolutions on the server and dynamically switch image sources during your animation.

Text Engine

The text engine will flow text strings within a TextBlock by applying simple formatting and explicitly positioning glyphs for precise fixed-format display. It will either use a specified font from the system (which is limited to a set that is available on all platforms) or use a specified font URI, which can refer to a TrueType font.

Glyph Cache

The glyph cache is used by the text engine to produce glyphs for rendering from font files. The glyph is optimized for readability at a particular target resolution, so an initial cost is incurred on the first frame on which text is drawn or when the scale of text changes. After this initial cost, scrolling or translation of text is significantly cheaper.

If your application requires dynamic scale changes of large text, it may be better to pick a vector representation of that effect.

Media Pipeline

The video pipeline retrieves content either through progressive HTTP download or HTTP streaming (for WMS servers), calls the decoders to decode the video, and displays with the rendering system and audio engine.

Video can have arbitrary content shown on top, scaled to full-screen sizes, used in multiple locations with VideoBrush on arbitrarily shaped paths, rotated, and so on.

If your application transitions from windowed to full-screen display, we recommend the use of a video brush that references the currently playing media element in the new full-screen content to ensure that the transition is seamless and does not require rebuffering.

If the content in your application has to react to events in the video, you can insert markers in the video stream that will be fired to the application.

For more information on using media in your application, see Media Overview.

Decoders

Silverilght 1.0 supports PNG and JPG files for imaging, Windows Media Video (WMV) files for video, and Windows Media Audio (WMA) and MP3 files for audio.

Downloader and Packaging

XAML, images, fonts, or other data can be packaged into a compressed (.zip) file and downloaded on demand with the Downloader object. We recommend that you test your application with the browser cache cleared over low-bandwidth connections to ensure efficient loading performance. If the initial load time of your application is large, you can provide a loading screen as shown by sample (insert link).

Ink Support

Ink support refers to handwriting or drawing content that has been input by using a pen, a touch screen, or a mouse. Silverlight provides an InkPresenter object that lets you accept ink-based input in your application. To recognize the text, send the data back to the server. Samples can be found at the Silverlight Gallery. For more information about this feature, see Ink Support in Silverlight.

See Also

Silverlight Overviews


What Changed Between Beta and Release of Silverlight 1.0

This document provides a list of new features, changes, and enhancements that have been made to Silverlight since the Silverlight 1.0 Beta release (MIX release May, 2007). In addition, this document provides a list of "breaking changes" that you might need to make in applications that you created using the Silverlight 1.0 Beta release, in order to make them compatible with the Silverlight 1.0 release.

Note: Another resource for breaking changes is here.

This overview covers the following topics:

  • Silverlight 1.0 Release Enhancements
  • Breaking Changes
    • Remove "javascript:" in event handlers
    • Remove "Sys."
    • Use the latest Silverlight.js
    • All Downloads are now Asynchronous
    • Glyph element FontURI is Resolved Asynchronously
    • Remove Visibility.Hidden
    • Extra check on ASX Tags Resulting in MediaFailed Event
    • New Parser Error on Invalid Double Values like "Auto"
    • OnLoad, OnError, OnResize, OnFullScreenChange are now Function Pointer Based Rather than String Based
    • Elements in <*.Resource> blocks must be named
    • The MediaElement Position property value can be greater than the MediaElement NaturalDuration property value
    • Additional Animation Run-Time Errors
    • Can No Longer Use ’\’ in URIs
    • All Shaped Transform Members are now of Type Transform instead of TransformGroup
    • Remove IsFilled Property
    • AddEventListener now Returns a Token to be Passed to removeEventListener to Un-Register Event Handlers
    • Replace <control>.settings.version Property with isVersionSupported method
    • Change enableHtmlAccess: true to enableHtmlAccess: "true"
    • The width and height properties in createObject must be string values
    • Tighter restrictions of what objects can have child objects
    • Downloader is only able to make a download from the same port as the HTML

Silverlight 1.0 Release Enhancements

  • New "root" property on Content. Enables access to the root element of the XAML DOM.
  • New “Tag” property on UIElement. Enables user storage on every Silverlight UIElement.
  • New MediaElement APIs for selecting different audio streams out of a file with multiple audio tracks. See the AudioStreamCount and AudioStreamIndex properties.
  • Improved media performance: optimized assembly instructions for the video decode.
  • Media script commands encoded in a separate stream in the video file will now raise the MediaElement’s MarkerReached event.
  • Added support for Adobe CFF fonts.
  • Improved performance for transparent controls on Safari.

Breaking Changes

The following list contains the breaking changes between the release of Silverlight 1.0 and Silverlight 1.0 Beta (Mix release of May, 2007). If you have created applications using the Beta release, please update your applications using this list as a guideline. Use the code samples, where provided, to ensure your application runs on both Beta and RTM version of Silverlight 1.0.

Remove "javascript:" in event handlers

The first example shows attaching an event handler in Beta and the second example shows how to do it in the 1.0 release.

Silverlight Beta

XAML
<canvas onMouseLeftButtonDown="javascript:myhandler"  />

Silverlight Release

XAML
<canvas onMouseLeftButtonDown="myhandler" />

Remove "Sys."

Remove "Sys." from namespaces in your code. For example, change the following beta code.

JavaScript
Sys.Silverlight.createObject(....)

To this code.

JavaScript
Silverlight.createObject(....)

Use the latest Silverlight.js

Please make sure you use the latest Silverlight.js provided to you in your applications. A few changes have been made to this file. The plug-in has been renamed from "WPFe Plug-In" to "Silverlight Plug-In". This plug-in is referred to in Silverlight.js file to detect Silverlight on the system. Also the MIME type of the plug-in was changed from application/ag-plugin to application/x-silverlight. Finally, the namespace "Sys." was removed. Make sure all instances of "Sys." are pulled from your applications.

All Downloads are now Asynchronous

Due to difficulties in providing reliable synchronous downloads across all platforms, we’ve removed this feature from our downloader API. Consequently, the 3rd parameter on the download open API has been removed as it is no longer needed. You must update open calls to remove this parameter.

Only the Beta release lets you add the extra argument to the downloader open method. Following is an example.

JavaScript
function download(host, file) {
  var dl = host.createObject("downloader");
  dl.addEventListener("completed", downloadComplete);
  // If Beta version add the extra argument
  if (_mix) {
    dl.open("get", file, true);
  } else {
    dl.open("get", file);
  }
  dl.send();
}

Glyph element FontURI is Resolved Asynchronously

When processing the XAML code, the font specified by the Glyphs FontUri attribute is downloaded separately and asynchronously. This means that text displayed by the Glyphs element will appear once the font is downloaded, in most cases after other content has already appeared.

In Silverlight 1.0, there is no event for Glyphs downloading progress when using the FontUri. To work around this you could use the Downloader object to first request the font file (and thus use the Downloader's progress events to know when Glyphs is downloaded).

Once the Downloader has finished downloading the font, you can then create a Glyphs element with the FontUri by specifying the exact same URI. Since the font is already downloaded, it would not be downloaded again and the Glyphs element should render almost instantaneously.

NOTE: This does make an assumption that the font downloaded will remain in the browser's cache (since this retentive behavior is user and browser specific, this is uncertain) and will be picked up when the Glyphs element attempts to download the same file.

Remove Visibility.Hidden

In order to reduce surface area, Visibility.Hidden was removed from the product. Prior to this change, Visibility.Hidden behaved the same as Visibility.Collapsed. Since Silverlight behavior is functionally similar to the behavior of WPF Visibility.Collapsed, Visibility.Collapsed was retained. To create content that will work consistently between Beta and 1.0, replace all occurrences of "Hidden" in both XAML and script with "Collapsed."

For JavaScript, change this Beta code.

JavaScript
sender.findName("fsm").visibility = "Hidden";

To this code.

JavaScript
sender.findName("fsm").visibility = "Collapsed";

And for XAML, change this Beta code.

XAML
<Canvas x:Name="mask" Visibility="Hidden">

To this code.

XAML
<Canvas x:Name="mask" Visibility="Collapsed">

Extra check on ASX Tags Resulting in MediaFailed Event

There is a set of ASX tags that were ignored in the Silverlight Beta release and that now result in a MediaFailed event. These tags are: PREVIEWMODE, BANNERBAR, PARAM, REPEAT, STARTMARKER, ENDMARKER and some MOREINFO tags. Also, if a REF URL fails to open, Silverlight does not fall back to other REFs in the same ENTRY. Instead, a MediaFailed event is raised.

New Parser Error on Invalid Double Values like "Auto"

More parser errors are reported in Silverlight 1.0 RTM. Applications will break now in cases where the developer sets a numeric property to an invalid value. In the Beta release, an invalid value was treated as a 0, but Silverlight 1.0 RTM throws an error when it encounters the same value. The following is an example:

XAML
<TextBlock Width="Auto" Text="Created By:" />

“Auto” is not supported in Silverlight 1.0. In the Beta release of Silverlight 1.0, the above example causes the Width to be set to 0. Since the Beta release did not clip TextBlock by Width, this did not impact the application behavior. However, this same example will generate a parser error in Silverlight 1.0 RTM.

OnLoad, OnError, OnResize, OnFullScreenChange are now Function Pointer Based Rather than String Based

We’ve changed OnLoad, OnError, OnResize and OnFullScreenChange to be function-pointer based rather than string based. In order to develop Silverlight content that works on both Beta and 1.0 RTM releases, you need to check the version and develop the application code accordingly. The following is an example using OnResize:

XAML
if (Silverlight.checkVersion(_ag, "20416")) {
  // Beta code path – use strings
  _ag.content.onResize = "javascript:onResize";
  ag.content.onFullScreenChange = "onFullScreenChanged";
} else {
  // Release code path – use function pointers
  _ag.content.onResize = onResize;
  _ag.content.onFullScreenChange = onFullScreenChanged;
}

Elements in <*.Resource> blocks must be named

Elements in <*.Resource> blocks must be named. This means you must have an x:Name property for all content in a <*.Resources> section. For example:

Silverlight Beta

XAML
<Canvas.Resources>
<Storyboard>
            <!-- Content here... -->
      </Storyboard>
 </Canvas.Resources>

Silverlight 1.0 RTM

XAML
<Canvas.Resources>
      <Storyboard x:Name="name">
              <!-- Content here... -->
       </Storyboard>
 </Canvas.Resources>

The MediaElement Position property value can be greater than the MediaElement NaturalDuration property value

This will mostly be seen in broadcast cases which had previously returned 0 for the Position value but now returns the play time. Developers creating transport controls should be aware of this and the need to clip the media if necessary. For example:

Silverlight Beta

JavaScript
// set the slider thumb position in the right range of the track’s width
// assumes position is never greater than media’s naturalDuration
sliderThumb[“Canvas.Left”] = (myME.position.seconds/myME.naturalDuration.seconds)*sliderTrack.width;

Silverlight 1.0 RTM

JavaScript
// need to clip the slider position by the track’s width
if (myME.position.seconds >= myME.naturalDuration.seconds)
      sliderThumb[“Canvas.Left”] = sliderTrack.width;
else
sliderThumb[“Canvas.Left”] = (myME.position.seconds/myME.naturalDuration.seconds)*sliderTrack.width;

Additional Animation Run-Time Errors

Silverlight 1.0 RTM is stricter than Beta in throwing run-time errors caused by functionality that is not supported. Examples of such errors are:

  • Storyboard.TargetProperty must be defined on all animations by the time they are begun. Storyboard.TargetName must either be specified on animations themselves or on a parent Storyboard by the time they are begun.
  • Certain Storyboard/Animations properties can only be modified when the Storyboard is stopped. These properties are Storyboard.TargetName and Storyboard.TargetProperty.

Can No Longer Use ’\’ in URIs

This behavior has been changed in order to maintain the cross platform support of Silverlight-based applications. All Web resources should be renamed if they include a "\". For example, use "./assets/images/bg.jpg" instead of ".\assets\images\bg.jpg”

All Shaped Transform Members are now of Type Transform instead of TransformGroup

This behavior has been changed in order to be consistent across Silverlight and WPF. For example, RTM brush.relativeTransform.toString() will return "Transform" rather than "TransformGroup."

Remove IsFilled Property

The IsFilled property on PathFigure is no longer supported. Developers should remove it from their application code.

Silverlight Beta

XAML
<PathFigure IsFilled="true" .../>

Silverlight 1.0 RTM

XAML
<PathFigure .../>

AddEventListener now Returns a Token to be Passed to removeEventListener to Un-Register Event Handlers

If you intend to remove event handlers during the lifetime of your Silverlight-based application, you must change the syntax by which you add the event handlers, and retain a token that is now necessary for the removeEventListener call. The token differentiates for cases where multiple handlers were attached for the same event. If you do not intend to remove event handlers, you can leave your addEventListener calls alone, although you should note that addEventHandler now also supports adding the handlers by reference rather than by a quoted name string. This change was made in order to make the Silverlight event object model more similar to other scripting object model syntaxes.

For JavaScript, change this Beta code.

JavaScript
myObj.addEventListener(“MouseEnter”, myEnterHandler);
myObj.removeEventListener(“MouseEnter”, myEnterHandler);

To this code.

JavaScript
var enterToken = myObj.addEventListener(“MouseEnter”, myEnterHandler);
myObj.removeEventListener(“MouseEnter”, enterToken);

And for XAML, change this Beta code.

XAML
<... x:Name=”myObj” MouseEnter=”myEnterHandler”/>
JavaScript
sender.FindName(“myObj”).removeEventListener(“MouseEnter”, myEnterHandler);

To this code.

XAML
<... x:Name=”myObj” MouseEnter=”myEnterHandler”/>
JavaScript
sender.FindName(“myObj”).removeEventListener(“MouseEnter”, 0);

Replace <control>.settings.version Property with isVersionSupported Method

Use this method to remove the <control>.settings.version property from the object tag and to use a new isVersionSupported method. This method takes a version string (for example, “1.0” or “1.1”) and returns a Boolean indicating whether the plug-in is compatible with the requested version.

Change enableHtmlAccess: true to enableHtmlAccess: "true"

Following is an example of how to add quotation marks to the value of enableHtmlAccess. Change this example.

JavaScript
enableHtmlAccess: true

To this.

JavaScript
enableHtmlAccess: "true"

The width and height properties in createObject must be string values

The width and height properties in the createObject function call must be string values, not integer values.

Tighter restrictions of which objects can have child objects

Silverlight 1.0 RTM tightens restrictions on which objects can have child objects. For example, Rectangle and TextBlock used could have child objects in Silverlight Beta, but this is no longer allowed.

Downloader is only able to make a download from the same port as the HTML

The Downloader object is only able to make a download from the same port as the HTML file that hosts the Silverlight plug-in.


Silverlight Conceptual

Silverlight SDK

Silverlight Overviews

Silverlight provides developers with a unified programming model for building rich Web user experiences that incorporate UI and media.

General Topics

Topic | Description
Introduction to Silverlight 1.0 | Introduces Silverlight 1.0 and provides links to resources.
Silverlight 1.0 Architecture Overview | Provides a high-level overview of the Silverlight architecture with a focus on how to best build Silverlight 1.0 applications.
What Changed Between Beta and Release of Silverlight 1.0 | Lists changes between Beta (MIX build) and the Release of Silverlight 1.0.

Fundamentals

Topic | Description
Silverlight Object Models | Describes how Silverlight scripting applications expose their functionality through a browser-based Document Object Model (DOM) and a Silverlight-specific object model.
Silverlight Object Positioning | Shows you how to control the position of objects (for example, shapes, text, and media) within your Silverlight-based application.
Using a Silverlight Plug-In | Explains how to create and reference the Silverlight plug-in, which enables hosting in the browser.
Using CreateSilverlight.js and Silverlight.js | Describes the JavaScript helper files that enable you to initialize and create Silverlight plug-in instances on a Web page.
Localized Deployment | Introduces how to deploy localized Silverlight runtimes (e.g. German, French, etc).
Silverlight Events | Explains how to work with events, which notify the application of changes in Silverlight state and user input.
Silverlight Mouse Support | Explains how to respond to mouse actions, such as moving or clicking the mouse.
Silverlight Keyboard Support | Explains how to respond to keystroke actions.
Using the CreateFromXaml Method | Describes how to create XAML objects dynamically, and then add them to the existing Silverlight object hierarchy. You can create a single Silverlight object, such as a TextBlock, or an entire tree of Silverlight objects.
Referencing and Modifying Objects | Explains how to access and modify objects in your Silverlight-based application at run time.
Text and Fonts Overview | Describes how you can create and format text, apply transforms, and download fonts for your Silverlight-based application.
Resizing a Silverlight Plug-In | Explains how to set and retrieve the size of a Silverlight plug-in, and determine when the plug-in was resized.
Silverlight Full-screen Support | Explains how you can display the Silverlight plug-in in full-screen or embedded mode.
Using a Downloader Object | Explains how to use the Downloader object, which downloads application data, such as XAML content, JavaScript content, and images.
Timer Overview | Describes how to create a timer in Silverlight.
Error Handling in Silverlight-based Scripting Applications | Describes the different ways in which you can provide error-handling support in your Silverlight-based application.
XAML Syntax | Describes the different ways to declare objects and set properties in XAML.
Ink Support in Microsoft Silverlight | Describes how to use the inking API to add ink support to Silverlight applications.
Performance Tips | Lists some tips for ensuring that your Silverlight applications run fast and smooth.
Accessibility Overview | Provides an overview of techniques to make your Silverlight applications more accessible.
Using Inline XAML as the XAML Source | Discusses how to specify the content for a Silverlight plug-in as inline XAML rather than as a URI to a self-contained XAML file.
XAML Namescopes | Discusses the concept of a namescope in XAML, and how namescope concepts are relevant to your usages of the APIs FindName, CreateFromXaml and Name.
Silverlight Scripting Application Notes | Describes issues regarding the use of JavaScript with Silverlight scripting applications.

Media, Animation, and Graphics

Topic | Description
Media Overview | Introduces the multimedia features of Silverlight and describe how to integrate sound and video into your Silverlight pages.
Animation Overview | Provides an overview of the Silverlight animation types and usage, including how to create Storyboard and Trigger objects.
Silverlight Key-Frame Animations Overview | Introduces you to key-frame animations.
Brushes Overview | Describes how to use Silverlight brush objects to paint with solid colors, linear gradients, radial gradients, and images.
Shapes Overview | Provides an overview of how to draw with Shape objects. A Shape is a type of UIElement that enables you to draw a shape to the screen.
Geometries Overview | Describes how to use the Silverlight Geometry objects to describe shapes. This topic also contrasts the differences between Geometry objects and Shape elements.
Transforms Overview | Describes how to use the 2-D transform classes to rotate, scale, move (translate), and skew objects.
VideoBrush Overview | Describes how to use a VideoBrush to paint an area with a video.
Interactive Animations Overview | Describes how to interactively control Storyboard animations.
Supported Media Formats and Protocols | Describes the formats and protocols supported by the MediaElement object.

See Also

Silverlight Reference


Silverlight Fundamentals

The overviews in this section describe the overall programming model for Microsoft Silverlight, including concepts such as properties, events, input, and working with an element tree.

  • Silverlight Object Models: Describes how Silverlight scripting applications expose their functionality through a browser-based Document Object Model (DOM) and a Silverlight-specific object model.

  • Silverlight Object Positioning: Shows you how to control the position of objects (for example, shapes, text, and media) within your Silverlight-based application.

  • Using a Silverlight Plug-in: Explains how to create and reference the Silverlight plug-in, which enables hosting in the browser.

  • Using CreateSilverlight.js and Silverlight.js: Describes the JavaScript helper files that enable you to initialize and create Silverlight plug-in instances on a Web page.

  • Localized Deployment: Introduces how to deploy localized Silverlight runtimes (e.g. German, French, etc).

  • Silverlight Events: Explains how to work with events, which notify the application of changes in Silverlight state and user input.

  • Silverlight Mouse Support: Explains how to respond to mouse actions, such as moving or clicking the mouse.

  • Silverlight Keyboard Support: Explains how to respond to keystroke actions.

  • Using the CreateFromXaml Method: Describes how to create XAML objects dynamically, and then add them to the existing Silverlight object hierarchy. You can create a single Silverlight object, such as a TextBlock, or an entire tree of Silverlight objects.

  • Referencing and Modifying Objects: Explains how to access and modify objects in your Silverlight-based application at run time.

  • Text and Fonts Overview: Describes how you can create and format text, apply transforms, and download fonts for your Silverlight-based application.

  • Resizing a Silverlight Plug-in: Explains how to set and retrieve the size of a Silverlight plug-in, and determine when the plug-in was resized.

  • Full-Screen Support: Explains how you can display the Silverlight plug-in in full-screen or embedded mode.

  • Using a Downloader Object: Explains how to use the Downloader object, which downloads application data, such as XAML content, JavaScript content, and images.

  • Timer Overview: Describes how to create a timer in Silverlight.

  • Error Handling in Silverlight-based Scripting Applications: Describes the different ways in which you can provide error-handling support in your Silverlight-based application.

  • XAML Syntax: Describes the different ways to declare objects and set properties in XAML.

  • Ink Support: Describes various uses for ink in your Silverlight-based application.

  • Performance Tips: Lists some tips for ensuring that your Silverlight-based application runs fast and smoothly.

  • Accessibility Overview: Provides an overview of techniques to make your Silverlight applications more accessible.

  • Using Inline XAML as the XAML Source: Discusses how to specify the content for a Silverlight plug-in as inline XAML rather than as a URI to a self-contained XAML file.

  • XAML Namescopes: Discusses the concept of a namescope in XAML, and how namescope concepts are relevant to your usages of the APIs FindName, CreateFromXaml and Name.

  • Scripting Application Notes Describes issues regarding the use of JavaScript with Silverlight scripting applications.

See Also

Introduction to Silverlight 1.0
Silverlight Architecture
What Changed Between Beta and Release of Silverlight 1.0
Silverlight 1.0 QuickStarts


Silverlight Object Models

Silverlight-based scripting applications expose their functionality through a browser-based Document Object Model (DOM), as well as a Silverlight-specific object model. These object models enable you to create and manipulate Silverlight content.

This topic contains the following sections:

  • Document Object Model
  • Silverlight Object Model
  • Mixing Object Models

Document Object Model

The Document Object Model (DOM) is a platform- and language-neutral programming interface for HTML and XML documents. It provides a structured representation of a document, such as a Web page, as well as a defined way to access and manipulate the document's structure, style, and content. The DOM represents the document as a structured group of nodes and objects that have properties, methods, and events. This representation enables you to manipulate the nodes and objects by using procedural languages such as JavaScript.

The document object represents the entire HTML page and can be used to access all elements in a page. The body object represents the body of the document, which is represented as the <BODY> tag in the HTML page. The following HTML example shows how to set the content of the <BODY> tag to an HTML-formatted literal string by setting the innerHTML property.

HTML
<html>
  <body/>
<html/>

<script language="JavaScript">
  document.body.innerHTML = '<b>Hello, world</b>';
</script>

The World Wide Web Consortium (W3C) DOM standard forms the basis of the DOM implemented in the most widely used browsers. However, most browsers offer extensions beyond the W3C standard. Therefore, developers need to be aware of these differences in order to create platform-neutral content. Silverlight can be accessed by the browser DOMs listed in the following table.

DOM | Description
Gecko DOM (Mozilla, Firefox, Netscape version 6 and later, and other Mozilla-based browsers) | Gecko is the software component that handles the parsing of HTML, the layout of pages, the document object model, and the rendering of the entire application. For more information, see Gecko DOM Reference.
DHTML DOM (Internet Explorer version 4 and later) | The Dynamic HTML (DHTML) DOM gives authors direct, programmable access to the individual components of their Web documents, from individual elements to containers. For more information, see About the DHTML Object Model.

Silverlight Object Model

The Silverlight object model defines a set of objects that enable you to create a Silverlight-based application. The Silverlight object model is exposed through the Silverlight plug-in, which you create as the host container on a Web page. For more information on hosting a Silverlight plug-in on a Web page, see Using a Silverlight Plug-in.

The following illustration shows how the Web page, the Silverlight plug-in, and the Silverlight content interrelate.

Relationship between a Web page and Silverlight content
Silverlight Web page content

This diagram shows how there are two object models available within the web application - one for the HTML DOM and one for Silverlight. The Silverlight plug-in, represented in the HTML source as either an Object or Embed HTML tag, is conceptually the wall between the two object models; however, this wall can be crossed using JavaScript as you will see later.

After you create the Silverlight plug-in, you can retrieve a reference to the plug-in by using its ID in the DOM for the Web page. The following JavaScript example shows how to retrieve the ID of the Silverlight plug-in by using the document.getElementById method.

JavaScript
var plugin_1 = document.getElementById("SLPlugin_1");

Note To retrieve the plug-in's DOM properties, such as width and height, you must use the GetElementById method to return a reference to a DOM-accessible object. The GetHost method does not return an object from which DOM values can be retrieved.

For more information on referencing a Silverlight plug-in and its content, see Using a Silverlight Plug-in.

Silverlight Hierarchy of XAML Objects

When you add XAML objects to the Silverlight plug-in, you are defining a hierarchical tree structure with a root object. For example, the following XAML code creates a object hierarchy that contains a parent Canvas object and child TextBlock and Canvas objects. In this case, the first Canvas object defined is the root object for the tree structure.

XAML
<!-- The top-most object in the XAML hierarchy is referred to as the root object. -->
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  Loaded="onLoaded">

  <!-- Canvas objects can be a child of another Canvas object. -->
  <Canvas
    Canvas.Left="20" Canvas.Top="20">
    <Rectangle
      Width="200" Height="35"
      Fill="PowderBlue" />
    <TextBlock
      Canvas.Left="25" Canvas.Top="5"
      Foreground="Teal" FontFamily="Verdana" FontSize="18" FontWeight="Bold"
      Text="Sample Output" />
  </Canvas>

  <TextBlock
    Canvas.Left="36" Canvas.Top="80"
    Foreground="Maroon" FontFamily="Verdana" FontSize="24" FontWeight="Bold"
    Text="Hello, world" />
</Canvas>

XAML content is converted into a a hierarchical tree structure with a root object. The following illustration shows the tree structure for the previous XAML content.

XAML content as a tree structure

XAML Tree Structure

The tree structure determines the rendering order of Silverlight objects. The order of traversal starts with the root object, which is the topmost node in the tree structure. The root object's children are then traversed, left to right. If an object has children, its children are traversed before the object's siblings. This means that the content of a child object is rendered in front of the object's own content. The following illustration shows the rendered output and the rendering order sequence from the previous XAML example.

Rendering order of XAML content
XAML output

Adding XAML Objects to the Silverlight Object Hierarchy

When you create content for a Silverlight plug-in, you set the Source property of the plug-in to reference XAML content. The XAML content is parsed and converted into a Silverlight object hierarchy, which is then rendered. Setting the Source property is typically done indirectly through the use of JavaScript helper files, which provide initialization support for creating the Silverlight plug-in. For more information about using these helper files, see Using CreateSilverlight.js and Silverlight.js.

You can also add XAML content to existing objects in the XAML object hierarchy. For example, the following JavaScript example appends a TextBlock object to an existing Canvas object.

JavaScript
// MouseLeftButtonUp event handler for the Canvas object.
function onMouseLeftButtonUp(sender, mouseEventArgs)
{
    // Retrieve a reference to the plug-in.
    var plugin = sender.getHost();

    // Create a TextBlock using a literal XAML string.
    var textblock = plugin.content.createFromXaml('<TextBlock Canvas.Top="50">Hello, again</TextBlock>');

    // Append the TextBlock to the sender, or Canvas, object.
    sender.children.add(textblock);
}

For more information about adding XAML content to existing objects, see Using the CreateFromXaml Method.

Other Silverlight Objects

The Downloader object is a special-purpose Silverlight object that provides the ability to download content, including XAML content, JavaScript content, and media assets such as illustrations. With this object, you do not have to provide all application content when the Silverlight plug-in is instantiated. Instead, you can download content on demand in response to application needs. The Downloader object provides functionality for initiating the data transfer, monitoring the progress of the data transfer, and retrieving the downloaded content. For more information about using the Downloader object, see Using a Downloader Object.

Mixing Object Models

You can use JavaScript to bridge the DOM and the Silverlight Object Model. For example, let's say you have a TEXTAREA element in your HTML page (in the DOM) and you would like to access the user input of that element for use in your Silverlight-based application. The TEXTAREA element looks like this.

HTML
...
<TextArea ID="myHTMLTextArea">Type something and Click the box below</TextArea>
...

In your XAML, you have a simple Canvas with a MouseLeftButtonDown event attached to it.

XAML
// MouseLeftButtonUp event handler for the Canvas object.
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007">

  <Canvas
    Width="200" Height="35"
    Canvas.Left="20" Canvas.Top="20"
    Background="PowderBlue"
    MouseLeftButtonDown="onMouseLeftButtonDown">
    <TextBlock
      Canvas.Left="25" Canvas.Top="5"
      Foreground="Teal" FontFamily="Verdana" FontSize="18" FontWeight="Bold"
      Text="Click" />
  </Canvas>

</Canvas>

The following JavaScript retrieves the text from the TEXTAREA and then outputs that content into the XAML.

XAML
// MouseLeftButtonUp event handler for the Canvas object.
function onMouseLeftButtonDown(sender, mouseEventArgs)
{

    // Retrieve the text from the TEXTAREA element in the HTML.
    var txtInput = document.getElementById("myHTMLTextArea").value;

    // Retrieve a reference to the plugin.
    var plugin = sender.getHost();

    // Create a TextBlock using a literal XAML string. Use the text from
    // the HTML object for the content of the TextBlock.
    var textblock = plugin.content.createFromXaml('<TextBlock Canvas.Top="50">' + txtInput + '</TextBlock>');

    // Append the TextBlock to the sender, or Canvas, object.
    sender.children.add(textblock);

}

Conceptually, this looks like the diagram below. Although the two object models cannot access each other directly, JavaScript acts as a bridge because the JavaScript code is accessible both to and from the object models.

JavaScript is Accessible to Both Object Models
JavaScript Object Model Map

See Also

Object Positioning
Using a Silverlight Plug-in
Using CreateSilverlight.js and Silverlight.js
Silverlight Events
XAML Syntax
Overviews
Silverlight Fundamentals


Object Positioning in Silverlight

This overview demonstrates how to control the position of objects (such as shapes, text, and media) in your Microsoft Silverlight-based application.

The overview contains the following sections:

  • The Canvas Object
  • Positioning Paths, Geometries, and Other Shapes
  • Transforms
  • Z-Order

The Canvas Object

All Silverlight objects must be contained in a Canvas object and positioned relative to their containing Canvas. You control the positioning of objects inside the Canvas by specifying x and y coordinates. These coordinates are in pixels, which are resolution-independent. The x and y coordinates are often specified by using the Canvas.Left and Canvas.Top attached properties. Canvas.Left specifies the object's distance from the left side of the containing Canvas (x coordinate) and Canvas.Top specifies the object's distance from the top of the containing Canvas (y coordinate).

The example below shows how to position a rectangle 30 pixels from the left and 30 pixels from the top of a Canvas.

XAML
<Canvas
    xmlns="http://schemas.microsoft.com/client/2007"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Width="640" Height="480"
    Background="White"
    >
    <Rectangle Canvas.Left="30" Canvas.Top="30" Fill="red"
    Width="200" Height="200" />
</Canvas>

The following illustration shows how this code renders inside the Canvas.

Positioning a rectangle inside the Canvas
Positioning a rectangle inside the Canvas

Note Silverlight does not support high dpi in version 1. Therefore, objects rendered on the screen and the coordinate system do not scale in response to monitor resolution. In addition, coordinates that are used by mouse events are not affected by monitor resolution.

You can nest Canvas objects and position them by using the Canvas.Left and Canvas.Top properties. When you nest objects, the coordinates used by each object are relative to its immediate containing Canvas. In the example below, the root (white) Canvas contains a nested (blue) Canvas that has Canvas.Left and Canvas.Top properties of 30. The nested blue Canvas contains a red rectangle that also has Canvas.Left and Canvas.Top values of 30.

XAML
<Canvas
    xmlns="http://schemas.microsoft.com/client/2007"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Width="300" Height="300"
    Background="White">

    <Canvas Width="250" Height="250" Canvas.Left="30" Canvas.Top="30"
    Background="blue">

      <Rectangle Canvas.Left="30" Canvas.Top="30" Fill="red"
      Width="200" Height="200" />

    </Canvas>

</Canvas>

The following illustration shows how this code renders.

Nested objects
Nested objects

Note In Silverlight-based applications that are embedded in HTML pages, the HTML element that hosts the Silverlight plug-in often has a specific width and height. Because of this, it is possible for objects to be positioned out of view. For example, if your host HTML element is only 300 pixels wide and you position an object 400 pixels to the right in your Silverlight-based application, your users will not be able to see the object.

Positioning Paths, Geometries, and Other Shapes

Not all objects are positioned by using the Canvas.Left and Canvas.Top properties. However, they all use x and y coordinates that are relative to the containing Canvas. Examples of these objects include the Path object, various geometry objects, and shapes such as Line. The following example shows the positioning syntax for some of these objects. For more information about paths, geometries, and other shapes, see Shapes and Drawing in Silverlight Overview, Geometries Overview, and Path Markup Syntax.

XAML
<Canvas
    xmlns="http://schemas.microsoft.com/client/2007"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Width="300" Height="300"
    Background="White">

  <!-- Simple line gives X and Y coordinates for the start
       and end of the line. -->
  <Line X1="280" Y1="10" X2="10" Y2="280"
      Stroke="Blue" StrokeThickness="5"/>

  <!-- A Polyline allows you to specify a number of X,Y coordinates
       to make a series of connected lines -->
  <Polyline Points="150, 150 150, 250 250, 250 250, 150"
      Stroke="Yellow" StrokeThickness="10"/>

  <!-- Path allows you to create more complex shapes including curves.
       Again, the shape of the Path is specified by coordinates. -->
  <Path Data="M 10,100 C 10,300 300,-200 250,100z"
      Stroke="Red" Fill="Orange"
      Canvas.Left="10" Canvas.Top="10" />

</Canvas>

The following illustration shows how this code renders.

Positioning Line, Polyline, and Path objects
Positioning Line, Polyline, and Path objects

Transforms

Another way to change the position of an object is to apply a transform to it. You can use transforms to move the object, rotate the object, skew the object's shape, change the size (scale) of the object, or a combination of these actions.

The following example shows a RotateTransform that rotates a Rectangle element 45 degrees about the point (0,0).

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Width="200" Height="200">
  <Rectangle
    Canvas.Left="100" Canvas.Top="100"
    Width="50" Height="50"
    Fill="RoyalBlue">
    <Rectangle.RenderTransform>
      <RotateTransform Angle="45" />
    </Rectangle.RenderTransform>
  </Rectangle>
</Canvas>

The following illustration shows how this code is rendered.

A Rectangle rotated 45 degrees about the point (0,0)
A Rectangle rotated 45 degrees about (0,0)

For more information about transforms and how to use them, see Transforms Overview.

Z-Order

So far, the discussion has focused on positioning objects in two-dimensional space. You can also position objects on top of one another. The z-order of an object determines whether an object is in front of or behind another overlapping object. By default, the z-order of objects within a Canvas is determined by the sequence in which they are declared. Objects that are declared later appear in front of objects that are declared first. The following example creates three Ellipse objects. You can see that the Ellipse declared last (the lime-colored ellipse) is in the foreground, in front of the other two Ellipse objects.

XAML
<Canvas
    xmlns="http://schemas.microsoft.com/client/2007"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <Ellipse
      Canvas.Left="5" Canvas.Top="5"
      Height="200" Width="200"
      Stroke="Black" StrokeThickness="10" Fill="Silver" />

  <Ellipse
      Canvas.Left="50" Canvas.Top="50"
      Height="200" Width="200"
      Stroke="Black" StrokeThickness="10" Fill="DeepSkyBlue" />

  <Ellipse
      Canvas.Left="95" Canvas.Top="95"
      Height="200" Width="200"
      Stroke="Black" StrokeThickness="10" Fill="Lime" />

</Canvas>

The following illustration shows how this code renders.

Overlapping Ellipse objects
Overlapping Ellipse objects

You can change this behavior by setting the Canvas.ZIndex attached property on objects within the Canvas. Higher values are closer to the foreground; lower values are farther from the foreground. The following example is similar to the preceding one, except that the z-order of the Ellipse objects is reversed. The Ellipse that is declared first (the silver ellipse) is now in front.

XAML
<Canvas
    xmlns="http://schemas.microsoft.com/client/2007"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <Ellipse
      Canvas.ZIndex="3"
      Canvas.Left="5" Canvas.Top="5"
      Height="200" Width="200"
      Stroke="Black" StrokeThickness="10" Fill="Silver" />

  <Ellipse
      Canvas.ZIndex="2"
      Canvas.Left="50" Canvas.Top="50"
      Height="200" Width="200"
      Stroke="Black" StrokeThickness="10" Fill="DeepSkyBlue" />

  <Ellipse
      Canvas.ZIndex="1"
      Canvas.Left="95" Canvas.Top="95"
      Height="200" Width="200"
      Stroke="Black" StrokeThickness="10" Fill="Lime" />

</Canvas>

The following illustration shows how this code renders.

Reversing the z-order of the Ellipse objects
Reversing z-order of the Ellipse objects

See Also

Shapes and Drawing Overview
Geometries Overview
Path Markup Syntax
Transforms Overview
Silverlight Object Models
Overviews


Using Silverlight Plug-ins

Silverlight SDK

Using a Silverlight Plug-in

When you install the Microsoft Silverlight run-time components, you install a browser plug-in. The Silverlight plug-in is packaged differently on different platforms. On the Windows operating system, Internet Explorer uses ActiveX technology to host Silverlight plug-ins, whereas all other browser and platform combinations use the Netscape plug-in technology.

This topic contains the following sections:

  • The Silverlight Plug-in in Context
  • Using JavaScript Helper Files to Create a Silverlight Plug-in
  • Referencing the Plug-in Instance at Run Time
  • Referencing the Plug-in's Properties, Methods, and Events at Run Time

The Silverlight Plug-in in Context

There are a number of components that make up a typical Web page with embedded Silverlight content. The diagram below summarizes these components:

Relationship between a Web page and Silverlight content
Silverlight-Web Page Relationship

Each of these components is summarized below:

  • Web Page: The Web page in which the Silverlight-based application is embedded (or hosted).
  • HTML Placeholder Element: The block-level HTML element (usually a <DIV> tag) that is used to contain the Silverlight plug-in and that therefore determines where in the Web page the Silverlight-based application is rendered.
  • Silverlight Plug-in: The Silverlight plug-in that renders the Silverlight content. This plug-in is defined in an HTML page by creating an <OBJECT> or <EMBED> tag and setting its parameter values. Functions in the Silverlight.js helper file produce this <OBJECT> or <EMBED> tag output. See Using JavaScript Helper Files to Create a Silverlight Plug-in below. As will be discussed in this overview, you can access this plug-in and reference its properties, methods, and events at run time.
  • Silverlight Content: The XAML content that makes up the presentation of your Silverlight-based application.

Note: If you would like to walkthrough using these components to create a Silverlight-based application, see parts 1 and 2 of the Silverlight 1.0 QuickStart.

Using JavaScript Helper Files to Create a Silverlight Plug-in

The Silverlight samples available on the Microsoft Silverlight Web site and in the SDK use a pair of JavaScript helper files, CreateSilverlight.js and Silverlight.js, to initialize and create Silverlight plug-ins on a Web page. A Silverlight plug-in is defined in an HTML page by creating an <OBJECT> or <EMBED> tag and setting its parameter values. Functions in Silverlight.js produce this <OBJECT> or <EMBED> tag output. They also provide installation or upgrade dialog boxes that will display in case the requested version of the Silverlight runtime is not available on the user's computer.

Using the Silverlight.js file is the required technique for using Silverlight plug-ins in an application. The CreateSilverlight.js file is a convenience file that lets you package and provide specific parameters to the methods that are defined in Silverlight.js.

For more information about using Silverlight.js and CreateSilverlight.js to instantiate a Silverlight plug-in or to check for version information, see Using CreateSilverlight.js and Silverlight.js.

Referencing the Plug-in Instance at Run Time

The GetHost method can be used by any UIElement-derived object to retrieve the Silverlight plug-in that contains the object. This method is especially useful for retrieving the Silverlight plug-in in an event-handling function in which the sender parameter identifies a UIElement-derived object.

The following JavaScript example shows how to retrieve a Silverlight plug-in in a KeyUp event-handler function.

JavaScript
function onKeyUp(sender, keyEventArgs)
{
    // Determine whether the keystroke combination CTRL+V was detected.
    if ((keyEventArgs.key == 51) && (keyEventArgs.ctrl == true))
    {
        // Retrieve a reference to the plug-in.
        var plugin = sender.getHost();

        // Determine whether the 1.0 version of Silverlight is available.
        alert("Silverlight 1.0: " + plugin.isVersionSupported("1.0"));
    }
}

If you need access to the plug-in's Document Object Model (DOM) values, such as width and height, you can retrieve a reference to the Silverlight plug-in by using its ID in the DOM for the Web page. The following JavaScript example shows how to retrieve a reference to the Silverlight plug-in by using the document.getElementById method.

JavaScript
var plugin_1 = document.getElementById("SLPlugin_1");

For more information on the DOM and the Silverlight Object Model, see Object Models.

Referencing the Plug-in's Properties, Methods, and Events at Run Time

You can access the members of a Silverlight plug-in at run time in three ways:

  • By referencing the Silverlight plug-in object.
  • By referencing the Silverlight plug-in's settings property, which is a sub-object that groups certain properties and methods.
  • By referencing the Silverlight plug-in's content property, which is a sub-object that groups certain properties and methods.

The following diagram illustrates how a Silverlight plug-in's properties, methods, and events are grouped at run time.

Silverlight plug-in settings and content groups

Accessing Plug-in Members Directly

The following table lists the properties, methods, and events that you can directly access from the Silverlight plug-in at run time.

Member | Syntax | Description
CreateObject | plugin.createObject(objectType) | Creates a specified object and returns a reference to it.
InitParams | plugin.initParams | Gets the optional set of user-defined initialization parameters.
IsLoaded | plugin.isLoaded | Gets a value that indicates whether the Silverlight plug-in is loaded.
IsVersionSupported | plugin.isVersionSupported(versionString) | Determines whether the installed Silverlight plug-in will support initialization if presented with a specified version string.
OnError | plugin.onError = eventhandlerFunction | Assigns a handler function that handles errors when the Silverlight plug-in generates a run-time error.
Source | plugin.source | Gets or sets the XAML content to render.

Accessing Plug-in Members by Using the Settings Property

The following table lists the properties that are accessible as settings members of the Silverlight plug-in at run time.

Member | Syntax | Description
Background | plugin.settings.background | Gets or sets the background color of the rectangular region that displays XAML content.
EnableFramerateCounter | plugin.settings.enableFramerateCounter | Gets or sets a value that determines whether to display the current framerate in the hosting browser's status bar.
EnableRedrawRegions | plugin.settings.enableRedrawRegions | Gets or sets whether to show the areas of the plug-in that are being redrawn with each frame.
EnableHtmlAccess | plugin.settings.enableHtmlAccess | Determines whether the hosted content in the Silverlight plug-in has access to the browser DOM.
MaxFrameRate | plugin.settings.maxFrameRate | Gets or sets the maximum number of frames to render per second.
Windowless | plugin.settings.windowless | Determines whether the Silverlight plug-in displays in windowless mode.

Accessing Plug-in Members by Using the Content Property

The following table lists the properties, methods, and events that are accessible as content members of the Silverlight plug-in at run time.

Member | Syntax | Description
Accessibility | plugin.content.accessibility | Gets an object that contains properties that report accessibility information to the Silverlight plug-in host.
ActualHeight | plugin.content.actualHeight | Gets the height of the rendering area of the plug-in.
ActualWidth | plugin.content.actualWidth | Gets the width of the rendering area of the plug-in.
CreateFromXaml | plugin.content.createFromXaml(xamlContent) | Creates XAML content dynamically.
CreateFromXamlDownloader | plugin.content.createFromXamlDownloader(xamlContent, part) | Creates XAML content dynamically by using downloader content.
FindName | plugin.content.findName(objectName) | Returns a reference to an object in the Silverlight content object hierarchy by referencing the object's Name or x:Name attribute value.
FullScreen | plugin.content.fullScreen | Gets or sets a value that indicates whether the plug-in displays in full-screen mode.
OnFullScreenChange | plugin.content.onFullScreenChange = eventhandlerFunction | Occurs whenever the FullScreen property of the plug-in changes.
OnResize | plugin.content.onResize = eventhandlerFunction | Occurs whenever the ActualHeight or ActualWidth property of the plug-in changes.
Root | value=plugin.content.root | Gets the root object of XAML content.

See Also

Silverlight Object Models
Silverlight Events
Referencing and Modifying Silverlight Objects
Overviews


Using CreateSilverlight.js and Silverlight.js

The Microsoft Silverlight samples available on the Silverlight Web site and in the Silverlight SDK use a pair of JavaScript helper files, CreateSilverlight.js and Silverlight.js, to initialize and create Silverlight plug-ins on a Web page. The Silverlight.js file is the required technique for using Silverlight plug-ins in an application. The CreateSilverlight.js file is a convenience file that lets you package and provide specific parameters to the methods that are in Silverlight.js.

This topic contains the following sections:

  • Role of the Helper Files
  • Calling the CreateSilverlight Method
  • Modifying the CreateSilverlight Method
  • Using the IsInstalled Method
  • Silverlight Versioning
  • Creating and Referencing Inline XAML
  • User-defined Initialization Parameters
  • Using the InplaceInstallPrompt Parameter
  • Using the OnLoad Event

Role of the Helper Files

CreateSilverlight.js and Silverlight.js are helper files that you use to create a Silverlight-based application. The following table lists the main roles of the files involved in initializing and creating a Silverlight plug-in.

File | Description
Default.htm, default.aspx, or other HTML file | Hosts the Silverlight plug-in by invoking the CreateSilverlight method that is defined in the CreateSilverlight.js file.
CreateSilverlight.js | Defines the CreateSilverlight method that invokes either the CreateObject or CreateObjectEx method, both of which are defined in the Silverlight.js file.
Silverlight.js | Defines the CreateObject and CreateObjectEx methods, which provide version checking support and generate the <OBJECT> or <EMBED> markup for plug-in instantiation in the HTML file that hosts the Silverlight plug-in.

The following illustration shows the relationships between these three files.

Relationship between Default.htm, CreateSilverlight.js, and Silverlight.js

Calling the CreateSilverlight Method

To use a Silverlight plug-in on a Web page, you modify the page to include the following:

  1. Two <SCRIPT> tags that reference the location of CreateSilverlight.js and Silverlight.js.
  2. An HTML block element such as a <DIV> tag that hosts the Silverlight plug-in. When the CreateObject and CreateObjectEx methods execute, this block element becomes the location in which the methods will write their HTML output. This block element must have a unique ID attribute value.
  3. A <SCRIPT> tag embedded within that block element that contains two lines of JavaScript. The first line creates a variable that references the HTML block element through the HTML Document Object Model (DOM) scripting call getElementByID. The second line invokes the CreateSilverlight method.

The following HTML example shows these three modifications to the Web page that hosts the Silverlight plug-in.

HTML
...
<head>
  <title>My Silverlight Application</title>

  <!-- Helper files for initializing and creating the Silverlight plug-in -->
  <script type="text/javascript" src="js/Silverlight.js"></script>
  <script type="text/javascript" src="js/CreateSilverlight.js"></script>

  <!-- Application event-handler functions -->
  <script type="text/javascript" src="js/eventhandlers.js"></script>
</head>
...
<body>
  <div id="slPluginHost" >
    <script type="text/javascript">
      // Create a variable that references the HTML element that hosts the plug-in.
      var parentElement = document.getElementById("slPluginHost");

      // Initialize and create the plug-in.
      createSilverlight();
    </script>
  </div>
</body>
...

Modifying the CreateSilverlight Method

The CreateSilverlight.js file typically contains a single method, CreateSilverlight. The source code that defines this method contains two method invocations that are commented out: Silverlight.createObject and Silverlight.createObjectEx. You can use either of these methods to initialize and create the Silverlight plug-in. The only difference between the two methods is that Silverlight.createObjectEx uses a single JavaScript Object Notation (JSON) dictionary to package all of its parameters. The following JavaScript example shows a modified call to Silverlight.createObject.

JavaScript
function createSilverlight()
{
    Silverlight.createObject(
        "plugin.xaml",                      // Source property value.
        parentElement,                      // DOM reference to hosting DIV tag.
        "myPlugin",                         // Unique plug-in ID value.
        {                                   // Plug-in properties.
            width:'1024',                   // Width of rectangular region of plug-in in pixels.
            height:'530',                   // Height of rectangular region of plug-in in pixels.
            inplaceInstallPrompt:false,     // Determines whether to display in-place install prompt if invalid version is detected.
            background:'white',             // Background color of plug-in.
            isWindowless:'false',           // Determines whether to display plug-in in windowless mode.
            framerate:'24',                 // MaxFrameRate property value.
            version:'1.0'                   // Silverlight version.
        },
        {
            onError:null,                   // OnError property value -- event-handler function name.
            onLoad:null                     // OnLoad property value -- event-handler function name.
        },
        null,                               // initParams -- user-settable string for information passing.
        null);                              // Context value -- passed to Silverlight.js onLoad event handlers.
}

The following JavaScript example shows a call to Silverlight.createObjectEx, with parameter values corresponding to the previous example.

JavaScript
function createSilverlightEx()
{
    Silverlight.createObjectEx({
        source: 'plugin.xaml',          // Source property value.
        parentElement:parentElement,    // DOM reference to hosting DIV tag.
        id:'myPlugin',                  // Unique plug-in ID value.
        properties:{                    // Plug-in properties.
            width:'1024',               // Width of rectangular region of plug-in in pixels.
            height:'530',               // Height of rectangular region of plug-in in pixels.
            inplaceInstallPrompt:false, // Determines whether to display in-place install prompt if invalid version is detected.
            background:'white',         // Background color of plug-in.
            isWindowless:'false',       // Determines whether to display plug-in in windowless mode.
            framerate:'24',             // MaxFrameRate property value.
            version:'1.0'},             // Silverlight version.
        events:{
            onError:null,               // OnError property value -- event-handler function name.
            onLoad:null},               // OnLoad property value -- event-handler function name.
        initParams:null,                // initParams property value -- user-settable string for information passing.
        context:null});                 // Context value -- passed to Silverlight.js onLoad event handlers.
}

Parameter Values

The following parameters are passed to the Silverlight.createObject and Silverlight.createObjectEx methods. Some of these parameters correspond to the resulting output in the form of OBJECT or EMBED tags. Also, some parameters correspond to a property in the Silverlight object model, so you can retrieve the values of the initialization parameters in run-time code.

  • source -- Refers to the XAML content file, and corresponds to the Source property of the Silverlight plug-in.
  • parentElement -- Refers to the block element in the HTML file that contains the createSilverlight scripting call and becomes the host element for the Silverlight plug-in after it is instantiated.
  • id -- Refers to the unique identifier of the instantiated Silverlight plug-in within the HTML DOM.
  • properties -- Refers to the set of Silverlight plug-in initialization properties. (See tables below.)
  • events -- Refers to the set of Silverlight plug-in events that can be set at initialization. (See tables below.)
  • initParams -- Refers to the set of user-defined initialization parameters. For more information, see the User-defined Initialization Parameters section.
  • context -- Refers to the unique identifier that can be passed as a parameter to an OnLoad event handler function that can be shared by multiple Silverlight plug-ins on the same Web page. This value uniquely identifies which plug-in was loaded without having to check the HTML DOM. For more information, see Using the OnLoad Event.

The following table lists the parameters that can be defined as Silverlight plug-in initialization properties (within the properties parameter).

Parameter | Description
width | Defines the width of the rectangular region that displays the Silverlight content. Sets the plug-in's width property. This property is exposed via the DOM. The default unit of measurement is pixels. You can also specify the width as a percentage of the displayable area of the tag containing the plug-in (for example, "40%"). The default value is 0. This value can be checked at run time through ActualWidth, which gives the actual pixel width for cases where the original width was specified as a percentage.
height | Defines the height of the rectangular region that displays the Silverlight content. Sets the plug-in's height property. This property is exposed via the DOM. The default unit of measurement is pixels. You can also specify the height as a percentage of the displayable area of the tag containing the plug-in (for example, "50%"). The default value is 0. This value can be checked at run time through ActualHeight, which gives the actual pixel height for cases where the original height was specified as a percentage.
background | Specifies the background color of the rectangular region that displays XAML content. This value can be retrieved and set at runtime through the SilverlightObject.settings.Background property. See the Background property for valid parameter settings for the background parameter. The default value is null, which for this property is equivalent to the color white.
isWindowless | Determines whether the plug-in displays as a windowless plug-in. This value can be retrieved at run time through the SilverlightObject.settings.Windowless property. If the value is set to true and the Background property value specifies an alpha value, the color value is blended with the HTML page. The default value is false. On Macintosh, the plug-in always acts as a windowless plug-in, and the value of this property is ignored in run-time behavior.
frameRate | Specifies the maximum number of frames to render per second. This value can be retrieved and set at run time through the SilverlightObject.settings.MaxFrameRate property. The actual frame rate that Silverlight content renders depends on system load performance. The maximum frame rate is 64. If the property is set to a value that is greater than 64, it is considered to be set to 64. The default value is 24.
inplaceInstallPrompt

Determines whether the in-place installation prompt appears if the specified version of the Silverlight plug-in is not installed. The default value is false, which means that the standard installation prompt appears. There is no corresponding run-time property. For more information, see Using the InplaceInstallPrompt Parameter.

Note Do not place quotation marks around this Boolean value. Other Boolean values in the initialization (such as isWindowless) require quotation marks, but inplaceInstallPrompt will not be processed correctly if you use quotation marks.
version | Specifies the Silverlight version required to run the application. The version initialization parameter is compared with the version of the currently installed Silverlight runtime. The inplaceInstallPrompt parameter determines which installation dialog box appears when the version checking in Silverlight.js returns false. There is no corresponding run-time property.
ignoreBrowserVer

Determines whether to disable checking for supported Silverlight browsers and browser versions. Setting this initialization parameter to true means that any browser can attempt to display the Silverlight-based application. The default value is false, which means that only supported Silverlight browsers can display the application. There is no corresponding run-time property.

Note Do not place quotation marks around this Boolean value. Other Boolean values in the initialization (such as isWindowless) require quotation marks, but ignoreBrowserVer will not be processed correctly if you use quotation marks.
enableHtmlAccess | Not relevant for Silverlight 1.0. In Silverlight 1.0, the Silverlight object model always has access to the browser DOM. This parameter exists for use by Silverlight 1.1 Alpha versions. This value can be retrieved at run time through the SilverlightObject.settings.EnableHtmlAccess property. The default value is true.

The following table lists the parameters that can be defined as Silverlight plug-in initialization events.

Parameter | Description
onError | Specifies a user-defined JavaScript error-handling function that is invoked when an error is generated in the Silverlight runtime components. (See OnError.) The default value is the default error-handling function, "default_error_handler", which is defined in Silverlight.js.
onLoad | Specifies the event-handling function for the plug-in's OnLoad event. The default value is null.

Using the IsInstalled Method

The Silverlight.js file contains a Silverlight runtime version checking method, IsInstalled, that can be used to verify whether a specified Silverlight runtime version is available before attempting to initialize a Silverlight control with calls to CreateObject or CreateObjectEx. IsInstalled returns true if the specified version matches or is compatible with the current version of the Silverlight runtime; otherwise, it returns false. The following HTML example shows how to invoke the IsInstalled method.

HTML
<div id="pluginHost" >
  <script type="text/javascript">

    // Determine whether the specified Silverlight runtime version is installed.
    var version = "2.0"; //deliberate over-version
    var isInstalled = Silverlight.isInstalled(version);

    // Create the plug-in if the specified Silverlight runtime version is installed.
    if (isInstalled)
    {
        var parentElement = document.getElementById("pluginHost");
        createSilverlight();
    }
    else
    {
        alert("Silverlight runtime version " + version + " not installed.");
    }
  </script>
</div>

Silverlight Versioning

The strings used to communicate versions of the Silverlight plug-in use the following format:

versionMajor.versionMinor.buildNumber.revisionNumber

Generally speaking, the versions you pass in the CreateObject or IsInstalled function only need to specify versionMajor.versionMinor. The full build+revision version of Silverlight that is installed may or may not be equal to that specified as a function parameter. If a more specific check succeeds, a less specific check must succeed as well. For example, if IsVersionSupported("1.0.01820.55") returns true, both IsVersionSupported("1.0.01820") and IsVersionSupported("1.0") must return true. Conversely, if a less specific check fails, a more specific check must fail, too. For example, if IsVersionSupported("1.0") returns false, both IsVersionSupported("1.0.01820") and IsVersionSupported("1.0.01820.55") must return false.

Creating and Referencing Inline XAML

Rather than using a discrete file that is referenced by a URI to set the initial Silverlight content, you can specify an area of inline HTML content that contains your XAML. In order to use this technique, you must enclose the XAML in a special SCRIPT block, and use a "#" prefix in the source parameter. For details on this technique, see Using Inline XAML as the XAML Source.

User-defined Initialization Parameters

The initParams initialization parameter lets you specify user-defined parameter values. These parameters values can be retrieved at run time by accessing the plug-in's InitParams property. The following JavaScript example shows how to specify the initParams parameter value in the user-defined CreateSilverlight method in CreateSilverlight.js.

JavaScript
function createSilverlight()
{
    Silverlight.createObject(
        "plugin.xaml",                  // Source property value.
        parentElement,                  // DOM reference to hosting DIV tag.
        "myPlugin",                    // Unique plug-in id value.
        {                               // Plug-in properties.
            width:'600',                // Width of rectangular region of plug-in in pixels.
            height:'200',               // Height of rectangular region of plug-in in pixels.
            version:'1.0'               // Plug-in version to use.
        },
        { },                            // No events defined -- use empty list.
        "param1, param2");              // InitParams property value.
}

To access the initParams initialization parameter values at run time, use the InitParams property of the plug-in. The following JavaScript example shows how to retrieve the parameter values by using the InitParams property.

JavaScript
function onLoaded(sender, eventArgs)
{
    // Retrieve a reference to the plug-in.
    var plugin = sender.getHost();

    // Retrieve the InitParams value and split comma-delimited string.
    var params = plugin.initParams.split(",");

    // Display the parameter values.
    var msg = "Params: ";
    for (var i = 0; i < params.length; i++)
    {
        msg += params[i] + " ";
    }

    alert(msg);
}

Using the InplaceInstallPrompt Parameter

The inplaceInstallPrompt parameter is an initialization parameter that determines whether the in-place installation prompt appears if the specified version of the Silverlight plug-in is not installed. The default value is false, which means that if the version checking in Silverlight.js returns false, the following Silverlight standard installation dialog box will appear.

Silverlight standard installation dialog box

When you click the Silverlight standard installation dialog box, the Silverlight download page appears.

Setting the InplaceInstallPrompt Parameter to True

When inplaceInstallPrompt is set to true, the following in-place installation prompt appears if the specified version of the Silverlight plug-in is not installed.

Silverlight in-place installation dialog box

When you click in the upper portion of the Silverlight in-place installation dialog box, the Silverlight download process begins. The lower portion of the in-place installation dialog box provides links to the Silverlight license agreement(s) and Silverlight privacy information. You must not alter Silverlight.js to change the wording, color, or location of the links, or remove these links in the in-place installation dialog box.

Note All browsers that are supported by Silverlight, except for Internet Explorer on the Windows operating system, require the browser to be restarted before Silverlight will work properly. You should warn users on your Web site (not in the installation dialog box) that restarting their browser might be required.

Using the Onload Event

The onLoad initialization parameter specifies the event-handler function that is called in response to the OnLoad event. The OnLoad event occurs after the XAML content in the Silverlight plug-in has completely loaded.

The OnLoad event occurs after any Loaded event for a UIElement-derived class such as Canvas, TextBlock, or Rectangle. The read-only IsLoaded property, which is set before the Onload event occurs, indicates whether the Silverlight plug-in is loaded.

Note JavaScript provides a set of events that you can use to respond to changes in the Web page, including the page's onload event. You can use the Silverlight plug-in OnLoad event and the page's onload event on the same page. In this case, the OnLoad event occurs before the page's onload event.

Using the Context Parameter with the OnLoad Event

The context parameter refers to the user-defined unique identifier that can be passed as a parameter to an OnLoad event handler that can be shared by multiple Silverlight plug-ins on the same Web page. The OnLoad context parameter corresponds to the value of the context initialization parameter.

The following HTML example shows how to define two Silverlight plug-in host elements on the same Web page.

HTML
<div id="pluginHost" >
  <script type="text/javascript">

    // Create a variable that references the HTML element that hosts the plug-in.
    var parentElement = document.getElementById("pluginHost");

    // Create variables that contain unique identifiers for the plug-in.
    var name = "myslPlugin_1";
    var context = "context_1";

    // Initialize and create the plug-in.
    createSilverlight();
  </script>
</div>

<div id="pluginHost2" >
  <script type="text/javascript">

    // Create a variable that references the HTML element that hosts the plug-in.
    var parentElement = document.getElementById("pluginHost2");

    // Create variables that contain unique identifiers for the instance.
    var name = "myslPlugin_2";
    var context = "context_2";

    // Initialize and create the plug-in.
    createSilverlight();

  </script>
</div>

The following JavaScript example shows the corresponding CreateSilverlight method in the user-defined CreateSilverlight.js file. Notice that the method uses the values of the same parentElement, name, and context variables. Redefining an existing JavaScript variable replaces the old value with a new value of the variable.

HTML
<div id="pluginHost" >
  <script type="text/javascript">

    // Create a variable that references the HTML element that hosts the plug-in.
    var parentElement = document.getElementById("pluginHost");

    // Create variables that contain unique identifiers for the plug-in.
    var name = "myslPlugin_1";
    var context = "context_1";

    // Initialize and create the plug-in.
    createSilverlight();
  </script>
</div>

<div id="pluginHost2" >
  <script type="text/javascript">

    // Create a variable that references the HTML element that hosts the plug-in.
    var parentElement = document.getElementById("pluginHost2");

    // Create variables that contain unique identifiers for the instance.
    var name = "myslPlugin_2";
    var context = "context_2";

    // Initialize and create the plug-in.
    createSilverlight();

  </script>
</div>

The following JavaScript example shows the corresponding OnLoad event-handling function that is used by both plug-in instances. The context parameter corresponds to the value defined by the plug-in's context initialization parameter.

JavaScript
function onLoad(plugin, userContext, sender)
{
    alert(plugin.id + " : " + userContext + " : " + sender.toString());
}

The Silverlight.js file generates an OnLoad event signature that is different from the event signature documented for OnLoad, which reflects the event signature directly at the plug-in level. The Silverlight.js OnLoad wraps the basic plug-in level OnLoad, adding two useful features:

  • If several plug-in instances are hosted in an HTML page, there is potential for confusion in event handlers about which instance was loaded. The CreateObject and CreateObjectEx functions in Silverlight.js add an optional context parameter for initialization, as decribed previously. Typically, this parameter is set to a unique string. That context value is passed back as an event-handler parameter, making it much simpler to write handler logic that can detect which plug-in's onLoad event is being handled at that time.
  • Instead of using the generic sender object, the Silverlight.js version of onLoad passes the actual Silverlight plug-in instance as the first event-handler parameter value. This saves you a call to sender.GetHost(), and you can store the return value as a variable in script for easy access to the Silverlight plug-in instance.

The Silverlight.js event-generated signature for OnLoad specifies the parameters listed in the following table.

plugin | Object Identifies the Silverlight plug-in that invoked the event.
userContext | String Refers to the unique context string for the plug-in.
sender | Object Refers to the root element of the plug-in. Typically this is a Canvas.

See Also

Silverlight Object Models
Using a Silverlight Plug-in
Overviews


Localized Deployment

This topic introduces how to localize the deployment of your Silverlight-based applications. For example, if you created a Silverlight-based application for a German-speaking audience, you would want them to have a German Web installation prompt with links to a German EULA and a German Privacy statement.

  • Localize for a Single Language
  • Localize for Multiple Languages

Localize for a Single Language

To localize for a single language you need to do the following.

  1. Get the Appropriate Silverlight.js File: There are currently ten different Silverlight.js files, each corresponding to one of eleven different languages. These JavaScript files are available in the SDK. You need to distribute the appropriate Silverlight.js file with your application. For example, if you want to localize your application to Korean, you would need to get the Korean version of Silverlight.js and reference it from your host HTML page.

  2. Reference the Silverlight.js File Appropriately: Change the .js file reference in the HTML head from "Silverlight.js" to "Silverlight.localeTextID.js" using the text id's below:

    Locale | CLCID | Text Id
    English | 0x409 | en-us
    French | 0x40c | fr-fr
    German | 0x407 | de-de
    Spanish | 0x40a | es-es
    Italian | 0x410 | it-it
    Chinese Simplified | 0x804 | zh-chs
    Chinese Traditional | 0x404 | zh-cht
    Korean | 0x412 | ko-kr
    Japanese | 0x411 | ja-jp
    Russian | 0x419 | ru-ru
    Brazilian Portuguese | 0x416 | pt-br

    Note: The English Silverlight.js file will still be available for use as "Silverlight.js" to support updates of the file without code modification to your page.

    For example, in the HTML file you use to host your Silverlight-based application, you would update your reference to Silverlight.js to the Japanese version like this:

    HTML
    ...
<!-- Reference the localized Silverlight.js file from the HTML page
     that hosts the Silverlight plug-in. In this example, the Japanese
     Text Id (ja) is used to reference the Japanese version of Silverlight.js -->
<script type="text/javascript" src="silverlight.ja-jp.js"></script>
...

    Note: The localized Silverlight.js files use UTF-8 encoding. Thus, the referring web page must notify the browser that it is using UTF-8 encoding. This is accomplished using the line of code below under the <HTML> tag:

    HTML
    ...
<html>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
...

Localize for Multiple Languages

You can only reference a single Silverlight.js file from your HTML host file. Because of this, you will need to dynamically create the reference to the silverlight.js file in order to be able to deploy for multiple languages from a single HTML host file. For example, the ASP .NET code below is used to automatically detect the language being used by the user and output the appropriate script reference:

ASP .NET
<%@ Page Language="C#" AutoEventWireup="true" UICulture="auto" Culture="auto" %>
<%@ import namespace="System.Threading" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    protected override void InitializeCulture()  {
        // Do something here if you want to handle a language other than the 0th language automatically
        base.InitializeCulture();
    }
    protected override void  OnInit(EventArgs e) {
        HtmlHead h = this.Header;
        if (h != null) {
            // Get the uiculture string
            String uic = Thread.CurrentThread.CurrentCulture.Name;

            HtmlGenericControl s = new HtmlGenericControl(HtmlTextWriterTag.Script.ToString());
            s.Attributes.Add(HtmlTextWriterAttribute.Type.ToString(), "text/javascript");
            s.Attributes.Add(HtmlTextWriterAttribute.Src.ToString(), "silverlight." + uic + ".js");
            h.Controls.Add(s);
        }
        base.OnInit(e);
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
<head runat="server" id="TheHead">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    View Source to see script reference.
    </div>
    </form>
</body>
</html>

If the user views source and the user's current thread is using English, then the user will see the following script resource.

HTML
...
<Script Type="text/javascript" Src="silverlight.en-US.js"></Script>
...

Naturally, you will need to have all the language appropriate Silverlight.js files available. Using the example above, you would keep them all in the same directory as the HTML file.

See Also

Using CreateSilverlight.js and Silverlight.js


Silverlight Events

Microsoft Silverlight provides a set of events that enable you to respond to actions, such as changes in Silverlight state and user input.

This topic contains the following sections:

  • Attaching an Event Handler
  • Defining an Event Handler
  • JavaScript Events

For information about mouse and keyboard events, see Silverlight Mouse Support and Silverlight Keyboard Support.

Attaching an Event Handler

Silverlight provides events for the event types listed in the following table.

Event type | Events
Plug-in support and object lifetime | OnError OnFullScreenChange OnLoad OnResize Loaded (on UIElement)
Downloader support | Completed (Downloader) DownloadProgressChanged (Downloader)
Focus | GotFocus LostFocus
Image and ImageBrush | ImageFailed (Image) ImageFailed (ImageBrush) DownloadProgressChanged (Image) DownloadProgressChanged (ImageBrush)
Keyboard input | KeyDown KeyUp
Media | BufferingProgressChanged Completed (Storyboard) CurrentStateChanged DownloadProgressChanged (MediaElement) MarkerReached MediaEnded MediaFailed MediaOpened
Mouse input | MouseEnter MouseLeave MouseLeftButtonDown MouseLeftButtonUp MouseMove

Note Silverlight supports the concept of a bubbled event for input events such as mouse events. A bubbled event is an event that is passed from a child object and is forwarded up to each of its successive parent elements in the object hierarchy. For more information about bubbled events, see the "Event Bubbling" section in Silverlight Mouse Support.

The following XAML example shows how to attach a handler for the Loaded event for the Canvas object. Notice that the event-handler function cannot be called with parameter values (even empty ones), unlike JavaScript event-handler functions. Also notice that the event-handler function name is not prefixed with the string "javascript:". The "javascript:" prefix was accepted in prerelease versions of Silverlight, but it is not permitted in the release versions.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  Loaded="onLoaded" />

Defining an Event Handler

A Silverlight event-handler function contains two parameters, as described in the following table.
Parameter | Description
sender | Identifies the Silverlight object that generated the event. You can retrieve the type value of the object by calling the ToString method on the parameter value.
eventArgs | Identifies the set of argument values for the specific event. An event, such as the Loaded event, does not define any event arguments, so the value of eventArgs is null.

Note If the Silverlight event-handler function does not reference the sender and eventArgs parameters, you do not have to define them as part of the function declaration.

The following JavaScript example shows how to define a Silverlight event-handler function. In this case, the code displays a string in an alert dialog box that contains the object type of the sender parameter.

JavaScript
function onLoaded(sender, eventArgs)
{
    // Display the object type of the sender parameter.
    alert("Sender = " + sender.toString());
}

You can reference named Silverlight objects in an event-handler function. Use the x:Name attribute to specify an object's identity.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Loaded="onLoaded">

  <TextBlock x:Name="myTextBlock" />

</Canvas>

The following JavaScript example shows how to use the FindName method to search the Silverlight object tree for a specific named object. In this case, the code displays the current date as the Text property of the TextBlock object. Also notice that the eventArgs parameter is omitted, because it is not referenced by the function.

JavaScript
function onLoaded(sender, eventArgs)
{
    // Set the TextBlock to display the current date and time.
    sender.findName("myTextBlock").text = Date();
}

The previous JavaScript example combines two separate operations in a single line of code. If you want to set multiple properties of a referenced object, you can create an object variable to hold the return value from the findName method, as shown in the following example.

JavaScript
function onLoaded(sender, eventArgs)
{
    // Set the TextBlock to display the current date and time, and set the FontFamily and FontSize properties.
    var textblock = sender.findName("myTextBlock");
    textblock.Text = Date();
    textblock.FontFamily = "Comic Sans MS";
    textblock.FontSize = "24";
}

Defining Events in JavaScript

To add and remove event-handler functions in JavaScript, use the AddEventListener and RemoveEventListener methods. The following JavaScript example shows how to add events to a TextBlock object.

JavaScript
function onLoaded(sender, eventArgs)
{
    textBlock = sender.findName("Status");
    var entertoken1 = textBlock.addEventListener("MouseEnter", onMouseEnter);
    var leavetoken1 = textBlock.addEventListener("MouseLeave", onMouseLeave);
}

To remove an existing event-handler function, use the RemoveEventListener method. The following JavaScript example shows how to remove events from a TextBlock object.

JavaScript
function removeEvents()
{
    textBlock.removeEventListener("MouseEnter", entertoken1);
    textBlock.removeEventListener("MouseLeave", leavetoken1);
}

Capturing Input Events by Capturing the Mouse

You can use the CaptureMouse and ReleaseMouseCapture methods to enable and disable mouse capture. When an object has captured the mouse, it receives mouse input regardless of whether the cursor is within its borders. The mouse is typically captured only during drag operations. For more information about capturing the mouse, see the "Implementing Drag-and-Drop Functionality" section in Silverlight Mouse Support.

JavaScript Events

JavaScript provides a set of events that you can use to respond to changes on the Web page. For example, the following HTML example shows JavaScript code that is triggered by the JavaScript onload event.

JavaScript
<body onload='javascript:alert("onload event generated")'>

In this example, JavaScript code is used directly instead of referencing an event-handler function. This is not possible with Silverlight events. By definition, the JavaScript onload event is not fired until the entire Web page is loaded. This means that any Silverlight plug-in contained within the page fires its Loaded event before the JavaScript onload event.

See Also

Silverlight Mouse Support
Silverlight Keyboard Support
Silverlight Object Models
Using a Silverlight Plug-in
Silverlight Error Handling
Overviews


Silverlight Mouse Support

Silverlight provides a set of events that allow you to respond to mouse actions, such as moving or clicking the mouse.

This topic contains the following sections:

  • Mouse Events
  • Defining a Mouse Event Handler
  • Event Bubbling
  • Implementing Drag-and-Drop Functionality
  • Notes

For a listing of all supported events, see Silverlight Events. For information on keyboard events, see Silverlight Keyboard Support.

Mouse Events

Silverlight provides the following set of mouse events.

Event | Description
MouseMove | Occurs when the coordinate position of the mouse pointer changes. The mouseEventArgs parameter contains input information.
MouseEnter | Occurs when the mouse enters the bounding area of an object. The mouseEventArgs parameter contains input information.
MouseLeave | Occurs when the mouse leaves the bounding area of an object. The mouseEventArgs parameter is null.
MouseLeftButtonDown | Occurs when the left mouse button is down. The mouseEventArgs parameter contains input information.
MouseLeftButtonUp | Occurs when the left mouse button is up, following a MouseLeftButtonDown event. The mouseEventArgs parameter contains input information.

Mouse Event Parameters

A Silverlight event-handler function contains two parameters, described in the following table.
Parameter | Description
sender | Identifies the Silverlight object that generated the event. You can retrieve the type value of the object by calling the ToString method on the parameter value.
mouseEventArgs | Identifies the the current x-coordinate and y-coordinate positions of the mouse pointer, as well as whether the SHIFT and CTRL keys are down. The MouseLeave event, however, does not define this parameter; in this case, the value of mouseEventArgs is null.

Note If the Silverlight event-handler function does not reference the sender and mouseEventArgs parameters, you do not have to define them as part of the function declaration.

Defining a Mouse Event Handler

You can define mouse event-handler functions for Silverlight objects. The following XAML example shows how to define the MouseEnter and MouseLeave events for two Ellipse objects. Notice that the objects share the event-handler functions for each event.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  MouseMove="onMouseMove">

  <Ellipse
    MouseEnter="onMouseEnter"
    MouseLeave="onMouseLeave"
    Height="100" Width="100"
    Fill="Teal" />

  <Ellipse
    MouseEnter="onMouseEnter"
    MouseLeave="onMouseLeave"
    Canvas.Left="120"
    Height="100" Width="100"
    Fill="Teal" />

  <TextBlock x:Name="Status" Canvas.Top="120" />

</Canvas>

The following JavaScript example shows the corresponding Silverlight event-handler functions for the MouseEnter and MouseLeave events.

JavaScript
function onMouseEnter(sender, mouseEventArgs)
{
    sender.fill = "Coral";
}

function onMouseLeave(sender, eventArgs)
{
    sender.fill = "Teal";
}

The following illustration shows the result of the first ellipse receiving the MouseEnter event.

Ellipses change color during MouseEnter and MouseLeave events

Ellipses change color during MouseEnter and MouseLeave events

Using Mouse Events that Pass a MouseEventArgs Parameter

The MouseMove, MouseEnter, MouseLeftButtonDown, and MouseLeftButtonUp events set the mouseEventArgs parameter so that input information can be retrieved. The following JavaScript example shows how to use the GetPosition method to retrieve the current mouse pointer position for the object that received the MouseMove event. In this case, the element parameter is set to null, which means the returned Point value represents the mouse pointer position of the object relative to the upper-left corner of the plug-in area.

JavaScript
function onMouseEnter(sender, mouseEventArgs)
{
    sender.fill = "Coral";
}

function onMouseLeave(sender, eventArgs)
{
    sender.fill = "Teal";
}

The element parameter of the GetPosition method can also be set to any UIElement-derived object that is contained by the Silverlight plug-in. The returned mouse pointer position is relative to element. Depending on the location of element relative to the object, the coordinate values of the mouse position may be negative values.

The following illustration shows how the green Rectangle object uses the red Rectangle object as the value of element, in order to return mouse position values that are relative to the coordinate space of element. This means that clicking near the upper-left corner of the green Rectangle generates mouse position values that are negative with respect to the red Rectangle.

Returning relative mouse position values
Returning relative mouse position values

Note Version 1 of Silverlight does not support high DPI; therefore, objects rendered on the screen and the coordinate system do not scale in response to monitor resolution. In addition, coordinates used by mouse events are not affected by monitor resolution.

The following JavaScript example shows how to retrieve the current mouse pointer position for the object relative to element.

JavaScript
function onMouseLeftButtonUp(sender, mouseEventArgs)
{
    // Return a Point object representing the x- and y-coordinates of the current mouse position
    // relative to the reference object.
    var pt = mouseEventArgs.getPosition(sender.findName("referenceObject"));

    // Display the current mouse position.
    sender.findName("Status").text = pt.x + " : " + pt.y;
}

Defining Mouse Events in JavaScript

To add and remove event-handler functions in JavaScript, use the AddEventListener and RemoveEventListener methods. The following JavaScript example shows how to add events to a TextBlock object.

JavaScript
function onLoaded(sender, eventArgs)
{
    textBlock = sender.findName("Status");
    var entertoken1 = textBlock.addEventListener("MouseEnter", onMouseEnter);
    var leavetoken1 = textBlock.addEventListener("MouseLeave", onMouseLeave);
}

To remove an existing event-handler function, use the RemoveEventListener method. The following JavaScript example shows how to remove events from a TextBlock object.

JavaScript
function removeEvents()
{
    textBlock.removeEventListener("MouseEnter", entertoken1);
    textBlock.removeEventListener("MouseLeave", leavetoken1);
}

Event Bubbling

Silverlight supports the concept of a bubbled event for input events such as mouse events. A bubbled event is an event that is passed from a child object and is forwarded up to each of its ancestors in the object hierarchy.

The MouseMove event is a bubbled event. This means that if multiple MouseMove events are defined for an object and its ancestors, the event is received by each object in the ancestor hierarchy, starting with the object that directly receives the event. Consider the following XAML example in which MouseMove events are defined for a Canvas and two Rectangle objects. In this case, if you move the mouse over either Rectangle object, it receives the MouseMove event. The event is then bubbled up to the parent Canvas.

XAML
<!-- Rectangle MouseMove event fires first, then Canvas MouseMove event -->
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Width="640" Height="480"
  Background="OldLace"
  MouseMove="onCanvasMouseMove"
  Loaded="onLoaded">

  <Rectangle
    x:Name="RectA"
    MouseMove="onRectMouseMove"
    Width="100" Height="100" Fill="PowderBlue" />

  <Rectangle
    x:Name="RectB"
    MouseMove="onRectMouseMove"
    Width="100" Height="100" Fill="Gold"
    Canvas.Top="50" Canvas.Left="50" Opacity="0.5" />

  <TextBlock x:Name="statusTextBlock" Canvas.Top="180" />

</Canvas>

The following JavaScript example shows how to implement the MouseMove event-handler functions for the corresponding XAML content in the previous example.

JavaScript
var statusTextBlock;

function onLoaded(sender) {
  statusTextBlock = sender.findName("statusTextBlock");
}

function onCanvasMouseMove(sender, mouseEventArgs)
{
  var msg = "x:y = " + mouseEventArgs.getPosition(null).x + ", " + mouseEventArgs.getPosition(null).y;
  // Uncomment the next line to show MouseMove event bubbling.
  //statusTextBlock.text = "Canvas: " + msg;
}

function onRectMouseMove(sender, mouseEventArgs)
{
  var msg = " x:y = " + mouseEventArgs.getPosition(null).x + ", " + mouseEventArgs.getPosition(null).y;
  statusTextBlock.text = sender.name + msg;
}

Implementing Drag-and-Drop Functionality

Drag-and-drop functionality is a very useful feature of interactive content. You can easily add drag-and-drop functionality to a Silverlight plug-in by implementing simple event-handler functions on three mouse events: MouseLeftButtonDown, MouseLeftButtonUp, and MouseMove.

A drag-and-drop operation is a sequence of three steps:

  • Mouse down. The object is selected. The object must have exclusive access to all mouse events generated by the Silverlight plug-in that contains it.
  • Mouse move. The object moves to a new position, relative to the current position of the mouse.
  • Mouse up. The object stops responding to mouse events.

Note: The drag-and-drop behavior described in this topic is limited to a single Silverlight plug-in. You cannot drag an object between two Silverlight plug-ins.

The following XAML example shows two objects that share the same three mouse event handlers, because the drag-and-drop functionality is implemented in the same way for all the objects.

XAML
<!-- Define a circular object. -->
<Canvas
  MouseLeftButtonDown="onMouseDown"
  MouseLeftButtonUp="onMouseUp"
  MouseMove="onMouseMove"
  Canvas.Top="20" Canvas.Left="50">
  <Ellipse
    Height="100" Width="100"
    Fill="Gold"
    Stroke="Black" StrokeThickness="4" />
  <Ellipse
    Height="50" Width="50"
    Canvas.Top="25" Canvas.Left="25"
    Fill="Black" />
</Canvas>

<!-- Define a diamond-shaped object. -->
<Canvas
  MouseLeftButtonDown="onMouseDown"
  MouseLeftButtonUp="onMouseUp"
  MouseMove="onMouseMove"
  Canvas.Top="140" Canvas.Left="100">
  <Canvas.RenderTransform>
    <RotateTransform Angle="45" />
  </Canvas.RenderTransform>

  <Rectangle
    Height="100" Width="100"
    Fill="Coral"
    Stroke="Black" StrokeThickness="4" />
</Canvas>

Note The Canvas object is used to group all the elements that compose an object. This enables the whole group to act as a unit during drag-and-drop operations. Likewise, any RenderTransform applied to the Canvas object affects all the elements of the object.

Starting the Drag-and-Drop Operation

The onMouseDown event-handler function in the following JavaScript example initiates the drag-and-drop operation by storing the beginning position of the mouse, setting a flag to indicate that the drag-and-drop operation is in effect, and gaining exclusive access to mouse events by invoking the CaptureMouse method. When an object has captured the mouse, it receives mouse input regardless of whether the cursor is within its borders.

JavaScript
// Define state variables for drag and drop operation.
var beginX;
var beginY;
var isMouseDown = false;

// Start drag and drop operation.
function onMouseDown(sender, mouseEventArgs)
{
    // Set the beginning position of the mouse.
    beginX = mouseEventArgs.getPosition(null).x;
    beginY = mouseEventArgs.getPosition(null).y;

    isMouseDown = true;

    // Ensure this object is the only one receiving mouse events.
    sender.captureMouse();
}

Moving an Object During the Drag-and-Drop Operation

The onMouseMove event-handler function in the following JavaScript example determines whether the drag-and-drop operation is in effect by testing the value of the isMouseDown variable. If the drag-and-drop operation is in effect, the incremental difference between the last stored mouse position and the current mouse position is applied to the object's Canvas.Top and Canvas.Left values.

JavaScript
// Reposition object during drag and drop operation.
function onMouseMove(sender, mouseEventArgs)
{
    // Determine whether the mouse button is down.
    // If so, move the object.
    if (isMouseDown == true)
    {
        // Retrieve the current position of the mouse.
        var currX = mouseEventArgs.getPosition(null).x;
        var currY = mouseEventArgs.getPosition(null).y;

        // Reset the location of the object.
        sender["Canvas.Left"] += currX - beginX;
        sender["Canvas.Top"] += currY - beginY;

        // Update the beginning position of the mouse.
        beginX = currX;
        beginY = currY;
    }
}

Stopping the Drag-and-Drop Operation

The onMouseUp event-handler function in the following JavaScript example stops the drag-and-drop operation by setting a flag to indicate that the drag-and-drop operation is no longer in effect, and invoking the ReleaseMouseCapture method on the object. This method releases the object's exclusive access to the Silverlight plug-in's mouse events. This means that all objects can now receive mouse events.

JavaScript
// Stop drag and drop operation.
function onMouseUp(sender, mouseEventArgs)
{
    isMouseDown = false;

    // Allow all objects to receive mouse events.
    sender.releaseMouseCapture();
}

How Mouse Capture Enables Drag-and-Drop Functionality

The reason why all the objects in the preceding XAML example can share mouse event handlers is that each object enables mouse capture during the drag-and-drop operation. As a result, when you drag an object such as the circular object, no mouse events are sent to other objects. Therefore, when the circular object is dragged under the diamond-shaped object, the diamond-shaped object does not receive mouse events, although the mouse cursor is directly over it.

Dragging the circular object does not trigger mouse events for the diamond-shaped object
Dragging the circular object does not trigger mouse events for the diamond-shaped object

Mouse capture also ensures that drag-and-drop operations perform correctly when you move the mouse quickly. As long as mouse capture is enabled, the mouse cursor does not need to be exactly on the object being dragged. Eventually, the object that is being dragged will render under the mouse cursor.

Notes

In Safari, if an unhandled exception occurs in the event-handler code, no further mouse-related event handlers are called for the lifetime of the Silverlight plug-in. In other browsers, only the handler that contained the error will exit (usually with a scripting error returned to the browser); other errorless mouse event handlers can continue to function.

See Also

Silverlight Events
Silverlight Keyboard Support
Silverlight Object Models
Using Silverlight Plug-ins
Silverlight Error Handling
Overviews


Silverlight Keyboard Support

Microsoft Silverlight provides a set of keyboard events that enable you to respond to keystroke actions.

This topic contains the following sections:

  • Keyboard Events
  • Defining a Keyboard Event Handler
  • Platform Differences for Keyboard Events

Keyboard Events

Silverlight provides the keyboard events described in the following table.

Event | Description
KeyDown | Occurs when the key is pressed while the content has focus.
KeyUp | Occurs when the key is released while the plug-in has focus.

Note Handling keyboard events might vary between browsers. When you create an application that uses keyboard input, make sure to test the application in your target browsers.

The following XAML example shows how to define the KeyDown event for the Canvas object. Notice that the event-handler function cannot be called with parameter values, unlike JavaScript event-handler functions.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  KeyUp="onKeyUp" />

Note Keyboard events can be defined only for the root Canvas object of a Silverlight plug-in.

The following example shows how to define a Silverlight keyboard event in JavaScript. If you attempt to define a keyboard event for any object other than the root Canvas object, a parser exception is thrown.

JavaScript
function onLoaded(sender, eventArgs)
{
    // Set the root Canvas object to a KeyUp event handler function.
    sender.addEventListener("KeyUp", onKeyUp);
}

Keyboard Events and Focus

In order for a keyboard event to be received, the Silverlight plug-in needs to have focus; otherwise, the events are not generated. A Silverlight plug-in can gain focus through user actions such as clicking the plug-in or tabbing to it.

Keyboard Events and the Browser

The browser determines which keystrokes it interprets as commands, and which keystrokes it passes on to hosted content. This means that certain keystrokes cannot be retrieved from KeyDown and KeyUp event-handler functions. Most keystrokes that a browser interprets as commands are shortcut, or accelerator, keystokes. For example, CTRL+D is a shortcut keystroke combination for adding a favorite URL to the Firefox and Internet Explorer browsers.

Keyboard Events and Full-Screen Mode

When a Silverlight plug-in is displayed in full-screen mode, keyboard events are prevented from being passed to keyboard event handlers in the application. The only valid keyboard input that is acted upon is the set of keystrokes that returns the Silverlight plug-in to embedded mode. This limitation of keyboard input during full-screen mode is a security feature. It is intended to minimize the possibility of unintended information being entered by a user. For more information on full-screen mode, see Silverlight Full-Screen Support.

Defining a Keyboard Event Handler

A Silverlight keyboard event-handler function contains two parameters, as described in the following table.
Parameter | Description
sender | Identifies the Silverlight object that generated the event. You can retrieve the type value of the object by calling the ToString method on the parameter value.
keyEventArgs Identifies the set of argument values for the specific event. The keyEventArgs parameter contains the following values:
  • Key -- An integer value that represents the key that is down. This value is the portable key code, which is not operating system-specific.
  • PlatformKeyCode -- An integer value that represents the key that is down. This value is the non-portable key code, which is operating system-specific.
  • Shift -- A Boolean value that determines whether the SHIFT key is down.
  • Ctrl -- A Boolean value that determines whether the CTRL key is down.

Note If the Silverlight event-handler function does not reference the sender and keyEventArgs parameters, you do not have to define them as part of the function declaration.

The following JavaScript example shows how to define a Silverlight event-handler function for the KeyDown event. In this case, the code displays a string in an alert dialog box that contains the version of the Silverlight plug-in.

JavaScript
function onKeyUp(sender, keyEventArgs)
{
    // Determine whether the keystroke combination CTRL+V was detected.
    if ((keyEventArgs.key == 51) && (keyEventArgs.ctrl == true))
    {
        // Retrieve a reference to the plug-in.
        var plugin = sender.getHost();

        // Determine whether the 1.0 version of Silverlight is available.
        alert("Silverlight 1.0: " + plugin.isVersionSupported("1.0"));
    }
}

Detecting the SHIFT and CTRL Keys in a Mouse Event Handler

The MouseEnter, MouseLeftButtonDown, MouseLeftButtonUp, and MouseMove events enable you to determine whether the SHIFT or CTRL keys are down when the mouse event-handling function is invoked. The following JavaScript example shows how to implement a MouseLeftButtonDown event-handler function that displays the values of the mouseEventArgs parameter.

JavaScript
function onMouseLeftButtonUp(sender, mouseEventArgs)
{
    // Concatenate the values of the MouseEventArgs parameter.
    var msg  = "x = " + mouseEventArgs.getPosition(null).x;
    msg += "  y = " + mouseEventArgs.getPosition(null).y;
    msg += "  shift = " + mouseEventArgs.shift;
    msg += "  ctrl = " + mouseEventArgs.ctrl;

    alert(msg);
}

Platform Differences for Keyboard Events

The keyboardEventArgs parameter of KeyDown and KeyUp events provides two types of key codes:
  • Key -- A portable key code that is not operating system-specific.
  • PlatformKeyCode -- A non-portable key code that is operating system-specific.

The portable key codes are a common subset of all the possible key codes of the supported operating systems, in this case, Macintosh and Windows. For example, the keystroke 'v' is represented as a Key value of 51, and a PlatformKeyCode value of 86. Certain keystrokes, however, are not portable, such as the Windows SCROLL LOCK key. In this case, the Key value is 255, which is the value for an unknown key, and the PlatformKeyCode is 145 on a Windows platform. For information about Windows-specific key codes, see "Virtual-Key Codes" in the MSDN Library at http://msdn.microsoft.com/library. For information on Macintosh-specific key codes, see Keyboard Layout Services Reference on the Apple Developer Connection Web site.

Detecting Platforms in JavaScript

When you visit a Web page, your browser sends the user agent string to the server that is hosting the site you are visiting. This string indicates which browser you are using, its version number, and details about your system, such as operating system and version. You can use this string to determine the platform the browser-hosted Silverlight plug-in is running on. The following JavaScript example shows how to create a set of variables that you can use in keyboard event-handling functions to determine the platform.

JavaScript
// Create variables to detect browser platform.
var is_mac = (navigator.userAgent.indexOf("Macintosh") != -1);
var is_win = (navigator.userAgent.indexOf("Windows") != -1);

See Also

Key
KeyDown
KeyUp
AddEventListener
RemoveEventListener
Silverlight Events
Overviews


Using the CreateFromXaml Method

The CreateFromXaml method enables you to create XAML content dynamically, and then add the content to the existing Microsoft Silverlight object hierarchy. You can create a single Silverlight object, such as a TextBlock, or an entire tree of Silverlight objects. For more information on XAML, see XAML Syntax Overview.

This topic contains the following sections:

  • Overview
  • Creating a Single XAML Object
  • Creating a Tree of XAML Objects

Overview

The Silverlight content on your Web page is arranged as a hierarchy of objects in a tree structure. The single, topmost object in the structure is the root object. The root object is generally a Canvas object, because it can contain other objects such as TextBlock or MediaElement.

To add XAML content dynamically to the tree structure, you first create the XAML fragment by using the CreateFromXaml method. At this point, the XAML fragment you create is disconnected from the Silverlight object hierarchy. This means that the fragment is not rendered yet. However, you can modify the properties of the objects in the XAML fragment. Object methods cannot be invoked.

The XAML that you specify as the parameter to CreateFromXaml must have a single root (it must be well-formed XML in that regard). If you attempt to call CreateFromXaml by using a string that equates to XML that has multiple roots or is otherwise not well-formed, the CreateFromXaml method call will fail and raise an error. The XML root does not need to specify the Silverlight xmlns, as long as it is eventually added to content that does specify the Silverlight xmlns at its root.

Note In order to guard your Silverlight application against security attacks, it is strongly recommended that you do not pass in untrusted XAML to the createFromXAML method. For example, untrusted XAML could contain a mock-up interface that mirrors a legitimate site, leading to a spoofing type security threat. Additionally, XAML contains references to script event handlers. Adding untrusted XAML to the live tree could result in unintended execution of script. Always validate that XAML passed in to createFrom XAML is from a source that your Silverlight application considers trusted.

The following illustration shows the relationship between the Silverlight object hierarchy and the XAML fragment.

Disconnected Silverlight object hierarchy and XAML fragment
Disconnected Silverlight object hierarchy and XAML fragment

Once you have created a disconnected object set from out of an XAML fragment, you can add it to the active Silverlight object hierarchy. The fragment can either be added as a child object to a parent object that is capable of supporting child objects, or set as a property value of an object. When the fragment becomes part of the Silverlight object hierarchy, the objects in the XAML fragment are rendered. The following illustration shows the relationship between the Silverlight object hierarchy and the XAML fragment when they are connected.

Connected Silverlight object hierarchy and XAML fragment
Connected Silverlight object hierarchy and XAML fragment

There are several requirements for adding XAML content dynamically to the Silverlight object hierarchy:

  • There must be existing XAML content associated with the Silverlight plug-in; you cannot use CreateFromXaml to replace the entire tree of content, you must at the very least preserve the original root element. If you want to replace the entire tree, you can set Source, although note that Source requires an actual file to exist at a URI, and cannot be initialized with just a string. However, you can work around this issue by using inline XAML as the Source, and using the HTML DOM to document.write the contents of the SCRIPT block that contains the intended source XAML. For details, see Using Inline XAML as the XAML Source.
  • The CreateFromXaml method can be invoked only by the Silverlight plug-in.
  • XAML content that is created by using the CreateFromXaml method can be assigned only to one object. If you want to add objects created from identical XAML to different areas of the application, you must invoke CreateFromXaml multiple times and use different variables for the return value. (If you do this, be careful of name collisions; see XAML Namescopes.)
  • The Silverlight object that will contain the new XAML content must be capable of encapsulating an object, either as a child element or as a property value.

Creating a Single XAML Object

The following JavaScript example shows how to add a TextBlock to an existing Canvas object.

JavaScript
// MouseLeftButtonUp event handler for the root Canvas object.
function onMouseLeftButtonUp(sender, eventArgs)
{
    // Retrieve a reference to the plug-in.
    var plugin = sender.getHost();

    // Define a XAML fragment and create it.
    var xamlFragment = '<TextBlock Canvas.Top="200" Text="Click for more info..." />';
    textBlock = plugin.content.createFromXaml(xamlFragment);

    // Add the XAML fragment as a child of the root Canvas object.
    sender.children.add(textBlock);
}

Note XAML content that is created by using the CreateFromXaml method is not rendered until it is added to an object by using the add method.

If you want to use the x:Name attribute value as part of your XAML fragment, you have to provide the XML namespace reference as part of the XAML content. For example, in order for the previous XAML fragment example to use the x:Name attribute value, it will have to be rewritten as shown in the following example.

JavaScript
    // Define a XAML fragment and create it.
    var xamlFragment = '<TextBlock xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" ';
       xamlFragment += 'x:Name="myCanvas" Canvas.Top="200" Text="Click for more info" />';

    textBlock = plugin.content.createFromXaml(xamlFragment);

Note If you use an x:Name attribute value that already identifies an object in the Silverlight object hierarchy, an error is generated when you invoke the Add method for the XAML fragment. For a complete discussion of namescopes and using Name values in the content that you create with CreateFromXAML, see XAML Namescopes.

Creating a LinearGradient Brush Object

You can also create XAML content that can be used as a property value for an object. The following JavaScript example shows how to create a LinearGradientBrush and add it as the Fill property for an Ellipse object.

JavaScript
// MouseEnter event handler for the Ellipse object.
function onMouseEnter(sender, eventArgs)
{
    // Set the Fill property of the Ellipse to the dynamically generated LinearGradientBrush.

    try
    {
    sender.fill = createLinearGradientBrush(sender.getHost());
    }
    catch(error)
    {
        alert(error.message);
    }
}

function createLinearGradientBrush(plugin)
{
    // Define a XAML fragment.
    var xamlFragment = '<LinearGradientBrush>';
       xamlFragment +=   '<GradientStop Color="Yellow" Offset="0.0" />';
       xamlFragment +=   '<GradientStop Color="Orange" Offset="0.5" />';
       xamlFragment +=   '<GradientStop Color="Red" Offset="1.0" />';
       xamlFragment += '</LinearGradientBrush>';

    // Create the XAML fragment and return it.
    return plugin.content.createFromXaml(xamlFragment);
}

In the previous example, if you wanted to assign the dynamically created LinearGradientBrush to more than one object, you would have to invoke the createLinearGradientBrush function for each object, as shown in the following example.

JavaScript
function initFill(objectArray)
{
    // Set the Fill property for each item in the object array.
    for (i = 0; i < objectArray.length; i++)
    {
        objectArray[i].fill = createLinearGradientBrush();
    }
}

Defining Events in XAML Fragments

XAML fragments can define events as part of the content. The following JavaScript example shows how to define MouseEnter and MouseLeave events for a Rectangle object. In this case, the stroke of the Rectangle increases when the mouse enters the object boundary, and decreases when the mouse leaves the object boundary.

JavaScript
function onLoaded(sender, eventArgs)
{
    // Retrieve a reference to the plug-in.
    var plugin = sender.getHost();

    // Define a XAML fragment.
    var xamlFragment = '<Rectangle Width="100" Height="40" Fill="OldLace" ';
       xamlFragment += 'StrokeThickness="1" Stroke="Black" ';
       xamlFragment += 'MouseEnter="onMouseEnter" MouseLeave="onMouseLeave" />';

    // Create the XAML fragment.
    var rectangle = plugin.content.createFromXaml(xamlFragment);

    // Add the XAML fragment as a child of the root Canvas object.
    sender.children.add(rectangle);
}

function onMouseEnter(sender, eventArgs)
{
    // Increase the stroke on entering.
    sender.StrokeThickness = 2;
}

function onMouseLeave(sender, eventArgs)
{
    // Decrease the stroke on leaving.
    sender.StrokeThickness = 1;
}

Creating a Tree of XAML Objects

The CreateFromXaml method also enables you to create an entire tree of XAML objects. In addition, you can remove the tree as needed, without de-allocating the objects. The ability to add and remove XAML content dynamically lets you create application features such as tooltips that appear only when the mouse is over a certain part of the Web page.

The following JavaScript example shows how to create a custom tooltip that consists of a hierarchy of Canvas, Rectangle, and TextBlock objects. The tooltip is then added as a child to the main Canvas object when the mouse enters a specific object boundary. The tooltip is removed when the mouse leaves the specific object boundary.

JavaScript
// Define global variables.
var plugin, toolTip, mainCanvas;

// Set global variables for the plug-in and main Canvas objects.
function onLoaded(sender, eventArgs)
{
    plugin = sender.getHost();
    mainCanvas = sender;
}

function onMouseEnter(sender, args) {
    // Determine whether the tool tip is created.
    if (toolTip == null) {

        // Define the XAML fragment for the tool tip.
        var xamlFragment = '<Canvas Width="150" Height="30" Background="#FFFFE1">';
           xamlFragment +=   '<Rectangle Width="150" Height="30" Stroke="Black" />';
           xamlFragment +=   '<TextBlock Text="Hello, World" Canvas.Left="10" Canvas.Top="5" />';
           xamlFragment += '</Canvas>';

        // Create the XAML fragment for the tool tip.
        toolTip = plugin.content.createFromXaml(xamlFragment);

        // Position the tool tip at a relative x/y coordinate value.
        var cursorPosition = args.getPosition(sender);
        toolTip["Canvas.Left"] = cursorPosition.x + 30;
        toolTip["Canvas.Top"] = cursorPosition.y + 40;
    }

    // Add the tool tip to the Canvas object.
    mainCanvas.children.add(toolTip);
}

function onMouseLeave(sender, args)
{
    // Determine whether the tool tip is created.
    if (toolTip != null)
    {
        // Remove the tool tip from the Canvas object.
        mainCanvas.children.remove(toolTip);
    }
}

This JavaScript example also illustrates that you can modify the properties of a XAML fragment before it is attached to the Silverlight object hierarchy. However, you cannot invoke method calls on any object in the XAML fragment before it is attached to the Silverlight object hierarchy. Notice that the properties that are modified are Canvas.Left and Canvas.Top. These properties represent the position of the object relative to its parent. In this case, the parent is the main Canvas object, and the child is the tooltip Canvas object.

JavaScript
// Position the tool tip at a relative x/y coordinate value.
var cursorPosition = args.getPosition(sender);
toolTip["Canvas.Left"] = cursorPosition.x + 30;
toolTip["Canvas.Top"] = cursorPosition.y + 40;

You can also modify a Silverlight object hierarchy by deleting objects. For example, the remove method on the Canvas object's collection of children enables you to specify an object to delete. For more information, see Referencing and Modifying Silverlight Objects.

JavaScript
// Remove the tool tip from the Canvas object.
mainCanvas.children.remove(toolTip);

See Also

Silverlight Object Models
Referencing and Modifying Silverlight Objects
XAML Namescopes
XAML Syntax Overview
Overviews


Referencing and Modifying Silverlight Objects

You can access and modify objects in your Microsoft Silverlight-based application at run time. For objects that are part of a collection or child objects, you can use the methods of the Collection object to reference and modify object values.

This topic contains the following sections:

  • Referencing Objects
  • Referencing Object Properties
  • Adding Objects
  • Removing Objects
  • Changing the Z-Order of Objects

Referencing Objects

You can reference objects in the Silverlight object hierarchy by using the methods of the Document Object Model (DOM) and Silverlight object model.

Referencing the Silverlight Plug-in

You can retrieve the Silverlight plug-in value by using the GetHost method from any UIElement-derived object. This method is useful in event-handler functions in which the sender parameter is passed. The following JavaScript example shows how to retrieve the Silverlight plug-in by using the GetHost method.

JavaScript
function onKeyUp(sender, keyEventArgs)
{
    // Determine whether the keystroke combination CTRL+V was detected.
    if ((keyEventArgs.key == 51) && (keyEventArgs.ctrl == true))
    {
        // Retrieve a reference to the plug-in.
        var plugin = sender.getHost();

        // Determine whether the 1.0 version of Silverlight is available.
        alert("Silverlight 1.0: " + plugin.isVersionSupported("1.0"));
    }
}

For more information about accessing Silverlight plug-ins, see Using Silverlight Plug-ins.

Finding a XAML Object

You can find any object in the Silverlight object hierarchy by using the FindName method and referencing the object's Name or x:Name attribute value. The object you are searching for does not have to be a direct child element of the object that invokes the FindName method. If the method is successful and finds an object by that name, a reference to the object is returned; otherwise, null is returned. The following JavaScript example shows how to find a named object in the XAML tree when the root Canvas is loaded.

JavaScript
// Loaded event handler for the root Canvas object.
function onLoaded(sender, eventArgs)
{
    // Retrieve the object corresponding to the x:Name attribute value.
    var found = sender.findName("RedRect");

    // Determine whether the object was found.
    if (found != null)
    {
        alert(found.toString());
    }
    else
    {
        alert("Object not found");
    }
}

Referencing an Object in a Collection

You can retrieve a specific child of a parent object by referencing the index of the collection of the parent object. The following JavaScript example shows how to retrieve a child of a parent Canvas object by using the GetItem method.

JavaScript
function getObject(parent, index)
{
    // Determine if the index is valid.
    if (index < parent.children.count)
    {
        // Retrieve the child object at the specified index in the collection.
        var object = parent.children.getItem(index);
    }

    return object;
}

Enumerating Child Objects

You can enumerate the child elements of a parent object by accessing the children collection of the parent object, and looping through each index in the collection while the index is lower than the count. The following JavaScript example shows how to enumerate the children of a parent Canvas object, which has a child element collection named Children.

JavaScript
function getChildren(parent, index)
{
    // Enumerate the children of the Canvas object.
    for (i = 0; i < parent.children.count; i++)
    {
        var child = parent.children.getItem(i);

        // Display the index and type of the child object.
        alert(i + ": " + child.toString());
    }
}

Referencing Object Properties

Properties in the Silverlight 1.0 object model are directly exposed to JavaScript through an object.property notation, in the same way that most other programming models that support JavaScript expose their properties. Many properties can also have a value set in XAML, by specifying the property through a variety of possible XAML syntaxes (see XAML Syntax Overview). The Silverlight object model also provides two accessor methods GetValue and SetValue, which get and set properties based on passing the relevent property's name as a string. You generally do not need to use the GetValue / SetValue methods. The object.property notation for getting and setting properties is entirely equivalent and is generally more intuitive.

Using the GetValue Method

The following JavaScript example shows how to get a property value by using both the GetValue method and by the conventional object.property notation.

JavaScript
function onMouseLeftButtonUp(sender, index)
{
    // Get the property value using the GetValue method.
    var opacity = sender.getValue("opacity");

    // Get the property value using the equivalent "." notation.
    var opacity = sender.opacity;

    alert("Opacity = " + opacity);
}

Using the SetValue Method

The following JavaScript example shows how to set a property value by using both the SetValue method and the conventional object.property notation.

JavaScript
function onMouseEnter(sender, index)
{
    // Set the property value using the SetValue method.
    sender.setValue("opacity", 0.5);

    // Set the property value using the equivalent "." notation.
    sender.opacity = 0.5;
}

Attached Properties

Attached properties are a concept that is part of the XAML language. You can set an attached property on objects or XAML elements even if that property is not conventionally defined in the setting object's list of properties. For attached properties such as Canvas.Top, the object.property notation does not work, because the two "dots" in the syntax create ambiguity. Instead, you set attached properties in Silverlight by using a syntax that resembles an indexer syntax: object["attachedPropertyName"], where the attachedPropertyName is a string that defines the full dotted name of the attached property (for example "Canvas.Top"). In both the GetValue/SetValue notations and the abridged notation, the "." (dot) is considered part of the property name/identifier.

JavaScript
// Set the property value using the SetValue method.
sender.setValue("Canvas.Top", 40);

// Set the property value using the equivalent "." notation.
sender["Canvas.Top"] = 40;

Adding Objects

You can add XAML content to objects that support child objects, such as the Canvas object. The following JavaScript example shows how to create a TextBlock and add it to the root Canvas object by using the Add method on the object's collection of children.

JavaScript
var textBlock;

function onLoaded(sender, eventArgs)
{
    // Retrieve the id of the plug-in.
    var plugin = sender.getHost();

    // Define and create a XAML fragment.
    var xamlFragment = '<TextBlock Canvas.Top="200" Opacity=".5" Text="Click for more info" />';
    textBlock = plugin.content.createFromXaml(xamlFragment);

    // Add the TextBlock to the root Canvas object.
    sender.children.add(textBlock);
}

// Toggle the Opacity property for the TextBlock.
function onToggle()
{
    if (textBlock.opacity)
    {
        textBlock.opacity = 0;
    }
    else
    {
        textBlock.opacity = 1;
    }
}

How Adding Objects Affects Z-Order

When you use the Add method, you add the object to the end of the parent object's collection. Because sibling objects are rendered starting from the first object to the last object, an object added to the end of a collection is displayed on top of all of its sibling objects. The following JavaScript example shows three objects added to a collection.

JavaScript
// Add three overlapping Rectangle objects.
function AddItems(rootCanvas)
{
    var plugin = rootCanvas.getHost();

    var xamlFragment = '<Rectangle Fill="Maroon" Canvas.Top="20" Canvas.Left="20" Height="100" Width="100" />';
    var rectangle_1 = plugin.content.createFromXaml(xamlFragment);
    rootCanvas.children.add(rectangle_1);

    var xamlFragment = '<Rectangle Fill="LightBlue" Canvas.Top="40" Canvas.Left="40" Height="100" Width="100" />';
    var rectangle_2 = plugin.content.createFromXaml(xamlFragment);
    rootCanvas.children.add(rectangle_2);

    var xamlFragment = '<Rectangle Fill="Teal" Canvas.Top="60" Canvas.Left="60" Height="100" Width="100" />';
    var rectangle_3 = plugin.content.createFromXaml(xamlFragment);
    rootCanvas.children.add(rectangle_3);
}

The following illustration shows the result of the previous JavaScript example. Notice that when you add objects to a collection, the object that was added most recently is higher in the z-order. In this case, the third rectangle is displayed on top of the two other rectangles. Notice the index value of each new object as it is added to the collection.

Z-order of objects added to the collection
Z-order of added objects

Inserting an Object into a Collection

When you use the Insert method, you add the object to a specified index in the parent object's collection. Existing objects are shifted to make room for the new inserted object. The following JavaScript example shows an object inserted into the beginning of a collection.

JavaScript
// Insert an overlapping Rectangle object.
function InsertItem(rootCanvas)
{
    var plugin = rootCanvas.getHost();

    var xamlFragment = '<Rectangle Fill="Black" Canvas.Top="0" Canvas.Left="0" Height="100" Width="100" />';
    var rectangle_4 = plugin.content.createFromXaml(xamlFragment);
    rootCanvas.children.insert(0, rectangle_4);
}

The following illustration shows the result of the previous JavaScript example. Notice the rendering of the inserted object. Because the inserted object is the first object in the collection, it is overlaid by all of its siblings.

Z-order of an object inserted into the collection
Z-order of inserted objects

Removing Objects

You can remove objects from the Silverlight object hierarchy by using the Remove and RemoveAt methods. As soon as objects are removed from the Silverlight object hierarchy, they are no longer rendered. When you remove an object by using the Remove or RemoveAt methods, you are disconnecting the object from the Silverlight object hierarchy. The disconnected object is now a XAML fragment that can be connected back to the object hierarchy by using the Add method. The following two illustrations show the process of disconnecting objects from the Silverlight object hierarchy.

Removing an object from the Silverlight object hierarchy
Removing an object

Disconnected XAML fragment and Silverlight object hierarchy
Disconnecting an object

The following JavaScript example shows how to remove a TextBlock from its parent Canvas object by using the Remove method on the object's collection of children.

JavaScript
function removeCaption(rootCanvas)
{
    // Retrieve the TextBlock object.
    var captionTextBlock = rootCanvas.findName("myCaption");

    if (captionTextBlock != null)
    {
        rootCanvas.children.remove(captionTextBlock);
    }
}

The RemoveAt method lets you remove a child object at a specified index value in the parent's collection. This means that the child object does not require an x:Name attribute value. The following JavaScript example shows how to remove the first object from a parent Canvas object by using the RemoveAt method.

JavaScript
// Remove the first child object from the parent collection.
myCanvas.children.removeAt(0);

Removing All Objects from a Collection

You can remove all objects in a collection by using the Clear method, which is equivalent to using the RemoveAt method for each item in the collection. The following JavaScript example shows how to remove all items from a collection by using the Clear method.

JavaScript
// Remove all child objects from the parent collection.
myCanvas.children.clear();

Changing the Z-Order of Objects

The Canvas.ZIndex property value represents the z-order rendering behavior of objects in a collection. The following XAML example shows how to define two sets of Rectangle objects. In the second set of rectangles, the Canvas.ZIndex property is set to invert the z-order.

XAML
<!-- Render rectangles using default z-order (position within the collection). -->
<Canvas>
  <Rectangle
    Fill="Maroon" Canvas.Top="20" Canvas.Left="20" Height="100" Width="100" />
  <Rectangle
    Fill="LightBlue" Canvas.Top="40" Canvas.Left="40" Height="100" Width="100" />
  <Rectangle
    Fill="Teal" Canvas.Top="60" Canvas.Left="60" Height="100" Width="100" />
</Canvas>

<!-- Render rectangles using explicit z-order by using Canvas.ZIndex. -->
<Canvas Canvas.Left="200">
  <Rectangle
    Canvas.ZIndex="2"
    Fill="Maroon" Canvas.Top="20" Canvas.Left="20" Height="100" Width="100" />
  <Rectangle
    Canvas.ZIndex="1"
    Fill="LightBlue" Canvas.Top="40" Canvas.Left="40" Height="100" Width="100" />
  <Rectangle
    Canvas.ZIndex="0"
    Fill="Teal" Canvas.Top="60" Canvas.Left="60" Height="100" Width="100" />
</Canvas>

The following illustration displays the result of the previous XAML content example:

Changing the z-order of objects within a collection
Changing the z-order of objects

The first set of Rectangle objects uses the default z-order rendering of objects, which is based on the position of the child object in the Canvas collection. The first object in the collection is rendered first, followed by the second object, and so on. The second set of Rectangle objects uses the Canvas.ZIndex property to override the default z-ordering of objects in the collection.

In the second set of Rectangle objects, the first object (the maroon-colored one) is the highest in the z-order, or closest to the foreground. Its Canvas.ZIndex value is "2". This is a purely arbitrary value, but it must be greater than any other child object Canvas.ZIndex value in the Canvas collection. If you do not set the Canvas.ZIndex value explicitly, it defaults to 0.

You can also set the Canvas.ZIndex value to a negative value such as "-99", which places the object even farther from the foreground. Canvas.ZIndex values are aligned along the z-axis. Higher values are closer to the foreground; lower values are farther from the foreground. The following illustration shows the relationship of z-order to z-axis.

Relationship of z-order to z-axis
Relationship of z-order to z-axis

See Also

Using Silverlight Plug-ins
Silverlight Events
Overviews


Text and Fonts Overview

Microsoft Silverlight provides several elements for rendering text, along with a set of properties for creating a variety of formatted text.

This topic contains the following sections:

  • Text_Elements
  • Formatting Text
  • Applying Transforms to Text
  • Using SetFontSource for Downloaded Fonts
  • Animating Text

Text Elements

The TextBlock object is the primary element for displaying text in Silverlight-based applications. The following XAML example shows how to define a TextBlock element and set its Text property to a character string.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007">
  <TextBlock Text="Hello, world!" />
</Canvas>

The following illustration displays the result of the previous XAML content example.

TextBlock rendering with default font properties
Default TextBlock rendering

There are several interesting items to note about the rendered text:

  • The default value of the FontSize property of the rendered TextBlock is 14.666 pixels, which is exactly 11 points.
  • The default value of the FontFamily property of the rendered TextBlock is "Lucida Sans Unicode, Lucida Grande".
  • No font files are required on the hosting Web server, or residing in the same directory location as the XAML content, to enable the default font.

When setting text in a TextBlock, it is not necessary to specify the Text property explicitly in XAML.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007">
  <TextBlock>Hello, world!</TextBlock>
</Canvas>

Note Leading or trailing white space is not preserved when setting the Text property.

Specifying Font Attributes

The following table lists the font attributes that can be applied to text elements such as a TextBlock.

Property | Description | Default Value
FontFamily | Represents a set of typefaces that share the same family name, such as "Times New Roman", but that differ in features. These feature differences include FontStyle, such as italic, and FontWeight, such as bold. | The default value is "Portable User Interface", which is used as an alias for the font family value of "Lucida Sans Unicode, Lucida Grande".
FontSize | Specifies a non-negative value as the desired font size in pixels. | The default value is 14.666 pixels, which is exactly 11 points.
FontStretch | Describes the degree to which a font form is stretched from its normal aspect ratio, which is the original width to height ratio specified for the glyphs in the font. | The default value is Normal.
FontStyle | Specifies whether the font style is normal or italic. | The default value is Normal.
FontWeight | Describes the relative weight of a font, in terms of the lightness or heaviness of the strokes. | The default value is Normal.

The following XAML example shows how to define a TextBlock element and set all of the above font attributes.

XAML
<TextBlock
  Text="Font Attributes"
  FontFamily="Verdana"
  FontSize="36"
  FontStretch="UltraExpanded"
  FontStyle="Italic"
  FontWeight="ExtraBlack" />

The following illustration displays the result of the previous XAML content example.

TextBlock rendering with defined font property values
Defining font properties for TextBlock

Note The property values that are set for font attributes may not be the ones used during rendering because of font fallback.

Supported Fonts

The following illustration shows the nine fonts that are supported by Silverlight text elements.

Supported fonts for text elements
Supported fonts for text elements

The SetFontSource method can be used to add downloaded font content to the existing collection of typefaces for Silverlight text elements. The downloaded content can either be an individual font file or packaged content, such as a .zip file, which contains one or more font files. For more information, see Using SetFontSource for Downloaded Fonts.

Using the Run and LineBreak Objects

The Run object is a text element that represents a discrete section of formatted or unformatted text. The LineBreak object represents an explicit new line in a TextBlock. The following XAML example shows how to define several differently formatted text strings within a TextBlock by using Run objects.

XAML
<!-- Display formatted text as Run objects within a TextBlock. -->
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007">

<TextBlock
  FontFamily="Arial" Width="400" Text="Sample text formatting runs">
  <LineBreak/>
  <Run Foreground="Maroon" FontFamily="Courier New" FontSize="24">Courier New 24</Run>
  <LineBreak/>
  <Run Foreground="Teal" FontFamily="Times New Roman" FontSize="18" FontStyle="Italic">Times New Roman Italic 18</Run>
  <LineBreak/>
  <Run Foreground="SteelBlue" FontFamily="Verdana" FontSize="14" FontWeight="Bold">Verdana Bold 14</Run>
</TextBlock>

</Canvas>

The following illustration shows the rendered formatted text from the previous XAML content example.

TextBlock rendering multiple Run objects
Multiple Run objects

Notice that the LineBreak object forces the text in each Run to display on a separate line. Without the LineBreak object, the text in each Run would flow together as one line and would eventually be truncated after exceeding the TextBlock object's Width value. The following illustraton shows how the formatted text would render without using LineBreak objects.

TextBlock rendering multiple Run objects without LineBreak objects
Multiple Run objects without LineBreaks

Formatting Text

In addition to selecting font attributes for text elements, you can format text by using text-specific properties such as Foreground, TextWrapping, and TextDecorations.

Using the Foreground Property

The Foreground property enables you to specify a Brush for the rendered text. A Brush can represent a solid color, a linear or radial gradient, or an image. The following XAML example shows how to set the Foreground property to a solid color and a linear gradient. Notice that the Foreground property can also be used in a Run object to display a different color than the TextBlock object's Foreground property value.

XAML
<!-- TextBlock with a single brush applied to the text. -->
<TextBlock
  FontSize="32"
  FontWeight="Bold"
  Foreground="Maroon">
  Maroon
</TextBlock>

<!-- TextBlock with three brushes applied to the text. -->
<TextBlock
  Canvas.Top="60"
  FontFamily="Arial"
  FontSize="32"
  FontWeight="Bold"
  Foreground="Navy">
  Navy
  <Run Text="DodgerBlue " Foreground="DodgerBlue"/>
  <Run Text="LightSteelBlue " Foreground="LightSteelBlue"/>
</TextBlock>

<!-- TextBlock with a linear gradient brush applied to the text. -->
<TextBlock
  Canvas.Top="100"
  FontFamily="Verdana"
  FontSize="32"
  FontWeight="Bold">
  LINEAR GRADIENT BRUSH
  <TextBlock.Foreground>
    <LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
      <GradientStop Color="Red" Offset="0.0" />
      <GradientStop Color="Orange" Offset="0.2" />
      <GradientStop Color="Yellow" Offset="0.4" />
      <GradientStop Color="Green" Offset="0.6" />
      <GradientStop Color="Blue" Offset="0.8" />
      <GradientStop Color="Violet" Offset="1.0" />
    </LinearGradientBrush>
  </TextBlock.Foreground>
  <TextBlock.RenderTransform>
    <ScaleTransform ScaleY="3.0" />
  </TextBlock.RenderTransform>
</TextBlock>

The following illustration shows the rendered text from the previous XAML example. Notice the effect of applying a ScaleTransform to the last line of rendered text. For more information about applying a RenderTransform to a TextBlock, see Applying Transforms to Text.

TextBlocks rendering solid color and linear gradient brushes
Solid color and linear gradient brushes

The Foreground property of the TextBlock can also specify an ImageBrush. The following XAML example shows how to set the Foreground property of an ImageBrush whose image is used as the fill for the TextBlock's rendered text.

XAML
<!-- TextBlock with an image brush applied to the text. -->
<TextBlock
  Canvas.Top="120"
  FontFamily="Verdana"
  FontSize="72"
  FontStyle="Italic"
  FontWeight="Bold">
  SHRUBBERY
  <TextBlock.Foreground>
    <ImageBrush ImageSource="forest.jpg"/>
  </TextBlock.Foreground>
</TextBlock>

The following illustration shows the rendered text from the previous XAML example.

TextBlock rendering an image brush
TextBlock rendering an image brush

Wrapping Text

The TextWrapping property indicates how text should wrap in a TextBlock. The TextWrapping enumeration defines the values listed in the following table.

Value | Description
NoWrap | No line wrapping is performed.
Wrap | Line breaking occurs if the line overflows beyond the available block width, even if the standard line-breaking algorithm cannot determine any line-break opportunity, as in the case of a very long word that is constrained in a fixed-width container with no scrolling allowed.

The following XAML example shows how to set the TextWrapping property to NoWrap and Wrap.

XAML
<!-- TextBlock with no text wrapping -->
<TextBlock
  Text="The quick red fox jumped over the lazy brown dog."
  Width="200"
  TextWrapping="NoWrap" />

<!-- TextBlock with text wrapping -->
<TextBlock
  Canvas.Top="40"
  Text="The quick red fox jumped over the lazy brown dog."
  Width="200"
  TextWrapping="Wrap" />

The following illustration shows the rendered text from the previous XAML example.

TextBlock rendering non-wrapped and wrapped text
TextBlock rendering non-wrapped and wrapped text

ActualHeight and ActualWidth are read-only properties that specify the rendered height and width of the TextBlock. These properties can be different from the Height and Width properties of the TextBlock. Setting the TextWrapping property affects the ActualHeight and ActualWidth values of the TextBlock. The following illustration shows how the TextWrapping property affects ActualHeight and ActualWidth.

How TextWrapping affects ActualWidth and ActualHeight
How TextWrapping affects ActualWidth and ActualHeight

Using Text Decorations

By using the TextDecorations property, you can create the visual appearance of a hyperlink in a Run or TextBlock object.

Simulating a hyperlink by using the TextDecorations property
Simulating a hyperlink

The following XAML example shows how to define a TextBlock that simulates a hyperlink by displaying an underline in response to the MouseEnter event. The underline is removed in response to the MouseLeave event. Notice that the Cursor property is set to display the Hand cursor when the mouse pointer is over the TextBlock.

XAML
<TextBlock
  Text="Click to Win!"
  TextDecorations="None"
  Cursor="Hand"
  FontSize="14" FontWeight="Bold"
  MouseEnter="onMouseEnter"
  MouseLeave="onMouseLeave"
  MouseLeftButtonUp="onMouseLeftButtonUp" />

The following JavaScript example shows the corresponding event-handling functions for the TextBlock defined in the previous XAML example.

JavaScript
function onMouseEnter(sender, mouseEventArgs)
{
    sender.textDecorations = "Underline";
    sender.foreground="Maroon";
}

function onMouseLeave(sender, mouseEventArgs)
{
    sender.textDecorations = "None";
    sender.foreground="Black";
}

function onMouseLeftButtonUp(sender, mouseEventArgs)
{
    alert("Congratulations!");
}

Applying Transforms to Text

Transforms can alter the display of text in your application. The following examples use different types of rendering transforms to affect the display of text in a TextBlock.

Using a RotateTransform

The following illustration shows text that is rotated 90 degrees by using a RotateTransform.

TextBlock that uses a RotateTransform
TextBlock with RotateTransform

The following code example uses a RotateTransform to rotate text. An Angle value of 90 rotates the element 90 degrees clockwise.

XAML
<!-- Rotate the text 90 degrees using a RotateTransform. -->
<TextBlock Text="Rotated Text" FontSize="32" Foreground="Teal">
  <TextBlock.RenderTransform>
    <RotateTransform Angle="90" />
  </TextBlock.RenderTransform>
</TextBlock>

Using a ScaleTransform

The following example shows the second line of text scaled by 150% along the x-axis, and the third line of text scaled by 150% along the y-axis.

TextBlock that uses a ScaleTransform
TextBlock with ScaleTransform

The following XAML example uses a ScaleTransform to scale text from its original size.

XAML
<TextBlock
  FontFamily="Verdana"
  FontSize="32"
  FontWeight="Bold"
  Foreground="SteelBlue"
  Text="Scaled Text" />

<!-- Scale the text width using a ScaleTransform. -->
<TextBlock
  Canvas.Top="40"
  FontFamily="Verdana"
  FontSize="32"
  FontWeight="Bold"
  Foreground="SteelBlue"
  Text="Scaled Text">
  <TextBlock.RenderTransform>
    <ScaleTransform ScaleX="1.5" ScaleY="1.0" />
  </TextBlock.RenderTransform>
</TextBlock>

<!-- Scale the text height using a ScaleTransform. -->
<TextBlock
  Canvas.Top="80"
  FontFamily="Verdana"
  FontSize="32"
  FontWeight="Bold"
  Foreground="SteelBlue"
  Text="Scaled Text">
  <TextBlock.RenderTransform>
    <ScaleTransform ScaleX="1.0" ScaleY="1.5" />
  </TextBlock.RenderTransform>
</TextBlock>

Note Scaling text is not the same as increasing the font size of text. Font sizes are calculated independently to provide the best resolution at different sizes. Scaled text, on the other hand, preserves the proportions of the original sized text

Using a SkewTransform

The following example shows text skewed along the x-axis.

TextBlock that uses a SkewTransform
TextBlock with SkewTransform

The following code example uses a SkewTransform to skew text. A skew, also known as a shear, is a transformation that stretches the coordinate space in a non-uniform manner. In this example, the two text strings are skewed -30 degrees and 30 degrees along the x-coordinate.

XAML
<!-- Skew the text using a SkewTransform. -->
<TextBlock
  FontSize="32"
  FontWeight="Bold"
  Foreground="Maroon"
  Text="Skewed Text">
  <TextBlock.RenderTransform>
    <SkewTransform AngleX="-30" AngleY="0" />
  </TextBlock.RenderTransform>
</TextBlock>

<TextBlock
  Canvas.Top="60"
  FontSize="32"
  FontWeight="Bold"
  Foreground="Maroon"
  Text="Skewed Text">
  <TextBlock.RenderTransform>
    <SkewTransform AngleX="30" AngleY="0" />
  </TextBlock.RenderTransform>
</TextBlock>

Using a TranslateTransform

The following example shows text translated, or moved, along the x- and y-axis.

TextBlock that uses a TranslateTransform
TextBlock with TranslateTransform

The following code example uses a TranslateTransform to offset text. In this example, a slightly offset copy of text below the primary text creates a shadow effect.

XAML
<!-- Offset the text using a TranslateTransform. -->
<TextBlock
  FontFamily="Verdana"
  FontSize="32"
  FontWeight="Bold"
  Foreground="Black"
  Text="Translated Text">
  <TextBlock.RenderTransform>
    <TranslateTransform X="2" Y="2" />
  </TextBlock.RenderTransform>
</TextBlock>

<TextBlock
  FontFamily="Verdana"
  FontSize="32"
  FontWeight="Bold"
  Foreground="Coral"
  Text="Translated Text"/>

Using SetFontSource for Downloaded Fonts

The SetFontSource method can be used to add downloaded font content to the existing collection of typefaces for a TextBlock object. The downloader parameter identifies the Downloader object that represents the downloaded content. The downloaded content can either be an individual font file or packaged content, such as a .zip file, which contains one or more font files.

Note Font files used with the SetFontSource method must be OpenType or TrueType fonts.

Note As with most types of software, font files are licensed, rather than sold, and licenses that govern the use of fonts vary from vendor to vendor. As a developer it is your responsibility to ensure that you have the required license rights for any font you embed within a document or application, or otherwise redistribute.

The following JavaScript example shows how to use the Downloader object to download an individual font file.

JavaScript
// Event handler for initializing and executing a font file download request.
function onMouseLeftButtonUp(sender, eventArgs)
{
    // Retrieve a reference to the plug-in.
    var plugin = sender.getHost();

    // Create a Downloader object.
    var downloader = plugin.createObject("downloader");

    // Add Completed event.
    downloader.addEventListener("Completed", onCompleted);

    // Initialize the Downloader request.
    downloader.open("GET", "SHOWG.TTF");

    // Execute the Downloader request.
    // NOTE: downloader APIs disallow file:\\ scheme
    // you must run this sample over localhost: or off a server or the following call will fail
    downloader.send();
}

When the font file has been downloaded, it needs to be added to the TextBlock object's collection of typefaces. When it has been added to the collection, it can be selected by using the FontFamily property. The following JavaScript example shows how to use the SetFontSource method to add the the font file to the typeface collection, and then set the FontFamily property to display the TextBlock with the downloaded font.

JavaScript
// Event handler for the Completed event.
function onCompleted(sender, eventArgs)
{
    // Retrieve the TextBlock object.
    var myTextBlock = sender.findName("myTextBlock");

    // Add the font files in the downloaded object to the TextBlock's type face collection.
    myTextBlock.setFontSource(sender);

    // Set the FontFamily property to the friendly name of the font.
    myTextBlock.fontFamily = "Showcard Gothic";

    myTextBlock.text = "Showcard Gothic";
}

You can also download font files that are contained in a packaged format such as a .zip file. The .zip file can contain other content files, such as image files.

Zip file packages can contain font image files
Zip file packages with font files

The following JavaScript example shows how to use the Downloader object to download a .zip file that contains an image file and multiple font files.

JavaScript
// Initialize the Downloader request. Zip file contains: Coco.png, Britanic.ttf, Erasbd.ttf, Showg.ttf
downloader.open("GET", "myMediaAssets.zip");

When the .zip file has been downloaded, the font files it contains must be added to the TextBlock object's collection of typefaces. When the font files have been added to the collection, they can be selected by using the FontFamily property. The following JavaScript example shows how to use the SetSource and SetFontSource methods to use the downloaded content.

JavaScript
// Event handler for the Completed event.
function onCompleted(sender, eventArgs)
{
    // Retrieve the Image object.
    var myImage = sender.findName("myImage");

    // Set the Source property of the Image object to the specific image
    // within the downloaded Zip package file.
    myImage.setSource(sender, "Coco.png");

    // Retrieve the TextBlock object.
    var myTextBlock = sender.findName("myTextBlock");

    // Add the font files in the downloaded package object to the TextBlock's type face collection.
    myTextBlock.setFontSource(sender);

    // Set the FontFamily property to the friendly name of the font.
    myTextBlock.fontFamily = "Showcard Gothic";
}

To return to the default font that is used to display the TextBlock, set the downloader parameter of the SetFontSource method to null. The following JavaScript example shows how to use the SetFontSource method with a null parameter value.

JavaScript
// Retrieve the TextBlock object.
var myTextBlock = sender.findName("myTextBlock");

// Remove the custom font setting.
myTextBlock.setFontSource(null);

If you want to package fonts in .zip files, you should initiate the downloader in such a way that the same downloader instance is used to provide the fonts, and that instance is retained. This is in contrast to the performance advice generally given for the downloader, which suggests that you null out the downloader after each completed download. Here, however, you want the downloader to persist, because the downloader will retain the last download and provide some degree of caching for fonts. This practice can provide a noticeable benefit for large font files or large numbers of SetFontSource calls.

Animating Text

The value of many text properties can be animated including the text size, position, and color (see Animation Overview for more information).

Performance Tip Animating the size of text can potentially use a lot of system resources. This is because when Silverlight renders any text, Silverlight uses "hinting" to smooth each text glyph. If you animate the text size (via a Transform or FontSize), then Silverlight will hint the glyphs for each frame, which is costly and could cause frame dropping. If your application requires dynamic scale changes of large text, it may be better to use vector graphics to represent the text.

See Also

LineBreak
Run
TextBlock
Overviews


Resizing a Silverlight Plug-In

Microsoft Silverlight provides a set of properties to retrieve the actual size of a Silverlight plug-in. It also provides an event that is raised whenever the plug-in is resized.

This topic contains the following sections:

  • Setting the Size of a Silverlight Plug-in
  • Getting the Actual Size of a Silverlight Plug-in
  • Using the OnResize Event
  • Differences Between the OnResize and OnFullScreenChange Events

Setting the Size of a Silverlight Plug-in

When you define a Silverlight plug-in, you specify the width and height of the rectangular region that contains the plug-in's content. You can define the width and height of a Silverlight plug-in by specifying the values in the CreateSilverlight.js and Silverlight.js helper files.

The default unit of measurement for width and height is pixels. This means that a width value of "300" displays a Silverlight plug-in that has a width of 300 pixels.

You can also specify the width or height of a Silverlight plug-in as a percentage of the displayable area of the tag, for example, 75%. The percentage value is relative to the current size of the browser window. If you resize the browser window width, you will also resize any plug-in whose width or height is specified as a percentage value. The following JavaScript example shows the Silverlight plug-in defined in the CreateSilverlight.js file as a percentage value for both width and height.

JavaScript
function createSilverlightEx()
{
    Silverlight.createObjectEx({
        source: 'xamlContent',          // Source property value.
        parentElement:parentElement,    // DOM reference to hosting DIV tag.
        id:'myPlugin',                  // Unique plug-in ID value.
        properties:{                    // Plug-in properties.
            width:'75%',                // Width of rectangular region of plug-in in pixels.
            height:'75%',               // Height of rectangular region of plug-in in pixels.
            background:'oldlace',       // Background color of plug-in.
            version:'1.0'},             // Plug-in version.
        events:{
            onLoad:null}});             // OnLoad property value -- event-handler function name.
}

When you resize the browser window, the Silverlight plug-in, as defined in the preceding code, is automatically resized so that its width and height are still 75% of the displayable area of the tag. Notice, however, that the Ellipse object retains its original size; Silverlight does not support automatic layout of content. This means that applications have to provide logic to resize or scale themselves appropriately when the size of the Silverlight plug-in changes.

Silverlight plug-in with width and height properties set to 75%

Plug-in with width and height properties set to 75%

The width and height properties of the Silverlight plug-in are inherited by the plug-in from the HTML DOM, so you can set these properties at run time. The following JavaScript example shows how to set the Silverlight plug-in size at run time.

JavaScript
// Set the plug-in to a new size.
function setNewSize(newWidth, newHeight)
{
    // Retrieve a reference to the plug-in via the DOM.
    var slPlugin = document.getElementById("slPlugin");
    alert(slPlugin);
    // Set the new size values;
    slPlugin.width = newWidth;
    slPlugin.height = newHeight;

    // Perform layout tasks for plug-in content.
}

Note To retrieve the plug-in's DOM properties, such as width and height, use the GetElementById method to return a reference to a DOM-accessible object. The GetHost method does not return an object from which DOM values can be retrieved.

Getting the Actual Size of a Silverlight Plug-in

The width and height properties of the Silverlight plug-in that are defined in the OBJECT and EMBED tags do not always reflect the true pixel size of the plug-in. For example, in cases where the width is defined as 75%, the actual width in pixels is unknown. However, the Silverlight plug-in provides two properties, ActualWidth and ActualHeight, that enable you to retrieve values that are always specified as pixel values.

The following JavaScript example shows how to use the ActualWidth and ActualHeight properties. If width is defined as a percentage value, the ActualWidth value represents a width value in pixels.

JavaScript
function onResizeStatus(sender, eventArgs)
{
    // Concatenate the size values as a formatted message string.
    var msgString  = " actualWidth: " + slPlugin.content.actualWidth;
        msgString += " actualHeight: " + slPlugin.content.actualHeight;

    // Display an alert dialog box with a formatted message string.
    var textBlock = sender.findName("Status");
    textBlock.text = msgString;
}

The following illustration shows the results of invoking the OnResize event-handler function that is defined in the preceding code sample. In this case, the plug-in's width and height are set to 100% and remain at 100% regardless of the size of the browser window. However, the ActualWidth and ActualHeight properties display the Silverlight plug-in size values as pixel values.

Displaying size properties on the OnResize event
Displaying size properties on OnResize event

Using the OnResize Event

The OnResize event occurs whenever the Silverlight plug-in changes its ActualHeight or ActualWidth property in embedded mode. In embedded mode, the plug-in displays within the Web browser. In full-screen mode, the plug-in displays on top of all other applications.

The following JavaScript example shows how to define a OnResize event for a Silverlight plug-in.

JavaScript
var plugin;

function onLoaded(sender, args)
{
    // Retrieve a reference to the plug-in.
    var slPlugin = sender.getHost();
    // Set the event handler function to the OnResize event.
    slPlugin.content.onResize = onResized;

    // Do initial layout of the app based on initial size.
    updateLayout(slPlugin.content.actualWidth, slPlugin.content.actualHeight);
}

function onResized(sender, eventArgs)
{
    // Do layout resizing of the app whenever the plug-in actualwidth or actualheight changes.
    updateLayout(slPlugin.content.actualWidth, slPlugin.content.actualHeight);
}

// Resize and reposition application elements.
function updateLayout(width, height)
{
    // Perform layout tasks based on width and height.
}

Note Silverlight does not support automatic layout of user interface elements. This means that applications have to provide logic to resize themselves appropriately when the size of the Silverlight plug-in changes.

Note Use OnResize to make sizing decisions rather than OnLoad. This is because the ActualHeight/ActualWidth values of the Silverlight plug-in are not guaranteed to be set at the time the OnLoad event fires. OnResize fires whenever the ActualHeight or ActualWidth properties change including when the plug-in first loads.

Performance Characteristics During a Size Change

Resizing a browser window has minimal effect on performance for Silverlight plug-ins that are contained within the browser page. This means, in most cases, that playback of audio or video content is seamless.

Differences Between the OnResize and OnFullScreenChange Events

The OnFullScreenChange event occurs whenever the FullScreen property of the Silverlight plug-in changes. When the FullScreen property is set to false, the Silverlight plug-in displays in embedded mode, that is, the plug-in is contained within the browser window. When the FullScreen property is set to true, the Silverlight plug-in displays in full-screen mode, that is, the plug-in resizes to the current resolution of the display and overlays all other applications, including the browser. The following illustrations show the differences between embedded mode and full-screen mode.

Silverlight plug-in displaying in embedded and full-screen mode
Embedded and full-screen mode

If a change in the Silverlight plug-in size triggers the OnFullScreenChange event, the OnResize event does not occur. In addition, the OnResize event does not occur when the Silverlight plug-in is in full-screen mode. The OnResize and OnFullScreenChange events are discrete events that are independent of each other, and never occur at the same time.

See Also

ActualHeight
ActualWidth
OnFullScreenChange
OnResize
Using Silverlight Plug-ins
Overviews


Silverlight Full Screen Support

Silverlight SDK

Silverlight Full-Screen Support

Microsoft Silverlight provides functionality for displaying the Silverlight plug-in in full-screen mode.

This topic contains the following sections:

  • Embedded Mode and Full-Screen Mode
  • Setting Full-Screen Mode
  • Returning to Embedded Mode
  • Using the OnFullScreenChange Event
  • Differences Between the OnResize and OnFullScreenChange Events

Embedded Mode and Full-Screen Mode

The Silverlight plug-in can display in either embedded mode or in full-screen mode:

  • In embedded mode, the plug-in displays within the Web browser.
  • In full-screen mode, the plug-in displays on top of all other applications.

When the Silverlight plug-in displays in embedded mode, the plug-in is contained within the browser window. When the Silverlight plug-in displays in full-screen mode, the plug-in resizes to the current resolution of the display and overlays all other applications, including the browser. The following illustrations show the differences between embedded mode and full-screen mode.

Silverlight plug-in displaying in embedded and full-screen mode
Embedded mode and full-screen mode

The Size of the Plug-in in Full-Screen Mode

When a Silverlight plug-in is displayed in full-screen mode, the plug-in's size is equal to the current resolution of the display. However, the values of the width and height properties of the plug-in are not affected during the switch to full-screen mode. To determine the true size of the plug-in in full-screen mode, use the ActualWidth and ActualHeight properties. These properties are set to the current resolution of the display.

When a Silverlight plug-in in full-screen mode switches back to embedded mode, the plug-in size reverts to the values of the width and height properties.

Setting Full-Screen Mode

The FullScreen property determines whether the Silverlight plug-in displays as a full-screen plug-in or as an embedded plug-in. If the FullScreen property is set to true, the Silverlight plug-in displays as a full-screen plug-in. If FullScreen is set to false, the Silverlight plug-in displays as an embedded plug-in. In cases where a page contains multiple Silverlight plug-ins, only one Silverlight plug-in can be in full-screen mode at one time.

When a Silverlight plug-in is displayed in full-screen mode, the following message appears briefly. This message alerts the user that the application is now in full-screen mode, and provides information about how to return to embedded mode.

Full-screen mode message

Full-screen mode message

A Silverlight plug-in can enable full-screen mode only in response to a set of user-initiated actions. These actions correspond to the MouseLeftButtonDown, MouseLeftButtonUp, KeyDown, and KeyUp events. If you try to set the FullScreen property to true in a Loaded event, the property setting is ignored. Limiting the actions that enable full-screen mode ensures that the user is always the initiator of full-screen mode behavior.

When a Silverlight plug-in is displayed in full-screen mode, keyboard events are prevented from being passed to keyboard event handlers in the application. The only valid keyboard input that is acted upon is the set of keystrokes that return the Silverlight plug-in to embedded mode. This limitation of keyboard input during full-screen mode is a security feature, and is intended to minimize the possibility of unintended information being entered by a user.

The following JavaScript example shows how to enable and disable full-screen mode for a Silverlight plug-in by using a MouseLeftButtonUp event-handling function.

JavaScript
// Event handler for clicking the full-screen mode button.
function onMouseLeftButtonUp(sender, eventArgs)
{
    // Toggle between embedded mode and full-screen mode.
    plugin.content.fullScreen = !plugin.content.fullScreen;
}

When the Silverlight plug-in is in full-screen mode, the ActualWidth and ActualHeight properties are set to the current resolution of the display.

Performance Characteristics During a Mode Change

Switching between embedded and full-screen modes has minimal effect on performance for content that is contained within the Silverlight plug-in. This means, in most cases, that playback of audio or video content is seamless.

Performance Note: For best performance, when your application goes into full screen, hide or disconnect from the tree all objects not being rendered in full screen mode. You can hide an object by setting its Visibility property to Collapsed.

Full-Screen Windowless Silverlight Plug-Ins

A Silverlight plug-in whose Windowless property is set to true always draws its background color at full opacity when displayed in full-screen mode. However, when the Silverlight plug-in returns to embedded mode, the background color reverts to its previous opacity value.

Returning to Embedded Mode

A Silverlight plug-in that is in full-screen mode can return to embedded mode in several ways. The simplest way to leave full-screen mode is for the user to enter a keystroke or keystroke combination:

  • Windows users should press ESC, CTRL+W, or ALT+F4.
  • Macintosh users should press ESC.

In addition, if a Silverlight plug-in that is in full-screen mode loses focus, it returns to embedded mode. A Silverlight plug-in in full-screen mode can lose focus in a multimonitor configuration when another window gains focus through a user action. For example, switching between tasks in Windows by using the ALT+TAB key combination causes the current application to lose focus and the next application to gain focus.

Setting the FullScreen Property to False

When a Silverlight plug-in is displayed in full-screen mode, setting the FullScreen property to false returns the plug-in to embedded mode. When a Silverlight plug-in switches back to embedded mode from full-screen mode, the plug-in size reverts to the values of the width and height properties.

Using the OnFullScreenChange Event

The OnFullScreenChange event occurs whenever the FullScreen property changes. The following JavaScript example shows how to define a OnFullScreenChange event for a Silverlight plug-in.

JavaScript
var plugin;

function onLoaded(sender, args)
{
    // Retrieve a reference to the plug-in.
    plugin = sender.getHost();

    // Set the event handler function for the OnFullScreenChange event.
    plugin.content.onFullScreenChange = onFullScreenChanged;

    // Do initial layout of the app based on initial size.
    updateLayout(plugin.content.actualWidth, plugin.content.actualHeight);
}

function onFullScreenChanged(sender, eventArgs)
{
    // Do layout resizing of the app whenever the FullScreen property changes.
    updateLayout(plugin.content.actualWidth, plugin.content.actualHeight);
}

// Resize and reposition application elements.
function updateLayout(width, height)
{
    // Perform layout tasks based on width and height.
}

Note Silverlight does not support automatic layout of elements. This means that applications have to provide logic to resize themselves appropriately when the plug-in size changes.

Differences Between the OnResize and OnFullScreenChange Events

The OnFullScreenChange event occurs whenever the FullScreen property of the Silverlight plug-in changes. When the FullScreen property is set to true, the Silverlight plug-in displays in full-screen mode. When the FullScreen property is set to false, the Silverlight plug-in displays in embedded mode.

If a change in the Silverlight plug-in size triggers the OnFullScreenChange event, the OnResize event does not occur. In addition, the OnResize event does not occur when the Silverlight plug-in is in full-screen mode. The OnResize and OnFullScreenChange events are discrete events that are independent of each other, and never occur at the same time.

See Also

ActualHeight
ActualWidth
OnFullScreenChange
OnResize
Using Silverlight Plug-ins
Overviews


Using a Downloader Object

Microsoft Silverlight provides a Downloader object, which represents a set of download functionality for a Silverlight plug-in.

This topic contains the following sections:

  • Role of the Downloader Object
  • Creating and Initializing a Downloader Object
  • Defining Downloader Event Handlers
  • Retrieving Downloaded Content
  • Using SetFontSource for Downloaded Fonts
  • Handling Downloader Errors
  • URI Protocols and Schemes

Role of the Downloader Object

The Downloader object is a special-purpose Silverlight object that provides the ability to download application data, such as XAML content, JavaScript content, or media assets such as images. The Downloader object lets you download content on demand in response to application needs, instead of having to provide all application content when the Silverlight plug-in is instantiated. More importantly, you can render downloaded content without having to refresh the entire Web page. The Downloader object provides functionality for initiating the data transfer, monitoring the progress of the data transfer, and retrieving the downloaded content.

The properties and methods of the Downloader object are modeled after the XMLHttpRequest (XHR) set of APIs. XMLHttpRequest gives JavaScript and other Web browser scripting languages the ability to transfer XML data to and from a Web server by using HTTP, and to manipulate the data.

Download Packages

Silverlight provides the ability to download content as a package, which is a collection of independent files that contain XAML content, media assets, and other application data. The .zip file format is supported as a download package. The following illustration shows a collection of application content that is contained within a .zip download package.

Download package containing a collection of application files

Download package containing application files

When the package is successfully downloaded, you can use methods such as GetResponseText, SetSource (Image), SetSource (MediaElement), and CreateFromXamlDownloader to selectively retrieve a specific named part of the package. In this case, a part reference is the file name of the individual content within the package, such as "rotation01_green.png".

Retrieving a part from a download package
Retrieving a part from a download package

Creating and Initializing a Downloader Object

To create a Downloader object, use the CreateObject method of the Silverlight plug-in. Do not invoke the CreateObject method until the Silverlight plug-in has been instantiated. The following JavaScript example shows how to invoke the CreateObject method to create a Downloader object.

JavaScript
// Event handler for initializing and executing a download request.
function onMouseLeftButtonUp(sender, eventArgs)
{
    // Retrieve a reference to the plug-in.
    var slPlugin = sender.getHost();

    // Create a Downloader object.
    var downloader = slPlugin.createObject("downloader");
}

The next step involves setting event-handler functions to two Downloader events, DownloadProgressChanged and Completed. The DownloadProgressChanged event, which is optional, enables you to monitor the progress of the download. One way of responding to this event is to provide visual feedback, such as a progress bar indicator.

The Completed event enables you to determine the state of the download request. The following JavaScript example shows how to add DownloadProgressChanged and Completed events to a Downloader object.

JavaScript
// Event handler for initializing and executing a download request.
function onMouseLeftButtonUp(sender, eventArgs)
{
    // Retrieve a reference to the plug-in.
    var slPlugin = sender.getHost();

    // Create a Downloader object.
    var downloader = slPlugin.createObject("downloader");

    // Add DownloadProgressChanged and Completed events.
    downloader.addEventListener("downloadProgressChanged", onDownloadProgressChanged);
    downloader.addEventListener("completed", onCompleted);
}

The next step involves initializing the download request by using the Open method, and executing the download request by using the Send method. The Open method initializes the Downloader object by specifying the action to perform and the content to perform the action on. The following JavaScript example shows the completed sequence of how to create, initialize, and execute a download request:

JavaScript
// Event handler for initializing and executing a download request.
function onMouseLeftButtonUp(sender, eventArgs)
{
    // Retrieve a reference to the plug-in.
    var slPlugin = sender.getHost();

    // Create a Downloader object.
    var downloader = slPlugin.createObject("downloader");

    // Add DownloadProgressChanged and Completed events.
    downloader.addEventListener("downloadProgressChanged", onDownloadProgressChanged);
    downloader.addEventListener("completed", onCompleted);

    // Initialize the Downloader request.
    // NOTE: downloader APIs disallow file:\\ scheme
    // you must run this sample over localhost: or off a server or the following call will fail

    downloader.open("GET", "promo.png");

    // Execute the Downloader request.
    downloader.send();
}

Defining Downloader Event Handlers

The following table shows the events provided by the Downloader object.

Event | Description
Completed | Occurs when the download request has completed and returned content.
DownloadFailed | Occurs when the download request has failed to return content.
DownloadProgressChanged | Occurs while content is being downloaded during a download request.

Defining a DownloadProgressChanged Event

The DownloadProgressChanged event is often used with a visual progress indicator, which displays the percentage of content that has been downloaded. A visual progress indicator can be a simple set of XAML content, such as Rectangle and TextBlock objects, as shown in the following example.

XAML
<!-- Visual progress indicator -->
<Canvas Canvas.Top="70">
  <Rectangle
    x:Name="progressRectangle"
    Canvas.Left="20"
    Height="10" Width="0"
    Fill="Maroon" />
  <Rectangle
    Canvas.Top ="-1"
    Canvas.Left="19" Height="12"
    Width="202"
    StrokeThickness="1" Stroke="Black" />
  <TextBlock
    x:Name="progressText"
    Canvas.Top ="-4" Canvas.Left="230"
    Text="0%" FontSize="12" />
</Canvas>

The following JavaScript example shows how to define a DownloadProgressChanged event-handler function that updates the visual progress indicator shown in the preceding XAML.

JavaScript
// Event handler for updating visual progress indicator
function onDownloadProgressChanged(sender, eventArgs)
{
    // Calculate the downloaded percentage.
    var percentage = Math.floor(sender.downloadProgress * 100);

    // Update the Rectangle and TextBlock objects of the visual progress indicator.
    progressText.text = percentage + "%";
    progressRectangle.width = percentage * 2;
}

The following illustration shows the visual progress indicator at the starting, middle, and ending position of the download.

Visual progress indicator
Visual progress indicator

A visual progress indicator can be constructed from a wide variety of XAML content, including animated objects.

Defining a Completed Event

The Completed event occurs when the download request has completed and returned content. The following JavaScript example shows how to define a Completed event-handler function that accesses the downloaded content.

JavaScript
// Event handler for the Completed event.
function onCompleted(sender, eventArgs)
{
    // Retrieve downloaded XAML content.
    var xamlFragment = sender.ResponseText;

    // Create the objects from the XAML content.
    var plugin = sender.getHost();
    var button = plugin.content.createFromXaml(xamlFragment);

    // Add downloaded XAML content to the root Canvas of the plug-in.
    var rootCanvas = sender.findName("rootCanvas");
    rootCanvas.children.add(button);
}

Retrieving Downloaded Content

When a Downloader object request is successful, the value from the ResponseText property represents the downloaded content as a string value. The response text can represent a plain string, XAML content, JavaScript content, or a media asset such as an image.

Note If you are downloading media assets for use by the Source property of Image and MediaElement objects, you should use the SetSource (Image) or SetSource (MediaElement) methods. This is a more efficient way to transfer large media assets. ImageBrush also has a SetSource method, and TextBlock has SetFontSource (for collections of fonts).

Using the URI Property to Identify Downloaded Content

When you invoke the Send method of the Downloader object, you specify a uri parameter that represents the data to be downloaded. The URI property corresponds to the value of the uri parameter of the Send method. The URI property enables you to differentiate downloaded content when you use a common DownloadProgressChanged or Completed event-handler function for multiple Downloader object requests.

The following JavaScript example shows how to use the URI property in a Completed event-handler function to determine what actions to take for the returned value of the GetResponseText method invocations. Because the downloaded content does not represent packaged content, the part parameter for GetResponseText must be set to an empty string. Notice that the Status property value is used to determine whether the content was successfully downloaded.

JavaScript
// Event handler for the Completed event.
function onCompleted(sender, eventArgs)
{
    // If HTTP status code indicates "OK", determine action based on URI property.
    if (sender.uri == "OK_button.js")
    {
        // Evaluate JavaScript code -- causes code to be memory-resident.
        eval(sender.ResponseText);
    }

    if (sender.uri == "OK_button.xaml")
    {
        // Retrieve downloaded XAML content.
        var xamlFragment = sender.ResponseText;

        // Create the objects from the XAML content.
        var plugin = sender.getHost();
        var button = plugin.content.createFromXaml(xamlFragment);

        // Add downloaded XAML content to the root Canvas of the plug-in.
        var rootCanvas = sender.findName("rootCanvas");
        rootCanvas.children.add(button);
    }
}

Retrieving Content from Packages

Instead of returning a string that you process as a single entity, the Downloader can also return a package, which is in the form of a .zip file. To retrieve the content, you write a handler for the Completed event. Instead of using the ResponseText property to retrieve contents, you use the GetResponseText method. GetResponseText has a part parameter, which you specify as the name of the part you want to retrieve from within the package.

Using the CreateFromXamlDownloader Method to Create XAML Content

The CreateFromXamlDownloader method creates XAML content dynamically by using the downloaded content in the Downloader object. If successful, the CreateFromXamlDownloader method returns an object reference, which you can then add to the existing Silverlight object hierarchy. You can create a single Silverlight object, such as a TextBlock, or an entire tree of Silverlight objects.

Note The CreateFromXamlDownloader method is an efficient mechanism for creating XAML objects, because it avoids having to copy downloaded content from the GetResponseText method return value to a temporary buffer and then back again for use by the XAML parser.

The following JavaScript example shows how to add XAML content to an existing Canvas object by using the CreateFromXamlDownloader method. Because the downloaded content does not represent packaged content, the part parameter for CreateFromXamlDownloader must be set to an empty string.

JavaScript
// Event handler for the Completed event.
function onCompleted(sender, eventArgs)
{
    // Retrieve a reference to the plug-in.
    var slPlugin = sender.getHost();

    // Retrieve the XAML fragment and create an object reference.
    // In this case, since the downloaded content represents a single file, OK_button.xaml,
    // the part parameter is set to an empty string.
    var xamlFragment = slPlugin.content.createFromXamlDownloader(sender, "");

    // Add the XAML object as a child of the root Canvas object.
    var root = sender.findName("rootCanvas");
    root.children.add(xamlFragment);
}

XAML content that is created by using the CreateFromXamlDownloader method is not rendered until it is added to an object by using the Add method. The following illustration shows the relationship between the Silverlight object hierarchy and the downloaded XAML content before and after the content is added to the object hierarchy.

Silverlight object hierarchy and downloaded XAML content
Silverlight object hierarchy and downloaded XAML content

You can also use the CreateFromXamlDownloader method to retrieve a specific part within the downloaded content package. When the downloaded content package is a .zip file, the CreateFromXamlDownloader method enables you to retrieve the contents of a file name within the .zip file. The following JavaScript example shows how to use the CreateFromXamlDownloader method, using the part parameter to reference a specified part within the downloaded content.

JavaScript
function onDownloadCompleted(sender, eventArgs)
{
    // Retrieve the XAML content from the downloaded package file.
    var jacketBrowserXaml = sender.getResponseText("jacketBrowser.xaml");

    // Create the objects from the XAML content.
    var jacketBrowser = plugin.content.createFromXaml(jacketBrowserXaml);

    // Add downloaded XAML content to the root Canvas of the plug-in.
    sender.findName("root").children.insert(0, jacketBrowser);

    // Retrieve a reference to the Image object representing the jacket.
    var jacketImageSlice = sender.findName("jacketSlice");

    // Set the Source property of the Image object to the specific jacket image
    // within the downloaded Zip package file.
    jacketImageSlice.setSource(sender, "rotation01_green.png");
}

Using the SetSource Method to Set Media Content

The SetSource method can be used as a way of setting downloaded media content to the Source property of the MediaElement object. Equivalent methods also exist on Image and ImageBrush. The first parameter of the SetSource method identifies the Downloader object representing the downloaded content. The second parameter identifies the specific part to retrieve within the downloaded content. If the downloaded content does not represent packaged content, such as a .zip file, the second parameter must be set to an empty string. The following JavaScript example shows how to use the SetSource method to set the Source property of an Image object to the downloaded content.

JavaScript
// Event handler for the Completed event.
function onCompleted(sender, eventArgs)
{
    // Retrieve the Image object.
    var myImage = sender.findName("myImage");

    // Set the Source property to the contents of the downloaded object,
    // In this case, since the downloaded content represents a single image file, promo.png,
    // the part parameter is set to an empty string.
    myImage.setSource(sender, "");
}

You can also use the SetSource method to retrieve a specific part within the downloaded content package. When the downloaded content package is a .zip file, the SetSource method enables you to retrieve the contents of a file name within the .zip file. The following JavaScript example shows how to use the SetSource method to set the Source property of an Image object to a specified part within the downloaded content.

JavaScript
function onDownloadCompleted(sender, eventArgs)
{
    // Retrieve the XAML content from the downloaded package file.
    var jacketBrowserXaml = sender.getResponseText("jacketBrowser.xaml");

    // Create the objects from the XAML content.
    var jacketBrowser = plugin.content.createFromXaml(jacketBrowserXaml);

    // Add downloaded XAML content to the root Canvas of the plug-in.
    sender.findName("root").children.insert(0, jacketBrowser);

    // Retrieve a reference to the Image object representing the jacket.
    var jacketImageSlice = sender.findName("jacketSlice");

    // Set the Source property of the Image object to the specific jacket image
    // within the downloaded Zip package file.
    jacketImageSlice.setSource(sender, "rotation01_green.png");
}

Using SetFontSource for Downloaded Fonts

The SetFontSource method can be used to add downloaded font content to the existing collection of typefaces for a TextBlock object. The downloader parameter identifies the Downloader object that represents the downloaded content. The downloaded content can either be an individual font file or packaged content, such as a .zip file, that contains one or more font files.

Note Font files used with the SetFontSource method must be OpenType or TrueType fonts, and must have a file name extension of .ttf.

The following JavaScript example shows how to use the Downloader object to download an individual font file.

JavaScript
// Event handler for initializing and executing a font file download request.
function onMouseLeftButtonUp(sender, eventArgs)
{
    // Retrieve a reference to the plug-in.
    var plugin = sender.getHost();

    // Create a Downloader object.
    var downloader = plugin.createObject("downloader");

    // Add Completed event.
    downloader.addEventListener("Completed", onCompleted);

    // Initialize the Downloader request.
    downloader.open("GET", "SHOWG.TTF");

    // Execute the Downloader request.
    // NOTE: downloader APIs disallow file:\\ scheme
    // you must run this sample over localhost: or off a server or the following call will fail
    downloader.send();
}

When the font file has been downloaded, it needs to be added to the TextBlock's collection of typefaces. When it has been added to the collection, it can then be selected by using the FontFamily property. The following JavaScript example shows how to use the SetFontSource method to add the the font file to the typeface collection, and then set the FontFamily property to display the TextBlock with the downloaded font.

JavaScript
// Event handler for the Completed event.
function onCompleted(sender, eventArgs)
{
    // Retrieve the TextBlock object.
    var myTextBlock = sender.findName("myTextBlock");

    // Add the font files in the downloaded object to the TextBlock's type face collection.
    myTextBlock.setFontSource(sender);

    // Set the FontFamily property to the friendly name of the font.
    myTextBlock.fontFamily = "Showcard Gothic";

    myTextBlock.text = "Showcard Gothic";
}

You can also download font files contained in a packaged format, such as a .zip file. The .zip file can contain other content files, such as image files.

Contents of a .zip file
Contents of a .zip file

The following JavaScript example shows how to use the Downloader object to download a .zip file that contains an image file and multiple font files.

JavaScript
// Initialize the Downloader request. Zip file contains: Coco.png, Britanic.ttf, Erasbd.ttf, Showg.ttf
downloader.open("GET", "myMediaAssets.zip");

When the .zip file has been downloaded, the font files it contains must be added to the TextBlock's collection of typefaces. Once the font files have been added to the collection, they can then be selected by using the FontFamily property. The following JavaScript example shows how to use the SetSource and SetFontSource methods to use the downloaded content.

JavaScript
// Event handler for the Completed event.
function onCompleted(sender, eventArgs)
{
    // Retrieve the Image object.
    var myImage = sender.findName("myImage");

    // Set the Source property of the Image object to the specific image
    // within the downloaded Zip package file.
    myImage.setSource(sender, "Coco.png");

    // Retrieve the TextBlock object.
    var myTextBlock = sender.findName("myTextBlock");

    // Add the font files in the downloaded package object to the TextBlock's type face collection.
    myTextBlock.setFontSource(sender);

    // Set the FontFamily property to the friendly name of the font.
    myTextBlock.fontFamily = "Showcard Gothic";
}

To return to the default font used to display the TextBlock, set the downloader parameter of the SetFontSource method to null. The following JavaScript example shows how to use the SetFontSource method with a null parameter value.

JavaScript
// Retrieve the TextBlock object.
var myTextBlock = sender.findName("myTextBlock");

// Remove the custom font setting.
myTextBlock.setFontSource(null);

Handling Downloader Errors

There are two mutually exclusive events that report success or failure of a download. These are Completed (success) and DownloadFailed (failure). Typically you write handlers for both events.

The Status and StatusText properties provide the HTTP status code and corresponding text string value that represent the final state of the Downloader object request. Generally speaking, status will always be 200 (success) from the Completed handler and 204 (no content) from the DownloadFailed handler.

Using the Abort Method

The Abort method cancels the download request that has been executed by using the Send method of the Downloader object. In addition, the Abort method resets the following Downloader properties to their initial state.

Property name | Initial state
DownloadProgress | 0
Status | 0
StatusText | Empty string

The following JavaScript example shows how to invoke the Abort method.

JavaScript
// Cancel download on mouse click.
function onLeftMouseButtonUp(sender, eventArgs)
{
    // Cancel Downloader activity and restore state.
    downloader.abort();
}

URI Protocols and Schemes

The URI that you specify for the first parameter of the Open method will generally use relative URIs. The relative URI will then use the same URI scheme that is used to serve the HTML page, which is generally HTTP. The starting location for the relative reference is the HTML page that contains the current Silverlight plug-in. Setting a cross-domain URI for the second parameter of the Open method is not permitted, and such download attempts will fail. In this case, DownloadFailed does not occur. Instead, a method error is thrown on the Send method call.

Because of the cross-domain restrictions on Downloader, if you are setting media or images using URI sources that are cross-domain, do not use the various SetSource methods, because these require a Downloader to process the URI. Instead, set the respective Source properties directly, and specify the URI as a string.

The Downloader does not support downloads through the FILE scheme. This may be an issue if you are testing Silverlight-based applications locally in the file system, instead of developing and then deploying your Web site to a test server or to localhost. The downloader will fail against the FILE scheme at the point when you call the Send method.

You can use HTTPS as the implied protocol for downloads, but only if the HTML page that contains the current Silverlight plug-in is also HTTPS.

Backslashes (\) are not permitted in Downloader URIs; always use forward slashes (/).

See Also

Downloader
CreateFromXamlDownloader
CreateObject
SetFontSource
SetSource (MediaElement)
SetSource (Image)
Overviews


Timer Overview

There is no timer object available in Silverlight 1.0 but you can use a Storyboard for the same purpose. This topic demonstrates how to use Storyboard to make function calls at every frame or at a time interval of your choice.

  • Timer Example Walkthrough
  • Complete Example

Timer Example Walkthrough

Below is a walkthrough of a simple example that demonstrates how to create a timer with a Storyboard.

  1. Create the Storyboard: Create a Storyboard in the resources block of your page. Give the Storyboard a name and a Duration. In this example, the Duration is 0, which will make the timer fire at every frame. You can adjust this duration to any time interval you want.

    XAML
    <Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Canvas.Resources>

    <!-- Timer Storyboard -->
    <Storyboard Duration="0:0:0" x:Name="timerStoryboard" />

  </Canvas.Resources>

</Canvas>

  2. Add Demonstration Code: This example uses a simple animation to demonstrate the timer calls. The following code is added to create a rectangle that constantly fades in and out of view (Opacity is animated). In addition, a TextBlock is added. This TextBlock will be used later to output the current opacity value as that value is animated.

    XAML
    <Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Canvas.Resources>

    <!-- Timer Storyboard -->
    <Storyboard Duration="0:0:0" x:Name="timerStoryboard" />

  </Canvas.Resources>
  <Rectangle
    x:Name="MyAnimatedRectangle"
    Width="100"
    Height="100"
    Fill="Blue"
    Loaded="StartTimer">
    <Rectangle.Triggers>

      <!-- Animates the rectangle's opacity. -->
      <EventTrigger RoutedEvent="Rectangle.Loaded">
        <BeginStoryboard>
          <Storyboard>
            <DoubleAnimation
              Storyboard.TargetName="MyAnimatedRectangle"
              Storyboard.TargetProperty="Opacity"
              From="1.0" To="0" Duration="0:0:5"
              AutoReverse="True" RepeatBehavior="Forever" />
          </Storyboard>
        </BeginStoryboard>
      </EventTrigger>
    </Rectangle.Triggers>
  </Rectangle>

  <!-- This TextBlock is used to output the current opacity value of the Rectangle -->
  <TextBlock Canvas.Top="110" x:Name="myTextBlock" ></TextBlock>
</Canvas>

  3. Start the Timer: Notice in the code above the Loaded event attached to the Rectangle that targets the StartTimer function. This function is used to start the timer at the same time the animation starts (see code below).

    JavaScript
    // This function initially starts the timer. This
// function is called when the rectangle first loads.
function StartTimer(sender, mouseEventArgs)
{
    // Retrieve the timer Storyboard and start it.
    var timer =  sender.findName("timerStoryboard");
    timer.begin();

}

  4. Iterate the Timer: The next task is to call a function when the Storyboard ends, start the Storyboard again, call the function again, etc. This creates an iterating timer. To do this, first attach a Completed event to the Storyboard.

    XAML
    ...
<!-- Timer Storyboard -->
<Storyboard Completed="StoryboardFinished" Duration="0:0:0" x:Name="timerStoryboard" />
...

    Now create the StoryboardFinished function.

    JavaScript
    // This function is called when the Completed event fires on
// the timer Storyboard. It allows you to do something programmatically
// after the Storyboard ends. It then starts the Storyboard again.
// Because the timer Storyboard has a Duration of 0, this function
// gets called at every frame.
function StoryboardFinished(sender, mouseEventArgs)
{

  var rect = sender.findName("MyAnimatedRectangle");
  var txtBlock = sender.findName("myTextBlock");

  // Output the current opacity value of the rectangle to the TextBlock.
  txtBlock.text = String(rect.opacity);

  var timer =  sender.findName("timerStoryboard");

  // Begin the timer Storyboard again. Because the Storyboard begins again
  // immediately after it last finished, this function gets called over
  // and over indefinitely.
  timer.begin();
}

    When you run this sample, you will see the opacity value update at each frame (very rapidly). Again, you can adjust the timing interval by setting a different Duration value on the timing Storyboard.

Complete Example

The following shows the entire sample.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Canvas.Resources>

    <!-- Timer Storyboard -->
    <Storyboard Duration="0:0:0" Completed="StoryboardFinished" x:Name="timerStoryboard" />

  </Canvas.Resources>
  <Rectangle
    x:Name="MyAnimatedRectangle"
    Width="100"
    Height="100"
    Fill="Blue"
    Loaded="StartTimer">
    <Rectangle.Triggers>

      <!-- Animates the rectangle's opacity. -->
      <EventTrigger RoutedEvent="Rectangle.Loaded">
        <BeginStoryboard>
          <Storyboard>
            <DoubleAnimation
              Storyboard.TargetName="MyAnimatedRectangle"
              Storyboard.TargetProperty="Opacity"
              From="1.0" To="0" Duration="0:0:5"
              AutoReverse="True" RepeatBehavior="Forever" />
          </Storyboard>
        </BeginStoryboard>
      </EventTrigger>
    </Rectangle.Triggers>
  </Rectangle>

  <!-- This TextBlock is used to output the current opacity value of the Rectangle -->
  <TextBlock Canvas.Top="110" x:Name="myTextBlock" ></TextBlock>
</Canvas>

JavaScript
// This function initially starts the timer. This
// function is called when the rectangle first loads.
function StartTimer(sender, mouseEventArgs)
{
    // Retrieve the timer Storyboard and start it.
    var timer =  sender.findName("timerStoryboard");
    timer.begin();

}

// This function is called when the Completed event fires on
// the timer Storyboard. It allows you to do something programmatically
// after the Storyboard ends. It then starts the Storyboard again.
// Because the timer Storyboard has a Duration of 0, this function
// gets called at every frame.
function StoryboardFinished(sender, mouseEventArgs)
{

  var rect = sender.findName("MyAnimatedRectangle");
  var txtBlock = sender.findName("myTextBlock");

  // Output into the TextBlock the current opacity value of the rectangle.
  txtBlock.text = String(rect.opacity);

  var timer =  sender.findName("timerStoryboard");

  // Begin the timer Storyboard again. Because the Storyboard begins again
  // immediately after it last finished, this function gets called over
  // and over indefinitely.
  timer.begin();
}

See Also

Animation Overview


Silverlight Application Scripting Error Handling

Silverlight SDK

Error Handling in Silverlight-based Scripting Applications

You can provide error-handling support in your Microsoft Silverlight-based scripting applications in a number of ways, depending on the type of the error. The onError event on the Silverlight plug-in can be used to handle parser errors, run-time errors, and other types of errors. A try/catch block can be placed around a synchronous method call, and errors resulting from the call can be handled in the catch block. Event handlers can be attached to asynchronous error events, such as the MediaFailed event. If you use Visual Studio, you can use the integrated JavaScript debugging support to set breakpoints and inspect values.

This topic contains the following sections:

  • Using the Default OnError Event Handler
  • Defining an OnError Event Handler
  • Synchronous Method Calls and try/catch Blocks in JavaScript
  • Silverlight Asynchronous Error Events
  • Enabling JavaScript Debugging in Visual Studio

Using the Default OnError Event Handler

The samples in the Silverlight SDK use the JavaScript helper files, CreateSilverlight.js and Silverlight.js, which enable you to create a Silverlight plug-in in a platform-independent way. These files also provide a default event handler for the onError event. When you allow the onError property to default to null, or set the property to null, the default handler function defined in Silverlight.js is invoked when errors are encountered.

The onError handler is used for XAML parsing errors, errors that occur during load, run-time errors, errors in synchronous method calls that are not handled in a try/catch block, and asynchronous error events that do not have an attached event listener.

The default OnError event-handler function defined in the Silverlight.js file displays a dialog box similar to the following illustration when a scripting error is encountered in Microsoft Internet Explorer.

Alert dialog box for default event handler
Alert dialog box for default event handler

Defining an OnError Event Handler

You can define an error handler for your Silverlight-based application by setting the OnError property of the Silverlight plug-in to a custom event-handler function.

The onError event handler takes two parameters: the sender object and the event arguments. The sender is the object on which the error occurred. The second parameter is an instance of the ErrorEventArgs object or one of its derived objects, ParserErrorEventArgs or RuntimeErrorEventArgs, depending on the type of error.

The following table lists the properties on a ErrorEventArgs object. These properties are common to all error events handled by onError.

Property | Description
errorMessage | Identifies the message that is associated with the error event.
errorType | Identifies the type of error, defined as a value of the ErrorType enumeration.
errorCode | Specifies the code associated with the error event.

The following table lists the properties that are specific to parser errors, which are defined on a ParserErrorEventArgs object.

Property | Description
charPosition | Identifies the character position in which the error occurred.
lineNumber | Identifies the line on which the error occurred.
xamlFile | Identifies the XAML file in which the error occurred.
xmlAttribute | Identifies the XML attribute in which the error occurred.
xmlElement | Identifies the XML element in which the error occurred.

The following table lists properties that are specific to run-time errors, which are defined on a RuntimeErrorEventArgs object.

Property | Description
charPosition | Identifies the character position in which the error occurred.
lineNumber | Identifies the line on which the error occurred.
methodName | Identifies the method that is associated with the error.

The following JavaScript example shows how to set the OnError event handler to a user-defined function named OnErrorEventHandler.

JavaScript
 Silverlight.createObject("ErrorEvent.xaml", pe, "AgControl1",
                               {width:'1024', height:'530',
                                inplaceInstallPrompt:false,
                                background:'white', isWindowless:'false',
                                framerate:'24', version:'1.0'},
                               {onError:"OnErrorEventHandler",  // Set the onError handler.
                                onLoad:null}, null);

The following JavaScript example shows the associated event-handler function for the OnError event of the Silverlight plug-in. The ErrorType property on the ErrorEventArgs is checked to determine the specific type of error. If the error is a run-time or parser error, additional error information is added to the display message.

JavaScript
function OnErrorEventHandler(sender, errorArgs)
{
    // The error message to display.
    var errorMsg = "Silverlight Error: \n\n";

    // Error information common to all errors.
    errorMsg += "Error Type:    " + errorArgs.errorType + "\n";
    errorMsg += "Error Message: " + errorArgs.errorMessage + "\n";
    errorMsg += "Error Code:    " + errorArgs.errorCode + "\n";

    // Determine the type of error and add specific error information.
    switch(errorArgs.errorType)
    {
        case "RuntimeError":
            // Display properties specific to RuntimeErrorEventArgs.
            if (errorArgs.lineNumber != 0)
            {
                errorMsg += "Line: " + errorArgs.lineNumber + "\n";
                errorMsg += "Position: " +  errorArgs.charPosition + "\n";
            }
            errorMsg += "MethodName: " + errorArgs.methodName + "\n";
            break;
        case "ParserError":
            // Display properties specific to ParserErrorEventArgs.
            errorMsg += "Xaml File:      " + errorArgs.xamlFile      + "\n";
            errorMsg += "Xml Element:    " + errorArgs.xmlElement    + "\n";
            errorMsg += "Xml Attribute:  " + errorArgs.xmlAttribute  + "\n";
            errorMsg += "Line:           " + errorArgs.lineNumber    + "\n";
            errorMsg += "Position:       " + errorArgs.charPosition  + "\n";
            break;
        default:
            break;
    }
    // Display the error message.
    alert(errorMsg);
}
f

Synchronous Method Calls and try/catch Blocks in JavaScript

Synchronous method calls block the calling function until the call returns. A try/catch statement enables you to test a block of JavaScript code for errors. The try block contains the code to be run, and the catch block contains the code to be executed if an error occurs.

If a synchronous method call fails and the method call is in a try/catch block, an error object, described in "ECMAScript Language Specification" (ECMA-262), is passed to the catch block and an onError event is not raised. Because an onError event is not raised, the onError event handler will not be called. If a synchronous method call fails and the method call is not inside a try/catch block, an onError event is raised and routed to the onError handler of the Silverlight plug-in. The ErrorType in the event arguments sent to the onError handler will be set to RuntimeError.

The only Silverlight-specific error information returned to the catch block through the error object is the ErrorMessage and on Internet Explorer only, the ErrorCode. The message property on the error object is set to the error message.

The try/catch functionality is currently supported on all browsers and operating systems that Silverlight supports except for Apple Safari and Macintosh. Because of this limitation, we recommend using onError for all synchronous run-time methods.

The following JavaScript example shows how to use a try/catch statement to handle errors generated from the Play method.

JavaScript
    // Get the MediaElement object.
    var player = sender.findName("MediaPlayer");

    try
    {
        // Attempt to start the media.
        player.play();
    }
    catch(errorObj)
    {
        // Perform necessary error handling.

        // Display the message of the Error Object.
        alert(errorObj.message);
    }

The following image shows the resulting error message that is displayed when the call to play in the previous example fails.

Error message
Error message

Silverlight Asynchronous Error Events

An asynchronous call returns control immediately after it has been called. An error that occurs during the asynchronous call will raise an error event that is specific to the type of call. If a handler is not attached to the event, an onError event will be raised and handled by the handler defined on the Silverlight plug-in. An example of an asynchronous error event is the MediaFailed event.

The following XAML shows how to attached an event handler to the MediaFailed event.

XAML
  <MediaElement x:Name="MediaPlayer" MediaFailed="MediaFailedHandler" />

The following JavaScript code shows an event handler for the MediaFailed event.

JavaScript
function MediaFailedHandler(sender, args)
{

    // Create basic error message.
    var errorMsg = "\n Media Error Message     \n" ;

    // Add Media information.
    errorMsg += "MediaElement Name: " + sender.Name + "\n";
    errorMsg += "Media File Name: " + sender.Source + "\n";

    // Display error information.
    alert(errorMsg);
}

Enabling JavaScript Debugging in Visual Studio

When you create a Silverlight-based application in Visual Studio, you can use Visual Studio to debug your JavaScript code. You can set breakpoints, view and modify variable values, and run script in the Immediate window. To enable JavaScript debugging in Visual Studio, you need to clear the "Disable script debugging" settings in Internet Explorer. By default, the check boxes for these settings are selected. The following illustration shows the check boxes after they have been cleared.

Internet Explorer advanced options

Internet Explorer advanced options

After you clear the "Disable script debugging" settings, you can set breakpoints in your JavaScript code, as shown in the following illustration.

Setting breakpoints

Note If you are running Windows Vista, you must run Visual Studio with administrator access; otherwise, breakpoints will be ignored.

See Also

Silverlight Events
Using Silverlight Plug-ins
Overviews


XAML Syntax Overview

This overview describes the different ways to declare objects and set properties in Extensible Application Markup Language (XAML).

This topic contains the following sections:

  • What Is XAML?
  • Declaring Objects
  • Setting Properties
  • Events

What Is XAML?

Extensible Application Markup Language (XAML) is a declarative language. You can create visible user interface (UI) elements in the declarative XAML markup. You can then use JavaScript in a separate code-behind file to respond to events and manipulate the objects you declared in XAML. An XML-based declarative language is very intuitive for creating interfaces from prototype to production, especially for people with a background in Web design and technologies.

XAML files are XML files that generally have the .xaml file name extension. The following example shows the contents of a typical Silverlight XAML file.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Rectangle
    Width="100"
    Height="100"
    Fill="Blue" />
</Canvas>

Declaring Objects

There are two ways to declare objects and set properties in XAML:

  • Object element syntax: Uses opening and closing tags to declare an object as an XML element. You can use this syntax to declare root objects or to set property values.
  • Attribute syntax: Uses an inline value to declare an object. You can use this syntax to set the value of a property.

Declaring an Object by Using Object Element Syntax

A typical way to declare an object is to use object element syntax, by creating the following two XML element tags, where objectName is the name of the object that you want to instantiate.

<objectName>

</objectName>

The following example uses object element syntax to declare a Canvas object.

XAML
<Canvas>
</Canvas>

Some objects, such as Canvas, can contain other objects.

XAML
<Canvas>
  <Rectangle>
  </Rectangle>
</Canvas>

As a convenience, if the object does not contain other objects, you can declare it by using one tag instead of two, as shown in the following example.

XAML
<Canvas>
  <Rectangle />
</Canvas>

Declaring an Object by Using Attribute Syntax

See the next section for information about how to use attribute syntax to declare an object and to set its properties in one step.

Setting Properties

You can set properties on objects that you declared by using object element syntax. There are multiple ways to set properties in XAML:

  • By using attribute syntax.
  • By using property element syntax.
  • By using content element syntax.
  • By using implicit collection syntax.

Setting a Property by Using Attribute Syntax

Use the following syntax, where ObjectName is the object you want to instantiate, property is the name of the property that you want to set on that object, and propertyValue is the value to set.

<objectNameproperty="propertyValue">

</objectName>

This syntax enables you to declare an object and set a property on that object in one step.

The following example uses attribute syntax to set the width, height, and fill of a Rectangle object.

XAML
<Canvas>
  <Rectangle
    Width="100"Height="100"Fill="Blue" />
</Canvas>

Setting a Property by Using Property Element Syntax

Some properties can be set by using property element syntax. To use property element syntax, you create XML elements for the property that you want to set. In the following syntax, property is the name of the property that you want to set and propertyValue is the type of value to set.

<objectName>

  <objectName.property>

    <propertyValue ... />

  </objectName.property>

</objectName>

The following example uses property element syntax to set the fill of a Rectangle with a SolidColorBrush.

XAML
<Canvas>
  <Rectangle
    Width="100"
    Height="100">
    <Rectangle.Fill>
      <SolidColorBrush />
    </Rectangle.Fill>
  </Rectangle>
</Canvas>

Setting a Property by Using Content Element Syntax

Sometimes, when a property supports property element syntax, you can omit the property name and set the property simply by nesting a value within the owning type's object tags. This is known as content element syntax. The following example sets the Text property of a TextBlock without explicitly specifying the Text property.

XAML
    <TextBlock>
      Hello!
    </TextBlock>

Setting a Property by Using Implicit Collection Syntax

Sometimes, when a property takes a collection, you can omit the collection element and simply specify its contents instead. This is known as implicit collection syntax. The following example shows how you can omit the GradientStopCollection for a LinearGradientBrush and simply specify its GradientStop objects. The GradientStopCollection is included in the first LinearGradientBrush but omitted from the second.

XAML
    <Rectangle Width="100" Height="100"
      Canvas.Left="0" Canvas.Top="30">
      <Rectangle.Fill>
        <LinearGradientBrush>
          <LinearGradientBrush.GradientStops>

            <!-- Here the GradientStopCollection tag is specified. -->
            <GradientStopCollection>
              <GradientStop Offset="0.0" Color="Red" />
              <GradientStop Offset="1.0" Color="Blue" />
            </GradientStopCollection>
          </LinearGradientBrush.GradientStops>
        </LinearGradientBrush>
      </Rectangle.Fill>
    </Rectangle>

    <Rectangle Width="100" Height="100"
      Canvas.Left="100" Canvas.Top="30">
      <Rectangle.Fill>
        <LinearGradientBrush>
          <LinearGradientBrush.GradientStops>

            <!-- Notice that the GradientStopCollection tag
                 is omitted. -->
            <GradientStop Offset="0.0" Color="Red" />
            <GradientStop Offset="1.0" Color="Blue" />
          </LinearGradientBrush.GradientStops>
        </LinearGradientBrush>
      </Rectangle.Fill>
    </Rectangle>

Sometimes you can omit both the collection element and the property element tags, as shown in the following example.

XAML
    <Rectangle Width="100" Height="100"
      Canvas.Left="200" Canvas.Top="30">
      <Rectangle.Fill>
        <LinearGradientBrush>
          <GradientStop Offset="0.0" Color="Red" />
          <GradientStop Offset="1.0" Color="Blue" />
        </LinearGradientBrush>
      </Rectangle.Fill>
    </Rectangle>

When to Use Attribute or Property Element Syntax to Set a Property

All properties support either attribute or property element syntax, and some properties support others. The type of syntax supported by a property depends on the type of object the property accepts. If the property value is a primitive type, such as a Double, Integer, or String, the property supports attribute syntax only. The following example uses attribute syntax to set the width of a Rectangle. The Width property supports attribute syntax, because the property value is a Double.

XAML
<Rectangle Width="100" />

Whether you can use attribute syntax to set a property depends on whether the object you use to set that property supports attribute syntax. The following example uses attribute syntax to set the fill of a Rectangle. The Fill property supports attribute syntax when you use a SolidColorBrush to set it, because SolidColorBrush supports attribute syntax.

XAML
<Rectangle Fill="Blue" />

Whether you can use property element syntax to set a property depends on whether the object you use to set that property supports object element syntax. If the object supports object element syntax, the property also supports property element syntax. The following example uses property element syntax to set the fill of a Rectangle. The Fill property supports attribute syntax when you use a SolidColorBrush to set it, because SolidColorBrush supports attribute syntax.

XAML
<Rectangle>
  <Rectangle.Fill>
    <SolidColorBrush />
  </Rectangle.Fill>
</Rectangle>

Events

XAML is a declarative language for objects and their properties, but XAML also includes a facility for attaching event handlers to objects in the markup. You provide the name of the event you add the handler for as an attribute name on the object where the event is handled. For the attribute value, you provide the name of an event-handler function that you define in script. The XAML reader uses this name to create a delegate representation in the loaded object tree and attaches the specified handler.

The following XAML example shows how to attach a handler for the Loaded event for the Canvas.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  Loaded="onLoaded" />

The function named onLoaded is defined in a JavaScript file. This JavaScript file is associated with the XAML file through the src parameter of the <SCRIPT> tag. This reference is included in the HTML page where the Silverlight plug-in that loads the XAML is created, as shown in the following example.

HTML
...
<!-- Reference the JavaScript file where the event functions are defined
     from the plug-in host HTML page. -->
<script type="text/javascript" src="eventfunctions.js"></script>
...

For more information about events, see Silverlight Events.

See Also

Silverlight Object Models
Overviews


Ink Support in Microsoft Silverlight

This topic describes various uses for ink in your Microsoft Silverlight-based Web applications.

This topic contains the following sections:

  • Common Ink Scenarios
  • Supported Ink Input Devices
  • Getting Started with Ink in Silverlight

Common Ink Scenarios

Annotation

Silverlight has rich support for hosting different types of content vessels and other media, and adding ink annotation is a way to make Silverlight content more interactive and personal. Using the elements to implement ink annotation in Silverlight is both easy and flexible. In addition, Silverlight is the only Web technology to support collection and display of high-quality pen input from Tablet PC devices.

Blogging

Blogs are personal, and when you add ink to a blog it gives them a unique, personal touch. You also extend what is possible in a blog when you add writing, drawing, and annotation over photos and videos.

Games

The use of ink in Silverlight opens up new scenarios for natural interaction in online game content. Silverlight makes the implementation of these scenarios straightforward, and the flexibility of the input model enables great flexibility when you implement it in your gaming content.

Supported Ink Input Devices

Pen Input

Computers with pen digitizers (such as a Tablet PC or even a desktop computer with an external digitizer) can take advantage of the full-fidelity pen input in Silverlight. These devices create ink that you can integrate into your Silverlight Web pages, resulting in high-quality handwriting, drawing, annotation, oil painting and other content input with a pen.

Touch Input

Silverlight supports touch-screen devices such as those found in certain Tablet PC and Ultra-Mobile PC (UMPC) computers. Touch enables users to interact with Silverlight content in a natural way, when a keyboard or a stylus is cumbersome or unnecessary.

Mouse Input

You can use a mouse to collect ink in Silverlight Web content. However, ink that is generated with the mouse has a lower resolution when compared to pen input that is gathered with a digitizer. You can use mouse-generated ink in the same way as pen-generated ink.

Getting Started with Ink in Silverlight

Understanding Ink Data

Ink refers to handwriting or drawing content that has been input with a pen, touch, or mouse. The ink in Silverlight is made up of a StrokeCollection object, which, in turn, is made up of individual Stroke objects. Each Stroke corresponds to a pen down, pen move, and pen up sequence. A Stroke can be a dot, a straight line, or a curving line. Each Stroke is made up of a StylusPointCollection object, which, in turn, is made up of individual StylusPoint objects. StylusPoint objects are collected when the pen moves while it is in contact with the digitizer. The ink also contains characteristics such as color, width, and outline color, all of which are contained in the DrawingAttributes class.

InkPresenter Element

The InkPresenter element is a Canvas that you use to display ink. The InkPresenter is generally the same as the Canvas element, but also has a StrokeCollection. When you add Stroke objects to the StrokeCollection, the InkPresenter automatically renders them.

Collecting Ink by Using Mouse Events

In general, you collect ink by retrieving StylusPoint objects when the pen moves while in contact with the screen. You then add a Stroke object, which consists of the collected StylusPoint objects, to the StrokeCollection that is associated with the InkPresenter.

See Also

The Ink Object Model: Windows Forms and COM versus WPF
Sample Applications
Overviews


Performance Tips

Silverlight SDK

Performance Tips for Silverlight-based Applications

This overview provides tips to ensure that your Microsoft Silverlight-based applications run fast and smoothly.

This topic contains the following sections:
  • Test on Multiple Platforms and Browsers
  • Set EnableFrameRateCounter to true During Development
  • Use Transparent Background for a Silverlight Plug-in Sparingly
  • Use Silverlight Animations Instead of Creating Your Own Per-Frame Animations
  • Avoid Animating the Size of Text
  • Avoid Using Windowless Mode
  • Use Visibility Instead of Opacity Whenever Possible
  • Silverlight Uses Multi-Core in Rendering and Media
  • In Full-Screen Mode, Hide Unused Objects
  • Do Not Use Width and Height with MediaElement Objects
  • Do Not Use Width and Height with Path Objects
  • When Downloader Finishes, Detach Events and Set to Null
  • Break Up CPU-Intensive Work into Smaller Tasks

Test on Multiple Platforms and Browsers

If you are developing Silverlight-based applications for multiple operating systems (for example, Macintosh and Windows) and browsers (for example, Microsoft Internet Explorer, Mozilla FireFox, and Apple Safari), remember to routinely test your applications by using the platform and browser combinations that you are targeting. The differences in platform or browser behavior, and the code Silverlight uses to handle the behavior, can affect application performance. In particular, you should test thoroughly when you create applications that have transparent embedded plug-in backgrounds, or applications that use a large amount of JavaScript code.

Set EnableFrameRateCounter to true During Development

The rendering performance of the plug-in varies with the hosting parameters that are specified and the complexity of the content. We recommend that you set the EnableFrameRateCounter property to true during development. This setting will display the frames-per-second (fps) of the rendered Silverlight content in the browser's status bar, so you can fine-tune your application.

Use Transparent Background for a Silverlight Plug-in Sparingly

A transparent background may be useful, for example, when your embedded Silverlight plug-in contains a non-rectangular shape such as a picture of a car, and you do not want to show the rectangle surrounding the car. You can make only the picture of the car visible by setting the background of the Silverlight plug-in to transparent. However, using a transparent background for a Silverlight plug-in has a significant effect on performance, so avoid using this functionality whenever possible.

Use Silverlight Animations Instead of Creating Your Own Per-Frame Animations

It is faster to change property values by using Silverlight built-in animations instead of creating your own per-frame animations using JavaScript. The recommended method for manipulating the element tree over time is through the animation system. This approach is platform- and browser-independent and is the most efficient method.

Avoid Animating the Size of Text

Animating the size of text can potentially use a lot of system resources. This is because Silverlight uses hinting to smooth each text glyph when it renders text. If you animate the text size (by using the Transform object or the FontSize property), Silverlight will hint the glyphs for each frame, which is costly and could result in frame-dropping. If your application requires dynamic scale changes of large text, it may be better to use vector graphics to represent the text.

Avoid Using Windowless Mode

Set the Windowless property to true only when necessary. Windowless mode is expensive and can cause tearing during animations.

Use Visibility Instead of Opacity Whenever Possible

If you simply want to make an object visible or not visible instead of using partial opacity or fading the object in or out of view, use the Visibility property instead of Opacity property. Opacity is associated with higher costs because the object is still hit tested and technically rendered. Setting Visibility to Collapsed avoids these costs.

Silverlight Uses Multi-Core in Rendering and Media

Silverlight takes advantage of multi-core for rendering and media playback. Therefore, your Silverlight-based applications will perform faster on multi-core systems.

In Full-Screen Mode, Hide Unused Objects

When your application goes into full-screen mode, hide all objects that are not being rendered in full-screen mode, or disconnect them from the tree. You can hide an object by setting its Visibility property to Collapsed.

Do Not Use Width and Height with MediaElement Objects

Avoid explicitly setting the width and height of a MediaElement object. Instead, let the media element display at its natural size. If you need to change the display size of the element, it is best to re-encode the media to the desired size by using a media encoding tool.

Do Not Use Width and Height with Path Objects

Do not set the Width and Height properties for a Path object. Setting these properties will result in additional stretching, which affects performance. Instead, rely on the explicitly set coordinates of the Path object to control its shape and position.

When Downloader Finishes, Detach Events and Set to Null

When you use the Downloader object, after the Completed event fires, detach all event handlers from the Downloader, and then set Downloader to null.

Break Up CPU-Intensive Work into Smaller Tasks

When JavaScript is running, the plug-in will stop drawing. Typically, this is not an issue if minimal work is done in the event handlers. However, if your application requires substantial, CPU-intensive work on the JavaScript thread, we recommend that you split that work into smaller tasks. This will allow rendering to keep up with the desired frame rate.

See Also

Overviews


Accessibility

Silverlight SDK

Accessibility in Silverlight

This overview describes techniques you can use to make your Microsoft Silverlight-based applications more accessible.

This topic contains the following sections:

  • Screen Reader
  • Associating Screen Reader Information and Events with the Silverlight Plug-In
  • Limitations

Screen Reader

Most of the accessibility features described in this overview depend on the screen reader that ships with the Windows operating system. The screen reader reads text from the screen audibly so that people who are visually impaired can access the content.

Associating Screen Reader Information and Events with the Silverlight Plug-In

The Silverlight Accessibility object and its members let you associate descriptive information with your Silverlight plug-in so that that information can be read out loud by a screen reader. For example, if you create an advertisement for a game such as Gears of War, you could provide information that would be read out loud by a screen reader, and then associate that information with the plug-in.

Specifically, the Accessibility object enables you to provide information to a screen reader by using the properties described in the following table.

Property | Description | Example
Title | Specifies the title of the plug-in. | "Gears of War Advertisement"
Description | Describes what the plug-in consists of or what it provides. | "This is an advertisement for Gears of War. Gears of War is a tactical video game developed by Epic Games and published by Microsoft Game Studios."
ActionDescription | Gets or sets a string that describes the primary method of manipulation for the Silverlight plug-in instance and its content from the user's viewpoint. | "Click to find out more."

In addition to these properties, the Accessiblity object provides the PerformAction event that is fired whenever the accessibility technology invokes an action.

The following example shows how to use these members to make a Silverlight plug-in more accessible.

  1. Associate OnLoad Event to Plug-in: You cannot manipulate the Accessiblity object from XAML. Therefore, you must find a way to set the Accessibility object in procedural code. You can associate the OnLoad event to the plug-in by setting the CreateSilverlight.js file to call the OnLoad event like this:

    JavaScript
    function createSilverlight()
{
    Silverlight.createObject(
        "advertisement.xaml",                  // Source property value.
        parentElement,                  // DOM reference to hosting DIV tag.
        name,                           // Unique plug-in id value, a variable set prior to each page call
        {                               // Plug-in properties.
            width:'600',                // Width of rectangular region of plug-in in pixels.
            height:'200',               // Height of rectangular region of plug-in in pixels.
            version:'1.0'               // Plug-in version to use.
        },
        {
            onError:null,               // Use default error handler.
            onLoad:onLoad               // OnLoad event handler that can be used for multiple instances.
        },
        null,                           // InitParams property value set to null.
        context);                       // Unique context id, a variable set prior to each page call
}

    The code below shows how this might look in the larger context of the CreateSilverlight.js file:

    JavaScript
    function createSilverlight()
{
    Silverlight.createObject(
        "advertisement.xaml",                  // Source property value.
        parentElement,                  // DOM reference to hosting DIV tag.
        name,                           // Unique plug-in id value, a variable set prior to each page call
        {                               // Plug-in properties.
            width:'600',                // Width of rectangular region of plug-in in pixels.
            height:'200',               // Height of rectangular region of plug-in in pixels.
            version:'1.0'               // Plug-in version to use.
        },
        {
            onError:null,               // Use default error handler.
            onLoad:onLoad               // OnLoad event handler that can be used for multiple instances.
        },
        null,                           // InitParams property value set to null.
        context);                       // Unique context id, a variable set prior to each page call
}

    See Using the OnLoad Event for more information.

  2. Use the Accessibiliy Object and its Members: Use the OnLoad event handler to set the Accessiblity object and its members (see below).

    JavaScript
    function onLoad(plugin, userContext, sender)
{

    // specify accessibility info
    var acc = plugin.content.accessibility;
    acc.Title = "Gears of War Advertisement";
    acc.description = "This is an advertisement for Gears of War. " +
                      "Gears of War is a tactical third-person shooter " +
                      "video game developed by Epic Games. and published by" +
                      " Microsoft Game Studios.";
    acc.actionDescription = "Click to find out more";

    acc.addEventListener("PerformAction", "doAccessibilityAction")
}

function doAccessibilityAction(sender)
{
    // TODO: navigate to Gears of War game site...
}

Limitations

Accessibility limitations:

  • Only the plug-in can get focus, not individual elements within the plug-in. As a result:
    • You cannot associate accessibility information with elements within the plug-in. For example, in the advertisement example, you can provide a description for the advertisement plug-in, but you cannot associate a description with a specific media play button or other object within the advertisement.
    • Because there is no focus, there is no tab index, ordering, or navigation for elements.
    • Without focus, all keyboard input goes to the root element.
  • Browser and platform limitations:
    • On Windows, exposing accessibility information requires the control to use embedded mode, not full-screen mode. See Silverlight Full-Screen Support for more information.
    • The Macintosh does not provide accessibility for browser plug-ins. Therefore, none of the accessibility information being exposed on the Silverlight plug-in can be accessed on the Macintosh through a screen reader.

See Also

Overviews


Using Inline XAML as the XAML Source

Rather than using a discrete file that is referenced by a URI to set the initial Silverlight content, you can specify an area of inline HTML content that contains your XAML. In order to use this technique, you must enclose the XAML in a special SCRIPT block, and use a "#" prefix in the source parameter.

Creating and Referencing Inline XAML

You can create inline XAML content that is contained within an HTML document element by using a script tag that specifies "text/xaml" as the type attribute. Notice that the XML document type declaration, <?xml version="1.0"?>, precedes the XAML content. The XAML content must be uniquely identified so it can be referenced by the source initialization parameter of the Silverlight plug-in. The prefix '#' is used to identify a source parameter value that references XAML content by its scripting tag identifier.

The XAML content can also define events that reference event handlers in the HTML page. The following HTML example shows how to create inline XAML content. In this case, the HTML page contains both JavaScript and XAML content.

HTML
<html>
<head>
  <title>Display Date</title>
  <script type="text/javascript" src="CreateSilverlight.js"></script>
  <script type="text/javascript" src="Silverlight.js"></script>

  <!-- Define Loaded event handler for TextBlock. -->
  <script type="text/javascript">
    function setDate(sender, eventArgs)
    {
      sender.text = Date();
    }
  </script>
</head>

<body bgcolor="Teal">

<!-- Define XAML content. -->
<script type="text/xaml" id="xamlContent"><?xml version="1.0"?>
  <Canvas
    xmlns="http://schemas.microsoft.com/client/2007"
    Background="Wheat">
    <TextBlock
      Canvas.Left="20"
      FontSize="24"
      Loaded="setDate" />
  </Canvas>
</script>

<div id="pluginHost" >
  <script type="text/javascript">
    var parentElement = document.getElementById("pluginHost");
    createSilverlightEx();
  </script>
</div>

</body>
</html>

Note: The script tag that contains the inline XAML content must precede the HTML element that contains the Silverlight plug-in, and therefore references the inline XAML for its source initialization.

The following JavaScript example shows how to reference the inline XAML content in the user-defined CreateSilverlightEx method in CreateSilverlight.js, which then calls the CreateObjectEx helper function in Silverlight.js. When you use CreateObjectEx, parameter values that are not defined are set to their default values.

JavaScript
function createSilverlightEx()
{
    Silverlight.createObjectEx({
        source: '#xamlContent',         // Source property value.
        parentElement:parentElement,    // DOM reference to hosting DIV tag.
        id:'myPlugin',                  // Unique plug-in ID value.
        properties:{                    // Plug-in properties.
            width:'360',                // Width of rectangular region of plug-in in pixels.
            height:'60',                // Height of rectangular region of plug-in in pixels.
            background:'oldlace',       // Background color of plug-in.
            version:'1.0'},             // Silverlight version.
        events:{
            onLoad:null}});             // OnLoad property value -- event handler function name.
}

When the page in the previous HTML example displays, the Silverlight plug-in is loaded and the Loaded event for the TextBlock object is fired, causing the TextBlock to display the current date and time.

Display output for inline XAML content example

See Also

Silverlight Object Models
Using a Silverlight Plug-in
Using CreateSilverlight.js and Silverlight.js
Using the createFromXaml Method
Source


XAML Namescopes

In Microsoft Silverlight, a namescope stores relationships between the XAML-defined names of objects and their instance equivalents. This is similar to the wider meaning of the term "namescope" in other programming languages and technologies. Namescopes are created during the process of loading the XAML source for a Silverlight-based application.

This topic contains the following sections:

  • How Namescopes are Defined
  • Using Namescopes at Runtime
  • Adding Objects to Silverlight at Runtime
  • Creating Namescopes with CreateFromXAML

How Namescopes are Defined

Namescopes are created by the XAML parser, and associated with the root element for a XAML element tree when the XAML is loaded. Typically, the XAML of the element tree is defined within a single XAML file, which is completely in XAML format. But XAML can also be defined as inline XAML within the HTML, or can be used as the string input for the CreateFromXaml method technique that is used to initialize new Silverlight objects at runtime.

Each name specified within the XAML is added to the root namescope. A name is established by setting the value for one of two nearly equivalent attributes, Name or x:Name. (For details on the distinction between Name and x:Name, see Remarks in Name.) If you try to define the same name twice in any namescope, an exception will be raised.

In general, attributes in XAML can only be specified on object elements. Property elements (used to provide values for certain Silverlight properties in XAML) cannot have a Name or any other attribute. For details on XAML syntax, see XAML Syntax Overview.

Using Namescopes at Runtime

Names and namescopes enable scripting code to reference the objects that were initially defined in XAML. The internal result of parsing XAML is to create a set of objects that retain some or all of the relationships these objects had in XML, with those relationships maintained as specific object properties of the created objects, or exposed to utility methods in the Silverlight object model. The most useful of these utility methods is FindName. In order to get an object reference to an object that was defined in XAML, simply use the return value of the FindName method, specifying the name of the object you want to retrieve as an input parameter. FindName works from almost any scope and will search the entire runtime set of objects; you are not limited to searching in particular parent-child axes. However, there are ways to define multiple namescopes within a Silverlight-based application. The effect of this ability on FindName calls is discussed in the upcoming sections.

Namescopes act identically, whether XAML content is defined as inline XAML or as a file that is entirely XAML. The namescope is defined on the basis of the root of the XAML portion, as if it were the root of a XAML file.

Adding Objects to Silverlight at Runtime with CreateFromXAML

In Silverlight 1.0, there is no true constructor syntax available in scripting for Silverlight objects. Instead, you define objects in XAML fragments, which are supplied as the input parameter for the CreateFromXaml method. The object elements that are defined as part of this XAML fragment can also have values defined for Name or x:Name. As part of the CreateFromXaml call, a preliminary namescope is created, based on the root of the provided XAML. This preliminary namescope evaluates any defined names in the provided XAML for uniqueness. If names in the provided XAML are not internally unique at this point, CreateFromXaml throws an error. However, if names in the provided XAML collide with names that are already in the primary Silverlight namescope, no errors occur immediately. This is because when the CreateFromXaml is called, the created object tree is disconnected. You must explicitly connect your created object tree, either by adding it to a content property collection such as Canvas.Children, or by setting some other property that takes an object value (such as specifying a new ImageBrush for a Fill property value). You will see name collisions causing errors only after you attempt to connect the disconnected object tree to the application's main object tree. The method or property used for the attempted connection will be the source of the error, and the attempted connection will fail (your disconnected tree will remain disconnected).

Creating Namescopes with CreateFromXAML

CreateFromXaml has an optional parameter createNameScope, which is normally defaulted to false. If you explicitly set this value to true in the CreateFromXaml call that you use to create a disconnected object tree, this still creates a preliminary namescope that evaluates any defined names in the provided XAML for uniqueness. If names in the provided XAML are not internally unique at this point, CreateFromXaml throws an error. The difference in the behavior is that the disconnected object tree is now flagged to not attempt to merge its namescope with the main application namescope when it is connected to the main application object tree. After you connect the trees, in effect your application now has a unified object tree, but discrete namescopes. A name defined at the CreateFromXaml root or on any object in the previously disconnected tree is not associated with the main application namescope; it has its own discrete namescope.

The complication with having discrete namescopes is that calls to the FindName method no longer work on a unified scope / namescope. Instead, the particular object that FindName is called on will imply the scope, with the scope being the namescope that the calling object is within. Therefore, if you attempt to call FindName to get a named object in the main application namescope from out of a discrete namescope created by CreateFromXaml, your result will be null. Conversely, calling FindName from the discrete namescope will not find named objects in the main application namescope. The FindName method defined on the Silverlight Plug-in object does not work around this issue; its namescope is always the main application namescope.

This discrete namescope issue only affects namescopes and the FindName call. You can still walk discrete steps upwards in some cases by calling the GetParent method, or walk discrete steps downward by calling into the relevant collection properties or properties (such as the collection returned by Canvas.Children).

To get to objects that are defined in a different namescope, you have several possible techniques:

  • Until you reach the object you want, you can walk the entire tree in discrete steps with GetParent and/or collection properties.
  • If you are calling from a discrete namescope and want the main application namescope, it is always easy to get a reference to the Silverlight plug-in and then call FindName on it. The concatenated script call for doing this in a single line is:
    returnedObject = object.GetHost().content.FindName("nameToFind");
    Here, object is the calling object in a discrete namescope. The .content in this syntax is the step through to the specific Silverlight plug-in subobject that defines the FindName method.
  • If you are calling from the main application namescope and want an object within a discrete namescope, the best thing to do is to plan ahead in your code and retain a reference to the object that was returned by CreateFromXaml and then added to the tree. You could keep this object as a global variable or otherwise pass it by using method parameters.

    • See Also

    Using the createFromXaml Method
    Using Inline XAML as the XAML Source
    Silverlight Plug-in Object
    FindName
    Name Property (DependencyObject)


Silverlight Scripting Application Notes

This topic contains the following section:

  • Numeric Values Stored as Single-Precision Values
  • Limits on Floating Point Numbers
  • Referencing an Event Handler Function

Numeric Values Stored as Single-Precision Values

Silverlight stores all numeric values internally as single-precision values. This means that if a property value is set to a higher precision value, such as a double, the property value that is later retrieved may not be the same, due to truncation or rounding.

Limits on Floating Point Numbers

A floating point can be no larger than +/- 1,000,000.

Referencing an Event Handler Function

The following XAML example shows how to attach a handler for the Loaded event for the Canvas object. Notice that the reference to the event handler function name is not prefixed by "javascript:". That prefix was required for early prerelease versions of Silverlight, then made optional in later prerelease versions, but is not permitted in the release versions.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  Loaded="onLoaded" />

The equivalent operation in script is to call the AddEventListener method. The second AddEventListener parameter that specifies the event handler function can be in two general forms: a quoted string of the function name, or a reference to the function name. For instance to parallel the XAML above, you could use either the syntax rootCanvas.addEventHandler("Loaded","onLoaded") or rootCanvas.addEventHandler("Loaded",onLoaded). You can also use a variation of the second syntax by explicitly creating a delegate for your function.

AddEventListener returns a token value that is necessary if you intend to remove that event handler through runtime script. For details see AddEventListener.

See Also

Silverlight Object Models, Using Silverlight Plug-ins, Silverlight Events


Silverlight Graphics Conceptual Topics

Silverlight SDK

Silverlight Graphics

The overviews in this section describe how to draw and paint with Microsoft Silverlight.

  • Shapes and Drawing in Silverlight: Provides an overview of how to draw with Shape objects. A Shape is a type of UIElement that enables you to draw a shape on the screen. Because they are UI elements, Shape objects can be used inside the Canvas element.

  • Brushes Overview: Describes how to use Silverlight brush objects to paint with solid colors, linear gradients, radial gradients, and images.

  • VideoBrush Overview: Describes how to use the Silverlight VideoBrush to paint shapes and text with video, and shows how to interactively control a VideoBrush.

  • Geometries Overview: Describes how to use the Silverlight Geometry objects to define shapes, and contrasts Geometry objects and Shape elements.

  • Path Markup Syntax: Describes the Extensible Application Markup Language (XAML) usage syntax for describing paths.

  • Transforms Overview: Describes how to use the 2-D transform classes to rotate, scale, skew, and move (translate) objects.

See Also

Introduction to Silverlight 1.0
Silverlight Architecture
What Changed Between Beta and Release of Silverlight 1.0
Silverlight 1.0 QuickStarts


Shapes and Drawing in Silverlight Overview

This topic gives an overview of how to draw with Shape objects. A Shape is a type of UIElement that enables you to draw a shape to the screen. Because they are UI elements, Shape objects can be used inside the Canvas element.

This topic contains the following sections.

  • Shape Objects
  • Using Paths and Geometries
  • Painting Shapes
  • Transforming Shapes
  • Related Topics

Shape Objects

Silverlight provides a number of ready-to-use Shape objects. Available shape objects include Ellipse, Line, Path, Polygon, Polyline, and Rectangle. Shape objects share the following common properties.

  • Stroke: Describes how the shape's outline is painted.

  • StrokeThickness: Describes the thickness of the shape's outline.

  • Fill: Describes how the interior of the shape is painted.

  • Data properties to specify coordinates and vertices, measured in device-independent pixels.

Shape objects can be used inside Canvas objects. Canvas supports absolute positioning of its child objects through the use of the Canvas.Left and Canvas.Top attached properties.

The Line class enables you to draw a line between two points. The following example shows several ways to specify line coordinates and stroke properties.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Height="300" Width="300">

  <!-- Draws a diagonal line from (10,10) to (50,50). -->
  <Line
    X1="10" Y1="10"
    X2="50" Y2="50"
    Stroke="Black"
    StrokeThickness="4" />

  <!-- Draws a diagonal line from (10,10) to (50,50)
       and moves it 100 pixels to the right. -->
  <Line
    X1="10" Y1="10"
    X2="50" Y2="50"
    StrokeThickness="4"
    Canvas.Left="100">
    <Line.Stroke>
      <RadialGradientBrush GradientOrigin="0.5,0.5" Center="0.5,0.5" RadiusX="0.5" RadiusY="0.5">
        <RadialGradientBrush.GradientStops>
          <GradientStop Color="Red" Offset="0" />
          <GradientStop Color="Blue" Offset="0.25" />
        </RadialGradientBrush.GradientStops>
      </RadialGradientBrush>
    </Line.Stroke>
  </Line>

  <!-- Draws a horizontal line from (10,60) to (150,60). -->
  <Line
     X1="10" Y1="60"
     X2="150" Y2="60"
     Stroke="Black"
     StrokeThickness="4"/>

</Canvas>

Although the Line class does provide a Fill property, setting it has no effect because a Line has no area.

Another common shape is the Ellipse. Create an Ellipse by defining the shape's Width and Height properties. To draw a circle, specify an Ellipse whose Width and Height values are equal.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <Ellipse
    Fill="Yellow"
    Height="100"
    Width="200"
    StrokeThickness="2"
    Stroke="Black"/>
</Canvas>

Using Paths and Geometries

The Path class enables you to draw curves and complex shapes. These curves and shapes are described using Geometry objects. To use a Path, you create a Geometry and use it to set the Path object's Data property. There are a variety of Geometry objects to choose from. The LineGeometry, RectangleGeometry, and EllipseGeometry classes describe relatively simple shapes. To create more complex shapes or create curves, use a PathGeometry. For information about creating PathGeometry objects, see the Silverlight Geometries Overview.

XAML Abbreviated Syntax

In Extensible Application Markup Language (XAML), you may also use a special abbreviated syntax to describe a Path. In the following example, abbreviated syntax is used to draw a complex shape.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <Path Stroke="DarkGoldenRod" StrokeThickness="3"
    Data="M 100,200 C 100,25 400,350 400,175 H 280" />
</Canvas>

The following illustration shows the rendered Path.

The Data attribute string begins with the "move to" command, indicated by M, which establishes a start point for the path in the coordinate system of the Canvas. Path data parameters are case-sensitive. The capital M indicates an absolute location for the new current point. A lowercase m would indicate relative coordinates. The first segment is a cubic Bezier curve beginning at (100,200) and ending at (400,175), drawn using the two control points (100,25) and (400,350). This segment is indicated by the C command in the Data attribute string. Again, the capital C indicates an absolute path; the lowercase c would indicate a relative path.

The second segment begins with an absolute horizontal "line to" command H, which specifies a line drawn from the preceding subpath's endpoint (400,175) to a new endpoint (280,175). Because it is a horizontal "line to" command, the value specified is an x-coordinate.

For the complete path syntax, see the Data reference and Path Markup Syntax.

Painting Shapes

You use Brush objects to paint a shape's Stroke and Fill. In the following example, the stroke and fill of an Ellipse are specified. Note that valid input for brush properties can be either a keyword or hexadecimal color value.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Width="300" Height="300"

  Background="LightGray">
  <Ellipse
    Canvas.Top="50"
    Canvas.Left="50"
    Fill="#FFFFFF00"
    Height="75"
    Width="75"
    StrokeThickness="5"
    Stroke="#FF0000FF"/>
</Canvas>

The following image shows the rendered Ellipse.

Alternatively, you can use property element syntax to explicitly create a SolidColorBrush object to paint the shape with a solid color.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <!-- This polygon shape uses pre-defined color values for its Stroke and
       Fill properties.
       The SolidColorBrush's Opacity property affects the fill color in
       this case by making it slightly transparent (opacity of 0.4) so
       that it blends with any underlying color. -->

  <Polygon
    Points="300,200 400,125 400,275 300,200"
    Stroke="Purple"
    StrokeThickness="2">
    <Polygon.Fill>
       <SolidColorBrush Color="Blue" Opacity="0.4"/>
    </Polygon.Fill>
  </Polygon>

</Canvas>

The following illustration shows the rendered shape.

You can also paint a shape's stroke or fill with gradients, images, patterns, and more. For more information, see the Silverlight Brushes Overview.

Transforming Shapes

Transform objects enable you to transform shapes in a two-dimensional plane. The different types of transformation include rotation (RotateTransform), scale (ScaleTransform), skew (SkewTransform), and translation (TranslateTransform).

A common transform to apply to a shape is a rotation. To rotate a shape, create a RotateTransform and specify its Angle. An Angle of 45 rotates the element 45 degrees clockwise; an angle of 90 rotates the element 90 degrees clockwise; and so on. Set the CenterX and CenterY properties if you want to control the point about which the element is rotated. These property values are expressed in the coordinate space of the element being transformed. CenterX and CenterY have default values of zero. Finally, apply the RotateTransform to the element by setting the shape's RenderTransform property.

In the following example, a RotateTransform is used to rotate a shape 45 degrees about the shape's top left corner (0,0).

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <!-- Rotates the Polyline 45 degrees about the point (0,0). -->
  <Polyline Points="25,25 0,50 25,75 50,50 25,25 25,0"
    Stroke="Blue" StrokeThickness="10"
    Canvas.Left="75" Canvas.Top="50">
    <Polyline.RenderTransform>
      <RotateTransform CenterX="0" CenterY="0" Angle="45" />
    </Polyline.RenderTransform>
  </Polyline>
</Canvas>

To apply multiple transforms to a shape (or any other UI element), use a TransformGroup.

For more information about Transform objects and additional examples, see the Silverlight Transforms Overview.

See Also

Silverlight Brushes Overview
Path Markup Syntax
Silverlight Geometries Overview
Silverlight Transforms Overview
Animation Overview


Silverlight Brushes Overview

This topic describes how to use Silverlight brush objects to paint with solid colors, linear gradients, radial gradients, and images.

This topic contains the following sections.

  • Painting an Area with a Solid Color
  • Painting an Area with a Gradient
  • Linear Gradients
  • Radial Gradients
  • Specifying Transparent or Partially Transparent Gradient Stops
  • Painting with Images
  • Painting with Video
  • Related Topics

Painting an Area with a Solid Color

One of the most common operations in any platform is to paint an area with a solid color. To accomplish this task, Silverlight provides the SolidColorBrush class. The following sections describe the different ways to paint with a SolidColorBrush.

To paint an area with a solid color in XAML, use one of the following options:

  • Select a predefined SolidColorBrush by name. For example, you can set the Fill of a Rectangle to "Red" or "MediumBlue". The example uses the name of a predefined SolidColorBrush to set the Fill of a Rectangle.

    XAML
    <Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <!-- This rectangle's fill is painted with a red SolidColorBrush,
       described using a named color. -->
  <Rectangle Width="100" Height="100" Fill="Red" />
</Canvas>

  • Choose a color from the 32-bit color palette by specifying the amounts of red, green, and blue to combine into a single solid color. The format for specifying a color from the 32-bit palette is #rrggbb, where rr is a two digit hexadecimal number specifying the relative amount of red, gg specifies the amount of green, and bb specifies the amount of blue. Additionally, the color can be specified as #aarrggbb, where aa specifies the alpha value, or transparency, of the color. This approach enables you to create colors that are partially transparent. In the following example, the Fill of a Rectangle is set to fully opaque red using hexadecimal notation.

    XAML
    <Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <!-- This rectangle's background is painted with a red SolidColorBrush,
       described using hexadecimal notation. -->
  <Rectangle Width="100" Height="100" Fill="#FFFF0000" />
</Canvas>

  • Use property element syntax to describe a SolidColorBrush. This syntax is more verbose but enables you to specify additional settings, such as the brush's opacity. In the following example, the Fill properties of two Rectangle elements are set to fully opaque red. The first brush's color is described using a predefined color name. The second brush's color is described using hexadecimal notation.

    XAML
    <Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <!-- Both of these rectangles' fills are painted with red
       SolidColorBrush objects, described using object element
       syntax. -->
  <Rectangle Width="100" Height="100">
    <Rectangle.Fill>
      <SolidColorBrush Color="Red" />
    </Rectangle.Fill>
  </Rectangle>

  <Rectangle Width="100" Height="100" Canvas.Top="110">
    <Rectangle.Fill>
      <SolidColorBrush Color="#FFFF0000" />
    </Rectangle.Fill>
  </Rectangle>
</Canvas>

Painting an Area with a Gradient

A gradient brush paints an area with multiple colors that blend into each other along an axis. You can use them to create impressions of light and shadow, giving your UI elements a three-dimensional feel. You can also use them to simulate glass, chrome, water, and other smooth surfaces. Silverlight provides two types of gradient brushes: LinearGradientBrush and RadialGradientBrush.

Linear Gradients

A LinearGradientBrush paints an area with a gradient defined along a line, the gradient axis. You specify the gradient's colors and their location along the gradient axis using GradientStop objects. You can also modify the gradient axis, which enables you to create horizontal and vertical gradients and reverse the gradient direction. The gradient axis is described in the next section. By default, a diagonal gradient is created.

The following example creates a linear gradient with four colors and uses it to paint a Rectangle.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <!-- This rectangle is painted with a diagonal linear gradient. -->
  <Rectangle Width="200" Height="100">
    <Rectangle.Fill>
      <LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
        <GradientStop Color="Yellow" Offset="0.0" />
        <GradientStop Color="Red" Offset="0.25" />
        <GradientStop Color="Blue" Offset="0.75" />
        <GradientStop Color="LimeGreen" Offset="1.0" />
      </LinearGradientBrush>
    </Rectangle.Fill>
  </Rectangle>
</Canvas>

This code produces the following gradient:

A diagonal linear gradient

The GradientStop is the basic building block of a gradient brush. A gradient stop specifies a Color at an Offset along the gradient axis.

  • The gradient stop's Color property specifies the color of the gradient stop. You may set the color by using a predefined color or by specifying ScRGB or hexadecimal ARGB values.

  • The gradient stop's Offset property specifies the position of the gradient stop's color on the gradient axis. The offset is a Double that ranges from 0 to 1. The closer a gradient stop's offset value is to 0, the closer the color is to the start of the gradient. The closer the gradient's offset value is to 1, the closer the color is to the end of the gradient.

The color of each point between gradient stops is linearly interpolated as a combination of the color specified by the two bounding gradient stops. The following illustration highlights the gradient stops in the previous example. The circles mark the position of gradient stops, and a dashed line shows the gradient axis.

Gradient stops in a linear gradient

The first gradient stop specifies the color yellow at an offset of 0.0. The second gradient stop specifies the color red at an offset of 0.25. The points between these two stops gradually change from yellow to red as you move from left to right along the gradient axis. The third gradient stop specifies the color blue at an offset of 0.75. The points between the second and third gradient stops gradually change from red to blue. The fourth gradient stop specifies the color lime green at an offset of 1.0. The points between the third and fourth gradient stops gradually change from blue to lime green.

The Gradient Axis

As previously mentioned, a linear gradient brush's gradient stops are positioned along a line, the gradient axis. You may change the orientation and size of the line using the brush's StartPoint and EndPoint properties. By manipulating the brush's StartPoint and EndPoint, you can create horizontal and vertical gradients, reverse the gradient direction, condense the gradient spread, and more.

By default, the linear gradient brush's StartPoint and EndPoint are relative to the area being painted. The point (0,0) represents the upper-left corner of the area being painted, and (1,1) represents the lower-right corner of the area being painted. The default StartPoint of a LinearGradientBrush is (0,0), and its default EndPoint is (1,1), which creates a diagonal gradient starting at the upper-left corner and extending to the lower-right corner of the area being painted. The following illustration shows the gradient axis of a linear gradient brush with default StartPoint and EndPoint.

Gradient axis for a diagonal linear gradient

The following example shows how to create a horizontal gradient by specifying the brush's StartPoint and EndPoint. Notice that the gradient stops are the same as in the previous examples; by simply changing the StartPoint and EndPoint, the gradient has been changed from diagonal to horizontal.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <!-- This rectangle is painted with a horizontal linear gradient. -->
  <Rectangle Width="200" Height="100">
    <Rectangle.Fill>
      <LinearGradientBrush StartPoint="0,0.5" EndPoint="1,0.5">
        <GradientStop Color="Yellow" Offset="0.0" />
        <GradientStop Color="Red" Offset="0.25" />
        <GradientStop Color="Blue" Offset="0.75" />
        <GradientStop Color="LimeGreen" Offset="1.0" />
      </LinearGradientBrush>
    </Rectangle.Fill>
  </Rectangle>

</Canvas>

The following illustration shows the resulting gradient. The gradient axis is marked with a dashed line, and the gradient stops are marked with circles.

Gradient axis for a horizontal linear gradient

The next example shows how to create a vertical gradient.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <!-- This rectangle is painted with a vertical linear gradient. -->
  <Rectangle Width="200" Height="100">
    <Rectangle.Fill>
      <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
        <GradientStop Color="Yellow" Offset="0.0" />
        <GradientStop Color="Red" Offset="0.25" />
        <GradientStop Color="Blue" Offset="0.75" />
        <GradientStop Color="LimeGreen" Offset="1.0" />
      </LinearGradientBrush>
    </Rectangle.Fill>
  </Rectangle>

</Canvas>

The following illustration shows the resulting gradient. The gradient axis is marked with a dashed line, and the gradient stops are marked with circles.

Gradient axis for a vertical gradient

Radial Gradients

Like a LinearGradientBrush, a RadialGradientBrush paints an area with colors that blend together along an axis. The previous examples showed how a linear gradient brush's axis is a straight line. A radial gradient brush's axis is defined by a circle; its colors "radiate" outward from its origin.

In the following example, a radial gradient brush is used to paint the interior of a rectangle.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <!-- This rectangle is painted with a radial gradient. -->
  <Rectangle Width="200" Height="100">
    <Rectangle.Fill>
      <RadialGradientBrush GradientOrigin="0.5,0.5" Center="0.5,0.5"
        RadiusX="0.5" RadiusY="0.5">
        <GradientStop Color="Yellow" Offset="0" />
        <GradientStop Color="Red" Offset="0.25" />
        <GradientStop Color="Blue" Offset="0.75" />
        <GradientStop Color="LimeGreen" Offset="1" />
      </RadialGradientBrush>
    </Rectangle.Fill>
  </Rectangle>

</Canvas>

The following illustration shows the gradient created in the previous example. The brush's gradient stops have been highlighted. Notice that, even though the results are different, the gradient stops in this example are identical to the gradient stops in the previous linear gradient brush examples.

Gradient stops in a radial gradient

The GradientOrigin specifies the start point of a radial gradient brush's gradient axis. The gradient axis radiates from the gradient origin to the gradient circle. A brush's gradient circle is defined by its Center, RadiusX, and RadiusY properties.

The following illustration shows several radial gradients with different GradientOrigin, Center, RadiusX, and RadiusY settings.

RadialGradientBrushes with different GradientOrigin, Center, RadiusX, and RadiusY settings.

Specifying Transparent or Partially Transparent Gradient Stops

Because gradient stops do not provide an opacity property, you must specify the alpha channel of colors using ARGB hexadecimal notation or ScRGB notation to create gradient stops that are transparent or partially transparent. The following sections explain how to create partially transparent gradient stops in XAML and code. For information about setting the opacity of the entire brush, see the Specifying the Opacity of a Brush section.

Specifying Color Opacity in XAML

In XAML, one way to specify the opacity of a color is to use ARGB hexadecimal notation. ARGB hexadecimal notation uses the following syntax:

# aa rrggbb

The aa in the previous line represents a two-digit hexadecimal value used to specify the opacity of the color. The rr, gg, and bb each represent a two-digit hexadecimal value used to specify the amount of red, green, and blue in the color. Each hexadecimal digit may have a value from 0 to 9 or A to F. 0 is the smallest value, and F is the greatest. An alpha value of 00 specifies a color that is completely transparent, while an alpha value of FF creates a color that is fully opaque. In the following example, hexadecimal ARGB notation is used to specify two colors. The first is partially transparent (it has an alpha value of x20), while the second is completely opaque.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <Rectangle Width="100" Height="100">
    <Rectangle.Fill>
      <LinearGradientBrush StartPoint="0,0">

        <!-- This gradient stop is partially transparent. -->
        <GradientStop Color="#200000FF" Offset="0.0" />

        <!-- This gradient stop is fully opaque. -->
        <GradientStop Color="#FF0000FF" Offset="1.0" />
      </LinearGradientBrush>
    </Rectangle.Fill>
  </Rectangle>
</Canvas>

Painting with Images

The ImageBrush class enables you to use images as fills, backgrounds, and outlines. An ImageBrush paints an area with a JPG or PNG image specified by its ImageSource property. You set the ImageSource property with the path of the image to load.

By default, an ImageBrush stretches its image to completely fill the area being painted, possibly distorting the image if the painted area has a different aspect ratio than the image. You can change this behavior by changing the Stretch property from its default value of Fill to None, Uniform, or UniformToFill.

The following example uses an ImageBrush to paint the Background of a Canvas.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Height="200" Width="300">
  <Canvas.Background>
    <ImageBrush ImageSource="sampleImages/Forest.jpg" />
  </Canvas.Background>
</Canvas>

Painting with Video

The VideoBrush class enables you to paint an area with video. The following example uses a VideoBrush to paint the Foreground of a TextBlock.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <MediaElement
      x:Name="butterflyMediaElement"
      Source="sampleMedia/Butterfly.wmv" IsMuted="True"
      Opacity="0.0" IsHitTestVisible="False" />

    <TextBlock Canvas.Left="5" Canvas.Top="30"
      FontFamily="Verdana" FontSize="120"
      FontWeight="Bold" TextWrapping="Wrap"
      Text="Video">

        <!-- Paint the text with video. -->
        <TextBlock.Foreground>
          <VideoBrush SourceName="butterflyMediaElement" Stretch="UniformToFill" />
        </TextBlock.Foreground>
    </TextBlock>

</Canvas>

For more information about VideoBrush, see the VideoBrush Overview.

See Also

VideoBrush Overview
Brush
SolidColorBrush
LinearGradientBrush
RadialGradientBrush


Silverlight VideoBrush Overview

A VideoBrush paints an area with video. This topic describes how to use the Silverlight VideoBrush to paint shapes and text with video. It also provides examples showing how to interactively control a VideoBrush.

This topic contains the following sections:

  • Prerequisites
  • Walkthrough: Paint a TextBlock with Video
  • VideoBrush Properties
  • The VideoBrush and MediaElement Relationship
  • Related Topics

Prerequisites

Because a VideoBrush depends on a MediaElement to supply a video stream, you should know how to create a MediaElement and use it to open a media file. For an introduction to the MediaElement, see the Media Overview.

What Is a VideoBrush?

A VideoBrush is a type of Brush object similar to a LinearGradientBrush or an ImageBrush. However, instead of painting an area with a gradient or an image, it paints an area with video content. This video content is provided by a MediaElement. Just like the other brush types, you can use a VideoBrush to paint the Fill of a Rectangle, the Background of a Canvas, or the Foreground of a TextBlock. For more information about the other types of brushes, see the Brushes Overview.

Walkthrough: Paint a TextBlock with Video

To paint an area with video, you create a MediaElement and a VideoBrush and apply that VideoBrush to the object that you want to paint. In this section, you will use VideoBrush and a MediaElement to paint the TextBlock in the following example.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <!-- The text to paint. -->
  <TextBlock
    Canvas.Left="5" Canvas.Top="30"
    FontFamily="Verdana" FontSize="120" FontWeight="Bold"
    Text="Video">
  </TextBlock>

</Canvas>

To paint the TextBlock with a video, complete the following steps.

  1. Create a MediaElement and set its Source property to the uniform resource identifier (URI) of the video you want to display.

    XAML
    <Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <MediaElement
    Source="sampleMedia/Butterfly.wmv"  />

  <!-- The text to paint. -->
  <TextBlock
    Canvas.Left="5" Canvas.Top="30"
    FontFamily="Verdana" FontSize="120" FontWeight="Bold"
    Text="Video">
  </TextBlock>

</Canvas>

  2. Assign a name to the MediaElement.

    XAML
    <Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <MediaElement
    x:Name="myButterflyMediaElement"
    Source="sampleMedia/Butterfly.wmv"  />

  <!-- The text to paint. -->
  <TextBlock
    Canvas.Left="5" Canvas.Top="30"
    FontFamily="Verdana" FontSize="120" FontWeight="Bold"
    Text="Video">
  </TextBlock>

</Canvas>

  3. Create a VideoBrush and use it to set the Foreground property of the TextBlock. (You could also use the VideoBrush to set any other property that accepts a brush value, such as the Fill of a Rectangle or the Background of a Canvas.)

    XAML
    <Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <MediaElement
    x:Name="myButterflyMediaElement"
    Source="sampleMedia/Butterfly.wmv"  />

  <!-- The text to paint. -->
  <TextBlock
    Canvas.Left="5" Canvas.Top="30"
    FontFamily="Verdana" FontSize="120" FontWeight="Bold"
    Text="Video">
    <TextBlock.Foreground>
      <VideoBrush />
    </TextBlock.Foreground>
  </TextBlock>

</Canvas>

  4. Set the SourceName of the VideoBrush to the name you assigned to the MediaElement in step 2. The text in the TextBox ("video") is now filled with video content.

    XAML
    <Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <MediaElement
    x:Name="myButterflyMediaElement"
    Source="sampleMedia/Butterfly.wmv"  />

  <!-- The text to paint. -->
  <TextBlock
    Canvas.Left="5" Canvas.Top="30"
    FontFamily="Verdana" FontSize="120" FontWeight="Bold"
    Text="Video">
    <TextBlock.Foreground>
      <VideoBrush SourceName="butterflyMediaElement" />
    </TextBlock.Foreground>
  </TextBlock>

</Canvas>

  5. The example now displays two copies of the video: once from the MediaElement you created in step 1 and once from the VideoBrush you just created. To display just one copy of the video, set the Opacity of the MediaElement to 0. To turn off the MediaPlayer object's audio output, set its IsMuted property to true.

    XAML
    <Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <MediaElement
      x:Name="butterflyMediaElement"
      Source="sampleMedia/Butterfly.wmv" IsMuted="True"
      Opacity="0.0" IsHitTestVisible="False" />

    <TextBlock Canvas.Left="5" Canvas.Top="30"
      FontFamily="Verdana" FontSize="120"
      FontWeight="Bold" TextWrapping="Wrap"
      Text="Video">

        <!-- Paint the text with video. -->
        <TextBlock.Foreground>
          <VideoBrush SourceName="butterflyMediaElement" Stretch="UniformToFill" />
        </TextBlock.Foreground>
    </TextBlock>

</Canvas>

VideoBrush Properties

In addition to the properties it inherits for being a type of Brush (such as Opacity and RelativeTransform), VideoBrush provides the following additional properties:

  • SourceName:
    The name of the MediaElement that supplies the brush's video.
  • Stretch:
    One of the following values that describe how the video content is stretched to fit the painted area: None, Stretch, Uniform, and UniformToFill. The default value is Stretch.

For more information on its other properties, see the VideoBrush object reference page.

The VideoBrush and MediaElement Relationship

The VideoBrush object's current video frame is determined by its MediaElement. The following diagram depicts the relationship between a MediaElement and a VideoBrush.

Note that when a MediaElement loads media and that that MediaElement is used by a VideoBrush as its SourceName, the video referenced as the MediaElement Source is downloaded and decoded only once. You do not suffer significant performance penalties by using a MediaElement and VideoBrush together, even if you choose to have both the MediaElement and VideoBrush display the video.

By pausing or stopping the MediaElement, you pause or stop the VideoBrush. The following example pauses, stops, and plays a VideoBrush by manipulating its MediaElement source.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <MediaElement
      x:Name="butterflyMediaElement"
      Source="sampleMedia/Butterfly.wmv" IsMuted="True"
      Opacity="0.0" IsHitTestVisible="False" />

    <TextBlock Canvas.Left="5" Canvas.Top="30"
      FontFamily="Verdana" FontSize="120"
      FontWeight="Bold" TextWrapping="Wrap"
      Text="Video">

        <!-- Paint the text with video. -->
        <TextBlock.Foreground>
          <VideoBrush SourceName="butterflyMediaElement" Stretch="UniformToFill" />
        </TextBlock.Foreground>
    </TextBlock>

  <Canvas Canvas.Left="5" Canvas.Top="200">

    <!-- Play -->
    <Canvas Width="120" Height="20"
      MouseLeftButtonDown="playMedia" Background="Transparent">
      <Rectangle Width="120" Height="20" Stroke="Gray" StrokeThickness="2" />
      <TextBlock Canvas.Left="10" Text="play" />
    </Canvas>

    <!-- Pause -->
    <Canvas Width="120" Height="20" Canvas.Left="130"
      MouseLeftButtonDown="pauseMedia" Background="Transparent">
      <Rectangle  Width="120" Height="20" Stroke="Gray" StrokeThickness="2" />
      <TextBlock Canvas.Left="10" Text="pause" />
    </Canvas>

    <!-- Stop -->
    <Canvas Width="120" Height="20" Canvas.Left="260"
      MouseLeftButtonDown="stopMedia" Background="Transparent">
      <Rectangle Width="120" Height="20" Stroke="Gray" StrokeThickness="2" />
      <TextBlock Canvas.Left="10" Text="stop" />
    </Canvas>
  </Canvas>

</Canvas>
JavaScript
function stopMedia(sender, args) {
    sender.findName("butterflyMediaElement").stop();
}

function pauseMedia(sender, args) {
    sender.findName("butterflyMediaElement").pause();
}

function playMedia(sender, args) {
    sender.findName("butterflyMediaElement").play();
}

Although the preceding illustration only shows a single VideoBrush, it ss possible for multiple VideoBrush objects to share the same MediaElement.

Although pausing, stopping, or playing a MediaElement affects its VideoBrush, some MediaElement operations and settings have no effect on the VideoBrush. The following MediaElement methods and properties also manipulate a VideoBrush:

  • Play
  • Pause
  • Stop
  • Position

The following MediaElement methods and properties do not affect VideoBrush:

  • Clip
  • Height
  • IsHitTestVisible
  • Opacity
  • Stretch
  • Transform
  • Width

See Also

Brushes Overview
Media Overview
MediaElement
VideoBrush


Silverlight Geometries Overview

This overview describes how to use the Silverlight Geometry objects to define shapes. It also contrasts Geometry objects and Shape elements.

This topic contains the following sections:

  • What Is a Geometry?
  • Geometries vs. Shapes
  • Common Properties that Take a Geometry
  • Simple Geometry Types
  • Path Geometries
  • Composite Geometries
  • Related Topics

What Is a Geometry?

Geometry objects, such as EllipseGeometry, PathGeometry, and GeometryGroup, enable you to describe the geometry of a two-dimensional (2-D) shape. These geometric descriptions have several uses, such defining a shape to paint to the screen or defining clip regions. Geometry objects can be simple (such as rectangles and circles) or composite (created from two or more Geometry objects). More complex geometries can be created by using the PathGeometry objects, which enable you to describe arcs and curves.

Geometries vs. Shapes

The Geometry and Shape classes seem similar in that they both describe 2-D shapes (compare EllipseGeometry and Ellipse for example), but there are important differences. For one, Shape objects are UIElement objects, but Geometry objects are not. Because they are UIElement objects, Shape objects can render themselves and have Opacity, OpacityMask, and other graphical properties that Geometry objects lack. Although Shape objects are more readily usable than Geometry objects, Geometry objects are more versatile.

One Shape, the Path class, actually uses a Geometry to describe its contents. By setting the Data property of the Path with a Geometry and setting its Fill and Stroke properties, you can render a Geometry.

Common Properties that Take a Geometry

The following table lists several properties that take a Geometry object.

Type | Property
Path | Data
UIElement | Clip

Simple Geometry Types

Geometry objects can be roughly grouped into three categories: simple geometries, path geometries, and composite geometries.

Simple geometry classes include LineGeometry, RectangleGeometry, and EllipseGeometry and are used to create basic geometric shapes, such as lines, rectangles, and circles.

  • A LineGeometry is defined by specifying the start point and the end point of the line.

  • A RectangleGeometry is defined with a Rect structure which specifies its relative position and its height and width. You can create a rounded rectangle by setting the RadiusX and RadiusY properties.

  • An EllipseGeometry is defined by a center point, an x-radius and a y-radius.

These same shapes, as well as more complex shapes, can be created using a PathGeometry or by combining geometry objects together, but these classes provide a simpler means for producing these basic geometric shapes.

The following example shows how to create and render a LineGeometry. As noted previously, a Geometry object is unable to draw itself, so the example uses a Path shape to render the line. Because a line has no area, setting the Fill property of the Path would have no effect; instead, only the Stroke and StrokeThickness properties are specified. The following illustration shows the output from the example.

A LineGeometry drawn from (10,20) to (100,130)

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Width="200" Height="200">
  <Path Stroke="Black" StrokeThickness="1" >
    <Path.Data>
      <LineGeometry StartPoint="10,20" EndPoint="100,130" />
    </Path.Data>
  </Path>
</Canvas>

The next example shows how to create and render an EllipseGeometry. The examples sets the Center of the EllipseGeometry is set to the point 50,50 and the x-radius and the y-radius are both set to 50, which creates a circle with a diameter of 100. The interior of the ellipse is painted by assigning a value to the Path element's Fill property, in this case Gold. The following illustration shows the output from the example.

An EllipseGeometry drawn at (50,50)

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <Path Fill="Gold" Stroke="Black" StrokeThickness="1">
    <Path.Data>
      <EllipseGeometry Center="50,50" RadiusX="50" RadiusY="50" />
    </Path.Data>
  </Path>
</Canvas>

The following example shows how to create and render a RectangleGeometry. The position and the dimensions of the rectangle are defined by a Rect structure. The position is 50,50 and the height and width are both 25, which creates a square. The following illustration shows the output of the example.

A RectangleGeometry drawn at 50,50

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <Path Fill="LemonChiffon" Stroke="Black" StrokeThickness="1">
    <Path.Data>
      <RectangleGeometry Rect="50,50,25,25" />
    </Path.Data>
  </Path>
</Canvas>

The following example shows how to use an EllipseGeometry as the clip region for an image. An Image object is defined with a Width of 200 and a Height of 150. An EllipseGeometry with a RadiusX value of 100, a RadiusY value of 75, and a Center value of 100,75 is set to the Clip property of the image. Only the part of the image that is within the area of the ellipse will be displayed. The following illustration shows the output from the example.

An EllipseGeometry used to clip an Image
An Image with and without clipping

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Image
    Source="sampleImages/Waterlilies.jpg"
    Width="200" Height="150">
    <Image.Clip>
      <EllipseGeometry
        RadiusX="100"
        RadiusY="75"
        Center="100,75"/>
    </Image.Clip>
  </Image>
</Canvas>

Path Geometries

The PathGeometry object and the geometry mini-language provide the means to describe multiple complex figures composed of arcs, curves, and lines.

At the heart of a PathGeometry is a collection of PathFigure objects, so named because each figure describes a discrete shape in the PathGeometry. Each PathFigure is itself composed of one or more PathSegment objects, each of which describes a segment of the figure. The following table lists the different types of segments.

Segment Type | Description
ArcSegment | Creates an elliptical arc between two points.
BezierSegment | Creates a cubic Bezier curve between two points.
LineSegment | Creates a line between two points.
PolyBezierSegment | Creates a series of cubic Bezier curves.
PolyLineSegment | Creates a series of lines.
PolyQuadraticBezierSegment | Creates a series of quadratic Bezier curves.
QuadraticBezierSegment | Creates a quadratic Bezier curve.

The segments within a PathFigure are combined into a single geometric shape, with the end point of each segment being the start point of the next segment. The StartPoint property of a PathFigure specifies the point from which the first segment is drawn. Each subsequent segment starts at the end point of the previous segment. For example, a vertical line from 10,50 to 10,150 can be defined by setting the StartPoint property to 10,50 and creating a LineSegment with a Point property setting of 10,150.

The following example creates a simple PathGeometry made up of a single PathFigure with a LineSegment and displays it using a Path element. The PathFigure object's StartPoint is set to 10,20 and a LineSegment is defined with an end point of 100,130. The following illustration shows the PathGeometry created by this example.

A PathGeometry that contains a single LineSegment

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <Path Stroke="Black" StrokeThickness="1">
    <Path.Data>
      <PathGeometry>
        <PathGeometry.Figures>
          <PathFigure StartPoint="10,20">
            <PathFigure.Segments>
              <LineSegment Point="100,130"/>
            </PathFigure.Segments>
          </PathFigure>
        </PathGeometry.Figures>
      </PathGeometry>
    </Path.Data>
  </Path>
</Canvas>

It is worth contrasting this example with the preceding LineGeometry example. The syntax used for a PathGeometry is much more verbose than that used for a simple LineGeometry, and it may make more sense to use the LineGeometry class in this case, but the verbose syntax of the PathGeometry allows for extremely intricate and complex geometric regions.

Geometries of greater complexities can be created by using a combination of PathSegment objects.

The next example uses a BezierSegment, a LineSegment, and an ArcSegment to create shape.

  • The example first creates a cubic Bezier curve by defining four points: a start point, which is the end point of the previous segment, an end point (Point3), and two control points (Point1 and Point2). The two control points of a cubic Bezier curve behave like magnets, attracting portions of what would otherwise be a straight line towards themselves, producing a curve. The first control point, Point1, affects the beginning portion of the curve; the second control point, Point2, affects the ending portion of the curve.
  • The example then adds a LineSegment, which is drawn between the end point of the preceding BezierSegment that preceded it to the point specified by its LineSegment property.
  • The example then adds an ArcSegment, which is drawn from the end point of the preceding LineSegment to the point specified by its Point property. The example also specifies the arc's x- and y-radius (Size), a rotation angle (RotationAngle), a flag indicating how large the angle of the resulting arc should be (IsLargeArc), and a value indicating in which direction the arc is drawn (SweepDirection). The following illustration shows the shape created by this example.
A PathGeometry

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <Path Stroke="Black" StrokeThickness="1" >
    <Path.Data>
      <PathGeometry>
        <PathGeometry.Figures>
          <PathFigure StartPoint="10,50">
            <PathFigure.Segments>
              <BezierSegment
                Point1="100,0"
                Point2="200,200"
                Point3="300,100"/>
              <LineSegment Point="400,100" />
              <ArcSegment
                Size="50,50" RotationAngle="45"
                IsLargeArc="True" SweepDirection="Clockwise"
                Point="200,100"/>
            </PathFigure.Segments>
          </PathFigure>
        </PathGeometry.Figures>
      </PathGeometry>
    </Path.Data>
  </Path>
</Canvas>

Even more complex geometries can be created by using multiple PathFigure objects within a PathGeometry.

The following example creates a PathGeometry with two PathFigure objects, each of which contains multiple PathSegment objects. The PathFigure from the above example and a PathFigure with a PolyLineSegment and a QuadraticBezierSegment are used. A PolyLineSegment is defined with a list of points and the QuadraticBezierSegment is defined with a control point and an end point. The following illustration shows the shape created by this example.

A PathGeometry with multiple figures

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Path Stroke="Black" StrokeThickness="1" >
    <Path.Data>
      <PathGeometry>
        <PathGeometry.Figures>
          <PathFigure StartPoint="10,50">
            <PathFigure.Segments>
              <BezierSegment
                Point1="100,0"
                Point2="200,200"
                Point3="300,100"/>
              <LineSegment Point="400,100" />
              <ArcSegment
                Size="50,50" RotationAngle="45"
                IsLargeArc="True" SweepDirection="Clockwise"
                Point="200,100"/>
            </PathFigure.Segments>
          </PathFigure>

          <PathFigure StartPoint="10,100">
            <PathFigure.Segments>
              <PolyLineSegment Points="50,100 50,150" />
              <QuadraticBezierSegment Point1="200,200" Point2="300,100"/>
            </PathFigure.Segments>
          </PathFigure>
        </PathGeometry.Figures>
      </PathGeometry>
    </Path.Data>
  </Path>
</Canvas>

Path Markup Syntax

Geometry supports a XAML attribute syntax using a special series of move and draw commands. For more information, see Path Markup Syntax.

Composite Geometries

Composite geometry objects can be created using a GeometryGroup. The GeometryGroup object creates an amalgamation of the Geometry objects it contains without combining their area. Any number of Geometry objects can be added to a GeometryGroup. The following example uses a GeometryGroup to create a composite Geometry.

A composite Geometry

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Path Stroke="Black" StrokeThickness="1" Fill="#CCCCFF">
    <Path.Data>

      <!-- Creates a composite shape from three geometries. -->
      <GeometryGroup FillRule="EvenOdd">
        <LineGeometry StartPoint="10,10" EndPoint="50,30" />
        <EllipseGeometry Center="40,70" RadiusX="30" RadiusY="30" />
        <RectangleGeometry Rect="30,55 100 30" />
      </GeometryGroup>
    </Path.Data>
  </Path>
</Canvas>

See Also

Geometry
PathGeometry
Path
Path Markup Syntax
Animation Overview


Path Markup Syntax

This topic describes the Extensible Application Markup Language (XAML) usage syntax for describing paths. Silverlight supports a powerful and complex mini-language that you can use to describe geometric paths.

This topic contains the following sections.

  • Prerequisites
  • The Path Mini-Language
  • Move Command
  • Draw Commands
  • The Close Command
  • Point Syntax
  • Special Values
  • Related Topics

Prerequisites

To understand this topic, you should be familiar with the basic features of Geometry objects. For more information, see the Silverlight Geometries Overview.

The Path Mini-Language

Silverlight provides a mini-language attribute syntax for describing geometric paths. You use this mini-language when setting a property of type Geometry, such as the Clip property of a UIElement or the Data property of a Path element. The following example uses the path attribute syntax to create a shape.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Path Stroke="Black" Fill="Gray"
    Data="M 10,100 C 10,300 300,-200 300,100" />
</Canvas>

A Note about White Space

For brevity, a single space is shown in the syntax sections that follow, but multiple spaces are also acceptable wherever a single space is shown.

Two numbers don't actually have to be separated by a comma or whitespace, but this can only be done when the resulting string is unambiguous. For instance, 2..3 is actually two numbers: "2." And ".3". Similarly, 2-3 is "2" and "-3". Spaces are not required before or after commands, either.

Syntax

The Extensible Application Markup Language (XAML) path syntax is composed of an optional FillRule value and one or more figure descriptions.

Path XAML Attribute Usage

< object property ="[fillRule] figureDescription[figureDescription]*" ... />

Term Description

fillRule

FillRule

Specifies whether the path uses the EvenOdd or NonZero FillRule.

  • F0 specifies the EvenOdd fill rule.

  • F1 specifies the Nonzero fill rule.

If you omit this command, the path uses the default behavior, which is EvenOdd. If you specify this command, you must place it first.

figureDescription

A figure composed of a move command, draw commands, and an optional close command.

moveCommand drawCommands [ closeCommand ]

moveCommand

A move command that specifies the start point of the figure. See the Move Command section.

drawCommands

One or more drawing commands that describe the figure's contents. See the Draw Commands section.

closeCommand

An optional close command that closes figure. See the Close Command section.

Move Command

Specifies the start point of a new figure.

Syntax

M startPoint

- or -

m startPoint

Term | Description
startPoint | Point The start point of a new figure.

An uppercase M indicates that startPoint is an absolute value; a lowercase m indicates that startPoint is an offset to the previous point, or (0,0) if none exists. If you list multiple points after the move command, a line is drawn to those points though you specified the line command.

Draw Commands

A draw command can consist of several shape commands. The following shape commands are available: line, horizontal line, vertical line, cubic Bezier curve, quadratic Bezier curve, smooth cubic Bezier curve, smooth quadratic Bezier curve, and elliptical arc.

You enter each command by using either an uppercase or a lowercase letter: uppercase letters denote absolute values and lowercase letters denote relative values: the control points for that segment are relative to the end point of the preceding example. When sequentially entering more than one command of the same type, you can omit the duplicate command entry; for example, L 100,200 300,400 is equivalent to L 100,200 L 300,400. The following table describes the move and draw commands.

Line Command

Creates a straight line between the current point and the specified end point. l 20 30 and L 20,30 are examples of valid line commands.

Syntax

L endPoint

- or -

l endPoint

Term | Description
endPoint | Point The end point of the line.

Horizontal Line Command

Creates a horizontal line between the current point and the specified x-coordinate. H 90 is an example of a valid horizontal line command.

Syntax

H x

- or -

h x

Term | Description
x | Double The x-coordinate of the end point of the line.

Vertical Line Command

Creates a vertical line between the current point and the specified y-coordinate. v 90 is an example of a valid vertical line command.

Syntax

V y

- or -

v y

Term | Description
y | Double The y-coordinate of the end point of the line.

Cubic Bezier Curve Command

Creates a cubic Bezier curve between the current point and the specified end point by using the two specified control points (controlPoint1 and controlPoint2). C 100,200 200,400 300,200 is an example of a valid curve command.

Syntax

C controlPoint 1 controlPoint 2 endPoint

- or -

c controlPoint 1 controlPoint 2 endPoint

Term | Description
controlPoint 1 | Point The first control point of the curve, which determines the starting tangent of the curve.
controlPoint 2 | Point The second control point of the curve, which determines the ending tangent of the curve.
endPoint | Point The point to which the curve is drawn.

Quadratic Bezier Curve Command

Creates a quadratic Bezier curve between the current point and the specified end point by using the specified control point (controlPoint). q 100,200 300,200 is an example of a valid quadratic Bezier curve command.

Syntax

Q controlPoint endPoint

- or -

q controlPoint endPoint

Term | Description
controlPoint | Point The control point of the curve, which determines the starting and ending tangents of the curve.
endPoint | Point The point to which the curve is drawn.

Smooth cubic Bezier curve Command

Creates a cubic Bezier curve between the current point and the specified end point. The first control point is assumed to be the reflection of the second control point of the previous command relative to the current point. If there is no previous command or if the previous command was not a cubic Bezier curve command or a smooth cubic Bezier curve command, assume the first control point is coincident with the current point. The second control point, the control point for the end of the curve, is specified by controlPoint2. For example, S 100,200 200,300 is a valid smooth cubic Bezier curve command.

Syntax

S controlPoint 2 endPoint

- or -

s controlPoint 2 endPoint

Term | Description
controlPoint 2 | Point The control point of the curve, which determines the ending tangent of the curve.
endPoint | Point The point to which the curve is drawn.

Smooth cubic Bezier curve Command

Creates a quadratic Bezier curve between the current point and the specified end point. The control point is assumed to be the reflection of the control point of the previous command relative to the current point. If there is no previous command or if the previous command was not a quadratic Bezier curve command or a smooth quadratic Bezier curve command, the control point is coincident with the current point.

Syntax

T controlPoint endPoint

- or -

t controlPoint endPoint

Term | Description
controlPoint | Point The control point of the curve, which determines the starting and tangent of the curve.
endPoint | Point The point to which the curve is drawn.

Elliptical Arc Command

Creates an elliptical arc between the current point and the specified end point.

Syntax

A size rotationAngle isLargeArcFlag sweepDirectionFlag endPoint

- or -

a size rotationAngle isLargeArcFlag sweepDirectionFlag endPoint

Term | Description
size | Size The x- and y-radius of the arc.
rotationAngle | Double The rotation of the ellipse, in degrees.
isLargeArcFlag | Set to 1 if the angle of the arc should be 180 degrees or greater; otherwise, set to 0.
sweepDirectionFlag | Set to 1 if the arc is drawn in a positive-angle direction; otherwise, set to 0.
endPoint | Point The point to which the arc is drawn.

The Close Command

Ends the current figure and creates a line that connects the current point to the starting point of the figure. This command creates a line-join (corner) between the last segment and the first segment of the figure.

Syntax

Z

- or -

z

Point Syntax

Describes the x- and y-coordinates of a point.

Syntax

x , y

- or -

x y

Term | Description
x | Double The x-coordinate of the point.
y | Double The y-coordinate of the point.

Special Values

Instead of a standard numerical value, you can also use the following special values. These values are case-sensitive.

Infinity

Represents the positive infinity Double value.

-Infinity

Represents the negative infinity Double value.

NaN

Represents the NaN Double value.

You may also use scientific notation. For example, +1.e17 is a valid value.

See Also

PathGeometry
Silverlight Geometries Overview


Silverlight Transforms Overview

This topic describes how to use the 2-D transform classes to rotate, scale, skew, and move (translate) objects.

  • What Is a Transform?
  • Transform Objects
  • Common Transformation Properties
  • Transformations and Coordinate Systems
  • Animating Transformations
  • Related Topics

What Is a Transform?

A Transform defines how to map, or transform, points from one coordinate space to another coordinate space. This mapping is described by a transformation Matrix, which is a collection of three rows with three columns of Double values.

Note Note:

Silverlight uses row-major matrices. Vectors are expressed as row vectors and not column vectors.

The following table shows the structure of a Silverlight matrix.

A 2-D transformation matrix
M11 Default: 1.0 | M12 Default: 0.0 | 0.0
M21 Default: 0.0 | M22 Default: 1.0 | 0.0
OffsetX Default: 0.0 | OffsetY Default: 0.0 | 1.0

By manipulating matrix values, you can rotate, scale, skew, and move (translate) an object. For example, if you change the value in the first column of the third row (the OffsetX value) to 100, you can use it to move an object 100 units along the x-axis. If you change the value in the second column of the second row to 3, you can use it to stretch an object to three times its current height. If you change both values, you move the object 100 units along the x-axis and stretch its height by a factor of 3. Because Silverlight only supports affine transforms, the values in the right column are always 0,0,1.

Although Silverlight enables you to directly manipulate matrix values, it also provides several Transform classes that enable you to transform an object without knowing how the underlying matrix structure is configured. For example, the ScaleTransform class enables you to scale an object by setting its ScaleX and ScaleY properties instead of manipulating a transformation matrix. Likewise, the RotateTransform class enables you to rotate an object by just setting its Angle property.

Transform Classes

Silverlight provides the following 2-D Transform classes for common transformation operations.

Class | Description | Illustration
RotateTransform | Rotates an element by the specified Angle. | Rotate illustration
ScaleTransform | Scales an element by the specified ScaleX and ScaleY amounts. | Scale illustration
SkewTransform | Skews an element by the specified AngleX and AngleY amounts. | A skew transformation.
TranslateTransform | Moves (translates) an element by the specified X and Y amounts. | Translate illustration

For creating more complex transformations, Silverlight provides the following two classes.

Class | Description
TransformGroup | Groups multiple TransformGroup objects into a single Transform that you can then apply to transform properties.
MatrixTransform | Creates custom transformations that are not provided by the other Transform classes. When you use a MatrixTransform, you manipulate a Matrix directly.

Common Transformation Properties

One way to transform an object is to declare the appropriate Transform type and apply it to the transformation property of the object. Different types of objects have different types of transformation properties. The following table lists several commonly used Silverlight types and their transformation properties.

Type | Transformation properties
Brush | Transform, RelativeTransform
Geometry | Transform
UIElement | RenderTransform

Transformations and Coordinate Systems

When you transform an object, you do not just transform the object, you transform coordinate space in which that object exists. By default, a transform is centered at the origin of the target object's coordinate system (0,0). The only exception is a TranslateTransform, which has no center properties to set because the translation effect is the same regardless of where it is centered.

The following example uses a RotateTransform to rotate a Rectangle element (a type of UIElement) by 45 degrees about its default center (0, 0). The following illustration shows the effect of the rotation.

A Rectangle element rotated 45 degrees about the point (0,0)
A FrameworkElement rotated 45 degrees about (0,0)
XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Width="200" Height="200">
  <Rectangle
    Canvas.Left="100" Canvas.Top="100"
    Width="50" Height="50"
    Fill="RoyalBlue">
    <Rectangle.RenderTransform>
      <RotateTransform Angle="45" />
    </Rectangle.RenderTransform>
  </Rectangle>
</Canvas>

By default, the element rotates about its upper-left corner (0, 0). The RotateTransform, ScaleTransform, and SkewTransform classes provide CenterX and CenterY properties that enable you to specify the point at which the transform is applied.

The next example also uses a RotateTransform to rotate a Rectangle element by 45 degrees; however, this time the CenterX and CenterY properties are set so that the RotateTransform has a center of 25,25. The following illustration shows the effect of the rotation.

A Rectangle element rotated 45 degrees about the point (25, 25)
A Geometry rotated 45 degrees about (25, 25)
XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Width="200" Height="200">
  <Rectangle
    Canvas.Left="100" Canvas.Top="100"
    Width="50" Height="50"
    Fill="RoyalBlue">
    <Rectangle.RenderTransform>
      <RotateTransform Angle="45" CenterX="25" CenterY="25" />
    </Rectangle.RenderTransform>
  </Rectangle>
</Canvas>

Animating Transformations

Transform objects can be animated. To animate a Transform, apply an animation of a compatible type to the property you want to animate.

The following example uses a Storyboard and a DoubleAnimation with a RotateTransform to make a Rectangle spin in place.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Width="200" Height="200">
  <Rectangle
    Canvas.Left="100" Canvas.Top="100"
    Width="50" Height="50"
    Fill="RoyalBlue">
    <Rectangle.RenderTransform>
      <RotateTransform x:Name="myTransform" Angle="45" CenterX="25" CenterY="25" />
    </Rectangle.RenderTransform>
    <Rectangle.Triggers>
      <EventTrigger RoutedEvent="Rectangle.Loaded">
        <BeginStoryboard>
          <Storyboard>
            <DoubleAnimation
              Storyboard.TargetName="myTransform"
              Storyboard.TargetProperty="Angle"
              From="0" To="360" Duration="0:0:5" RepeatBehavior="Forever" />
          </Storyboard>
        </BeginStoryboard>
      </EventTrigger>
    </Rectangle.Triggers>
  </Rectangle>
</Canvas>

For more information about animations, see the Animation Overview.

See Also

Transform
Matrix


Silverlight Media

The overviews in this section describe the audio and video features of Microsoft Silverlight.

  • Media Overview: Introduces the multimedia features of Silverlight, and describes how to integrate sound and video into your Silverlight pages.

  • Supported Media Formats and Protocols: Describes the formats and protocols supported by the MediaElement object. It also describes the MediaElement object's support for streaming and stream selection.

See Also

Introduction to Silverlight 1.0
Silverlight Architecture
What Changed Between Beta and Release of Silverlight 1.0
Silverlight 1.0 QuickStarts


Media Overview

This topic introduces the multimedia features of Silverlight and describe how to integrate sound and video into your Silverlight pages.

This topic contains the following sections.

  • The MediaElement Object
  • MediaElement Properties
  • Control Media Playback Interactively
  • Timeline Markers (Synchronization Points)
  • Related Topics

The MediaElement Object

Adding media to a page is as simple as adding a MediaElement to your markup and providing a Uri to the media to play. The following example creates a MediaElement and sets its Source to property to the Uri of a video file. The MediaElement begins playing when the page loads.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Width="300" Height="300">

  <MediaElement x:Name="media" Source="xbox.wmv"
    Width="300" Height="300" />

</Canvas>

The MediaElement can play Windows Media Video (WMV), Windows Media Audio (WMA), and MP3 files. For a detailed list of the formats and protocols supported, see the Media Formats Overview.

MediaElement Properties

The MediaElement class provides several media-specific properties. The following list describes a few of these properties.

  • AutoPlay: Specifies whether the MediaElement should begin playing automatically. The default value is True.
  • IsMuted: Specifies whether the MediaElement is silenced. A value of True mutes the MediaElement. The default value is False.
  • Stretch: Specifies how video is stretched to fill the MediaElement. Possible values are None, Uniform, UniformToFill, and Fill. The default is Fill. For more information, see the Stretch enumeration.
  • Volume: Specifies the volume of the MediaElement object's audio as a value from 0 to 1, with 1 being the loudest. The default value is 0.5.

In addition to its media-specific properties, MediaElement also has all the properties of a UIElement, such as Opacity and Clip. For a complete list of MediaElement properties, see the MediaElement reference page.

Control Media Playback Interactively

You can interactively control media playback by using the Play, Pause, and Stop methods of a MediaElement. The following example defines a MediaElement and several "buttons" for controlling media playback.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Width="300" Height="300">

  <MediaElement x:Name="media" Source="xbox.wmv" Width="300" Height="300"
    CurrentStateChanged="media_state_changed" />

  <!-- Stops media playback.-->
  <Canvas MouseLeftButtonDown="media_stop"
    Canvas.Left="10" Canvas.Top="265">
    <Rectangle Stroke="Black"
      Height="30" Width="55" RadiusX="5" RadiusY="5">
      <Rectangle.Fill>
        <RadialGradientBrush GradientOrigin="0.75,0.25">
          <GradientStop Color="Orange" Offset="0.0" />
          <GradientStop Color="Red" Offset="1.0" />
        </RadialGradientBrush>
      </Rectangle.Fill>
    </Rectangle>
    <TextBlock Canvas.Left="5" Canvas.Top="5">stop</TextBlock>
  </Canvas>

  <!-- Pauses media playback. -->
  <Canvas MouseLeftButtonDown="media_pause"
    Canvas.Left="70" Canvas.Top="265">
    <Rectangle Stroke="Black"
      Height="30" Width="55" RadiusX="5" RadiusY="5">
      <Rectangle.Fill>
        <RadialGradientBrush GradientOrigin="0.75,0.25">
          <GradientStop Color="Yellow" Offset="0.0" />
          <GradientStop Color="Orange" Offset="1.0" />
        </RadialGradientBrush>
      </Rectangle.Fill>
    </Rectangle>
    <TextBlock Canvas.Left="5" Canvas.Top="5">pause</TextBlock>
  </Canvas>

  <!-- Begins media playback. -->
  <Canvas MouseLeftButtonDown="media_begin"
    Canvas.Left="130" Canvas.Top="265">
    <Rectangle Stroke="Black" RadiusX="5" RadiusY="5"
      Height="30" Width="55">
      <Rectangle.Fill>
        <RadialGradientBrush GradientOrigin="0.75,0.25">
          <GradientStop Color="LimeGreen" Offset="0.0" />
          <GradientStop Color="Green" Offset="1.0" />
        </RadialGradientBrush>
      </Rectangle.Fill>
    </Rectangle>
    <TextBlock Canvas.Left="5" Canvas.Top="5">play</TextBlock>
  </Canvas>
</Canvas>

The accompanying code behind creates several event handlers and uses the Stop, Pause, and Play methods to control the MediaElement.

JavaScript
function media_stop(sender, args) {

    sender.findName("media").stop();
}

function media_pause(sender, args) {

    sender.findName("media").pause();
}

function media_begin(sender, args) {

    sender.findName("media").play();
}

(For more information about retrieving and manipulation Silverlight objects, see Reference and Modifying Silverlight Objects.)

In addition to stopping, pausing, or playing media, you can also seek to a specific position by setting the Position property of a MediaElement.

Timeline Markers (Synchronization Points)

A timeline marker is metadata associated with a particular point in a media file. These markers are usually created ahead of time and stored in the media file itself. They are typically used to name different scenes in a video, enable users to seek to a selected position, or provide scripting cues.

When the MediaElement reaches a timeline marker during playback, it raises the MarkerReached event. By handling this event, your code can use timeline markers to trigger actions. A MediaElement object's Markers property enables you to access the header-embedded markers stored in the currently playing media file. You can also use this property to add new timeline markers.

Although the MediaElement object supports all windows media technology markers (markers, and metadata script commands, and separate-stream script commands), the collection returned from the Markers property does not include any timeline markers encoded as a separate stream in the media file, such as separate-stream script commands. If a file contains both header-embedded script commands and separate-stream script commands, this collection only contains those embedded in the file header. Separate-stream script commands do trigger the MarkerReached event when encountered during media playback. However these markers are not accessible ahead of time using the Markers property.

MediaElement uses TimelineMarker objects to represent the collection of markers returned by the Markers property. The TimelineMarker object provides the following properties, which describe its time, name, and value.

  • Time: A TimeSpan object that specifies the time when the marker is reached.
  • Type: A string that specifies the marker's type. This value can be any user-defined string.
  • Text: A string that specifies the marker's value. This value can be any user-defined string.

The following example creates a MediaElement and registers for the MarkerReached event. It also creates several TextBlock objects.

XAML
  <MediaElement x:Name="media"
    Canvas.Top="50"
    MarkerReached="onMarkerReached" Source="thebutterflyandthebear.wmv"
    Width="300" Height="200" />

  <Canvas Canvas.Left="10" Canvas.Top="5">
    <TextBlock
      FontSize="12" Foreground="DarkGray">Time:</TextBlock>
    <TextBlock x:Name="timeTextBlock"
      Canvas.Left="40"
      FontSize="12" />
    <TextBlock Canvas.Top="12"
      FontSize="12" Foreground="DarkGray">Type:</TextBlock>
    <TextBlock x:Name="typeTextBlock"
      Canvas.Left="40" Canvas.Top="12"
      FontSize="12" />
    <TextBlock
      Canvas.Top="24"
      FontSize="12" Foreground="DarkGray">Value:</TextBlock>
    <TextBlock x:Name="valueTextBlock"
      Canvas.Left="40" Canvas.Top="24"
      FontSize="12" />

  </Canvas>

The JavaScript code-behind handles the MarkerReached event. It retrieves the Time, Type, and Text values of the timeline marker that triggered the event and displays that information in the TextBlock objects declared in the preceding markup.

JavaScript
function onMarkerReached(sender, markerEventArgs)
{

  sender.findName("timeTextBlock").Text =
      markerEventArgs.marker.time.seconds.toString();

  sender.findName("typeTextBlock").Text =
       markerEventArgs.marker.type;

  sender.findName("valueTextBlock").Text =
       markerEventArgs.marker.text;

}

Defining Media Markers

There are two ways to create media markers. The first is to use an editor such as the Windows Media File Editor (installed as part of the Windows Media Encoder 9 installation) or Microsoft Expression Media Encoder to create markers and save them in the media file itself or a separate stream. The following screen shots shows the Windows Media File Editor displaying the script commands (a type of marker) associated with a media file.

Windows Media File Editor

The other approach is to dynamically generate new TimelineMarker objects and add them to the MediaElement through its Markers property. These timeline markers are temporary and are not saved in the media file. Any such timeline markers you create disappear each time a new media file is loaded by that MediaElement. Note that using this approach requires that you use JavaScript to add the TimelineMarker objects (see example below).

The following example creates a new timeline marker and adds it to the MediaElement whenever a media file is opened.

XAML
  <MediaElement x:Name="media"
    Canvas.Top="50"
    MediaOpened="onMediaOpened"
    MarkerReached="onMarkerReached" Source="thebutterflyandthebear.wmv"
    Width="300" Height="200" />
JavaScript
function onMediaOpened(sender, eventArgs)
{

    var marker =
         sender.getHost().content.createFromXaml
         (
              '<TimelineMarker Time="0:0:5" Type="Test" Text="New Marker" />'
         );
    sender.markers.add(marker);

}

See Also

Reference

MediaElement Object

Conceptual

Supported Media Formats and Protocols


Supported Media Formats and Protocols

This topic describes the formats and protocols supported by the MediaElement object. It also describes the MediaElement object's support for streaming and stream selection.

This topic contains the following sections.

  • Supported Formats
  • Unsupported Formats
  • Supported Protocols
  • Streaming
  • Stream Selection in MBR Files
  • Proxy Servers and Streaming in Silverlight
  • Related Topics

Supported Formats

The MediaElement object supports the following formats. These encodings are supported regardless of the file's extension.

Video:

  • WMV1: Windows Media Video 7
  • WMV2: Windows Media Video 8
  • WMV3: Windows Media Video 9
  • WMVA: Windows Media Video Advanced Profile, non-VC-1
  • WMVC1: Windows Media Video Advanced Profile, VC-1

Audio:

  • WMA 7: Windows Media Audio 7
  • WMA 8: Windows Media Audio 8
  • WMA 9: Windows Media Audio 9
  • MP3: ISO/MPEG Layer-3
    • Input: ISO/MPEG Layer-3 data stream
    • Channel configurations: mono, stereo
    • Sampling frequencies: 8, 11.025, 12, 16, 22.05, 24, 32, 44.1, and 48 kHz
    • Bit rates: 8-320 kbps, variable bit rate
    • Limitations: "free format mode" (see ISO/IEC 11172-3, sub clause 2.4.2.3) is not supported.

Other formats

MediaElement also supports playlists in the form of Advanced Stream Redirector (ASX) files, also known as Windows Media Metafiles. Although the file extension does not matter, these files typically have a .asx, .wax, .wvx, .wmx, or .wpl extension. For more information about these file types, please see Windows Media Metafiles.

Note: The following features of ASX files are not supported in Silverlight:

ASX Feature | Description
PreviewMode Attribute | This attribute is found on the root ASX object. This is not supported and will raise a MediaError with AG_E_ASX_UNSUPPORTED_ATTRIBUTE.
BannerBar Attribute | This attribute is found on the root ASX object. This is not supported and will raise a MediaError with AG_E_ASX_UNSUPPORTED_ATTRIBUTE.
SkipIfRef | This attribute is found on the root ENTRY object. This is not supported and will raise a MediaError with AG_E_ASX_UNSUPPORTED_ATTRIBUTE.
PARAM Element | This is not supported and will raise a MediaError with AG_E_ASX_UNSUPPORTED_ELEMENT.
REPEAT Element | This is not supported and will raise a MediaError with AG_E_ASX_UNSUPPORTED_ELEMENT.
EVENT Element | This is not supported and will raise a MediaError with AG_E_ASX_UNSUPPORTED_ELEMENT.
STARTMARKER Element | This is not supported and will raise a MediaError with AG_E_ASX_UNSUPPORTED_ELEMENT.
ENDMARKER Element | This is not supported and will raise a MediaError with AG_E_ASX_UNSUPPORTED_ELEMENT.
Invalid content | If a valid ASX tag has content that is not accepted (e.g. MOREINFO tag as content of a REF tag), a MediaFailed error is raised.
Fallback URLs | If an ENTRY tag has multiple REF children, only the first one is read. Unlike WMP, Silverlight will not attempt to open additional REF URLs in case the first one fails, and a MediaFailed error is raised.

For more information on ASX elements, see ASX Elements Reference.

Unsupported Formats

The following formats are not supported.

  • Interlaced video content
  • Windows Media Screen
  • Windows Media Audio Professional
  • Windows Media Voice
  • Combination of Windows Media Video and MP3 (WMV video + MP3 audio)
  • Windows Media Video using odd (not divisible by two) dimensioned frames. For example, 127 x 135.

Supported Protocols

The following web protocols are supported.

  • http
  • https
  • mms (You can use an mms URL but it will fall back to http.)
  • rtsp (You can use an rtsp URL but it will fall back to http.)
  • rstpt (You can use an rtspt URL but it will fall back to http.)

Streaming

In addition to progressive downloads, MediaElement supports live and on-demand streaming from a Windows Media Server. If the file URI specifies the mms protocol, the MediaElement attempts to stream the file first. If the file can't be streamed, it downloads the file progressively. If the file URI specifies another protocol, such as http or https, the MediaElement attempts a progressive download first. If that fails, the MediaElement attempts to stream the file.

Note that live streaming media cannot be paused--calling the Pause method has no effect.

To find out more about the differences between streaming and progressive downloading, see Key Concepts in Windows Media Technologies.

Stream Selection and MBR Files

MediaElement supports multiple bit rate (MBR) files. When streaming media, the MediaElement automatically selects the appropriate stream for the bandwidth available. For progressively downloaded or local media, the MediaElement always selects the stream with the highest bit rate. For more information about multiple bit rate files, see Using Multiple Bit Rate Mutual Exclusion.

Proxy Servers and Streaming in Silverlight

In networks where a proxy server exists, special settings on the client may be required before streaming will work in Silverlight. In general, Silverlight only looks at system settings in order to make a decision about proxy server configuration, so specifying a proxy setting in Firefox will not affect the way streaming works in either Windows or Mac platforms.

Windows
End-users need to make sure they have the correct proxy settings under “Internet Options”. This can be accessed through IE, or directly from the Control Panel. In Windows, users should be able to use automatic proxy detection, specify a configuration script, or manually specify the proxy server IP address in order to enable streaming in Silverlight. As a result, as long as users are able to browse the web using IE, they can be guaranteed that streaming in Silverlight will work correctly. Even if users are able to browse the web using Firefox (meaning Firefox proxy settings are correct), there is a chance that streaming will not work if the system settings are not also correct.

Mac
End-users need to make sure they manually specify the proxy server’s IP address under “Network Preferences”. This can be accessed through Safari, or directly from System Preferences. Unlike Windows, specifying a PAC configuration script for the proxy server is not supported in Silverlight 1.0. As a result, there is a chance that a user is able to browse the web correctly, without being able to stream media in Silverlight. This could happen if the system settings are using a configuration script for proxy detection, or if the system settings are incorrect but Firefox is being used (and Firefox proxy settings are correct).

See Also

Reference

MediaElement

Conceptual

Key Concepts in Windows Media Technologies

Media Overview

Windows Media Metafiles


Silverlight Animation

The overviews in this section describe the Microsoft Silverlight animation system.

  • Animation Overview: Provides an introduction to the Silverlight animation system, which enables you to enhance your applications by adding movement and interactivity.

  • Interactive Animations Overview: Describes how to interactively control Storyboard animations, and how to declare Storyboard animations as resources to prevent them from playing automatically.

  • Key-Frame Animations Overview: Introduces key-frame animations, which enable you to animate by using more than two target values, and explains how to control an animation's interpolation method.

See Also

Introduction to Silverlight 1.0
Silverlight Architecture
What Changed Between Beta and Release of Silverlight 1.0
Silverlight 1.0 QuickStarts


Animation Overview

Animation can enhance your graphical creation by adding movement and interactivity. By animating a background color or applying an animated Transform, you can create dramatic screen transitions or provide helpful visual cues. This overview provides an introduction to the Silverlight animation system.

This topic contains the following sections.

  • Introducing Animations
  • Example: Make an Element Fade In and Out of View
  • Animation Types
  • Applying an Animation to a Property
  • Interactive Animations
  • What Happens After an Animation Ends?
  • Related Topics

Introducing Animations

Animation is an illusion that is created by quickly cycling through a series of images, each slightly different from the last. The brain perceives the group of images as a single changing scene. In film, this illusion is created by using cameras that record many photographs, or frames, each second. When the frames are played back by a projector, the audience sees a moving picture. Silverlight, you animate objects by applying animation to their individual properties. For example, to make a UIElement grow, you animate its Width and Height properties. To make a UIElement fade from view, you animate its Opacity property. Silverlight contains many objects that have properties that can be animated.

The next section shows how to create a simple animation that makes a Rectangle , a type of UIElement, fade in and out of view.

Example: Make a UIElement Fade In and Out of View

This example shows how to use a Silverlight animation to make a Rectangle fade in and out of view by animating a property value. It uses a DoubleAnimation, which is a type of animation that generates Double values, to animate the Opacity property of a Rectangle. As a result, the Rectangle fades in and out of view.

The first part of the example creates a Rectangle element and displays it in a Canvas.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Rectangle
    x:Name="MyAnimatedRectangle"
    Width="100"
    Height="100"
    Fill="Blue">
  </Rectangle>
</Canvas>

The steps that follow show how to create an animation and apply it to the rectangle's Opacity property.

Part 1: Create a DoubleAnimation

Because the Opacity property is of type Double, you need an animation that produces Double values. A DoubleAnimation is one such animation: it creates a transition between two Double values. To specify its starting value, you set its From property. To specify its ending value, you set its To property.

  1. An opacity value of 1.0 makes the object completely opaque, and an opacity value of 0.0 makes it completely invisible. To make the animation transition from 1.0 to 0.0 you set its From property to 1.0 and its To property to 0.0.

    XAML
    ...
<DoubleAnimation From="1.0" To="0.0"  />
...

  2. Specify a Duration for the animation. The Duration property of an animation specifies how long it takes to go from its starting value to its destination value. The following example sets the duration of the animation to five seconds.

    XAML
    ...
<DoubleAnimation From="1.0" To="0.0" Duration="0:0:5" />
...

  3. The preceding example creates an animation that transitions from 1.0 to 0.0, which causes the target element to fade from completely opaque to completely invisible. To make the element fade back into view after it vanishes, set its AutoReverse property to true. To make the animation repeat indefinitely, set its RepeatBehavior property to Forever.

    XAML
    ...
<DoubleAnimation From="1.0" To="0.0" Duration="0:0:5" AutoReverse="True" RepeatBehavior="Forever"/>
...

Part 2: Create a Storyboard

To apply an animation to an object, you create a Storyboard and use the Storyboard.TargetName and Storyboard.TargetProperty attached properties to specify the object and property to animate.

  1. Create the Storyboard and add the animation as its child.

    XAML
    ...
<Storyboard>
  <DoubleAnimation From="1.0" To="0.0" Duration="0:0:1" AutoReverse="True" RepeatBehavior="Forever" />
</Storyboard>
...

    Although the Storyboard in this example only contains a single animation, you may add multiple animations.

  2. The Storyboard has to know where to apply the animation. Use the Storyboard.TargetName attached property to specify the object to animate. In the following code, the DoubleAnimation is given a target name of myAnimatedRectangle, which is the name of the object to animate.

    XAML
    ...
<Storyboard>
  <DoubleAnimation
    Storyboard.TargetName="MyAnimatedRectangle"
    From="1.0" To="0.0" Duration="0:0:1" AutoReverse="True" RepeatBehavior="Forever" />
</Storyboard>
...

  3. Use the Storyboard.TargetProperty attached property to specify the property to animate. In the following code, the animation is configured to target the Opacity property of a Rectangle.

    XAML
    ...
<Storyboard>
  <DoubleAnimation
    Storyboard.TargetName="MyAnimatedRectangle"
    Storyboard.TargetProperty="Opacity"
    From="1.0" To="0.0" Duration="0:0:1" AutoReverse="True" RepeatBehavior="Forever" />
</Storyboard>
...

Part 3: Associate the Storyboard with a Trigger

To set the animation to start automatically, use an event trigger.

  1. Create a BeginStoryboard object and associate your storyboard with it. A BeginStoryboard is a trigger action that applies and starts a Storyboard.

    XAML
    ...
<BeginStoryboard>
  <Storyboard>
    <DoubleAnimation
      Storyboard.TargetName="MyAnimatedRectangle"
      Storyboard.TargetProperty="Opacity"
      From="1.0" To="0.0" Duration="0:0:5" AutoReverse="True" RepeatBehavior="Forever" />
  </Storyboard>
</BeginStoryboard>
...

  2. Create an EventTrigger and add the BeginStoryboard as its child. Set the RoutedEvent property of the EventTrigger to the Loaded event of the object that owns the animation. This example uses the rectangle's Loaded event to start the Storyboard.

    XAML
    ...
<EventTrigger RoutedEvent="Rectangle.Loaded">
  <BeginStoryboard>
    <Storyboard>
      <DoubleAnimation
        Storyboard.TargetName="MyAnimatedRectangle"
        Storyboard.TargetProperty="Opacity"
        From="1.0" To="0.0" Duration="0:0:5" AutoReverse="True" RepeatBehavior="Forever" />
    </Storyboard>
  </BeginStoryboard>
</EventTrigger>
...

  3. Add the EventTrigger to the Triggers collection of the Rectangle.

    XAML
    ...
<Rectangle
  Name="MyAnimatedRectangle"
  Width="100"
  Height="100"
  Fill="Blue">
  <Rectangle.Triggers>

    <!-- Animates the rectangle's opacity. -->
    <EventTrigger RoutedEvent="Rectangle.Loaded">
      <BeginStoryboard>
        <Storyboard>
          <DoubleAnimation
            Storyboard.TargetName="MyAnimatedRectangle"
            Storyboard.TargetProperty="Opacity"
            From="1.0" To="0.0" Duration="0:0:5" AutoReverse="True" RepeatBehavior="Forever" />
        </Storyboard>
      </BeginStoryboard>
    </EventTrigger>
  </Rectangle.Triggers>
</Rectangle>
...

Complete Example

The following example shows the complete code for creating a rectangle that fades in and out of view after it is loaded.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Rectangle
    x:Name="MyAnimatedRectangle"
    Width="100"
    Height="100"
    Fill="Blue">
    <Rectangle.Triggers>

      <!-- Animates the rectangle's opacity. -->
      <EventTrigger RoutedEvent="Rectangle.Loaded">
        <BeginStoryboard>
          <Storyboard>
            <DoubleAnimation
              Storyboard.TargetName="MyAnimatedRectangle"
              Storyboard.TargetProperty="Opacity"
              From="1.0" To="0.0" Duration="0:0:5" AutoReverse="True" RepeatBehavior="Forever" />
          </Storyboard>
        </BeginStoryboard>
      </EventTrigger>
    </Rectangle.Triggers>
  </Rectangle>
</Canvas>

In addition to starting a storyboard automatically when an object loads, you can use the interactive methods of the Storyboard object to start, pause, resume, and stop an animation. For more information, see the Interactive Animations Overview.

Animation Types

The preceding example used a DoubleAnimation to animated a property. In addition to the DoubleAnimation type, Silverlight provides several more animation objects. Because animations generate property values, different animation types exist for different property types. To animate a property that takes a Double, such as the Width property of an element, use an animation that produces Double values, such as a DoubleAnimation. To animate a property that takes a Point, use an animation that produces Point values, and so on.

There is at least one animation for each animatable property type, and sometimes there are more. Silverlight provides two categories of animation types: "From/To/By" animations and key frame animations. The following table describes the animation categories and the naming conventions they follow.

Category | Description | Naming convention
"From/To/By" animation Animates between a starting and destination value, or by adding an offset value to its starting value.
  • To specify a starting value, set the From property of the animation.
  • To specify an ending value, set the To property of the animation.
  • To specify an offset value, set the By property of the animation.

The examples in this overview use these animations, because they are the simplest to use.

<Type>Animation
Key frame animation | Animates between a series of values specified using key frame objects. Key frame animations are more powerful than From/To/By animations because you can specify any number of target values and even control their interpolation method. Some types can only be animated with key frame animations. Key frame animations are described in detail in the Key-Frame Animations Overview. | <Type>AnimationUsingKeyFrames

The following table shows several common animation types and some properties with which they are used.

Property type | Corresponding basic (From/To/By) animation | Corresponding key frame animation | Usage example
Color | ColorAnimation | ColorAnimationUsingKeyFrames | Animate the Color of a SolidColorBrush or a GradientStop.
Double | DoubleAnimation | DoubleAnimationUsingKeyFrames | Animate the Width of a Rectangle or the Height of an Ellipse.
Point | PointAnimation | PointAnimationUsingKeyFrames | Animate the Center position of an EllipseGeometry.

Animations Are Timelines

All animations inherit from the Timeline object; therefore, all animations are specialized types of timelines. A Timeline defines a segment of time. You can specify the timing behaviors of a timeline: its Duration, how many times it is repeated, and even how fast time progresses for it.

Because an animation is a Timeline, it also represents a segment of time. An animation also calculates output values as it progresses though its specified segment of time (or Duration). As the animation progresses, or "plays," it updates the property that it is associated with.

Three frequently used timing properties are Duration, AutoReverse, and RepeatBehavior.

The Duration Property

As previously mentioned, a timeline (and therefore, an animation) represents a segment of time. The length of that segment is determined by the Duration of the timeline, which is usually specified by using a TimeSpan value. When a timeline reaches the end of its duration, it has completed an iteration.

An animation uses its Duration property to determine its current value. If you do not specify a Duration value for an animation, it uses 1 second, which is the default.

The following syntax shows a simplified version of the Extensible Application Markup Language (XAML) attribute syntax for the Duration property.

hours : minutes : seconds

The following table shows several Duration settings and their resulting values.

Setting | Resulting value
0:0:5.5 | 5.5 seconds.
0:30:5.5 | 30 minutes and 5.5 seconds.
1:30:5.5 | 1 hour, 30 minutes, and 5.5 seconds.

For more information about Duration values and the complete Extensible Application Markup Language (XAML) syntax, see the Duration type page.

AutoReverse

The AutoReverse property specifies whether a timeline plays backward after it reaches the end of its Duration. If you set this animation property to true, an animation reverses after it reaches the end of its Duration, playing from its ending value back to its starting value. By default, this property is false.

RepeatBehavior

The RepeatBehavior property specifies how many times a timeline plays. By default, timelines have an iteration count of 1.0, which means they play one time and do not repeat at all.

Applying an Animation to a Property

The previous sections describe the different types of animations and their timing properties. This section shows how to apply the animation to the property that you want to animate. Storyboard objects provide one way to apply animations to properties. A Storyboard is a container timeline that provides targeting information for the animations it contains.

Targeting Objects and Properties

The Storyboard class provides the TargetName and TargetProperty attached properties. By setting these properties on an animation, you tell the animation what to animate. However, before an animation can target an object, the object must usually be given a name by using the x:Name attribute.

Applying and Starting Storyboards

To start a storyboard in XAML, you associate it with an EventTrigger. An EventTrigger is an object that describes what actions to take when a specified event occurs. One of those actions can be a BeginStoryboard action, which you use to start your storyboard. Event triggers are similar in concept to event handlers because they enable you to describe how your application responds to a particular event. Unlike event handlers, event triggers can be fully described in XAML; no other code is required.

To start a Storyboard in code, you can use the Begin method of the Storyboard class.

Interactively Control a Storyboard

The previous example showed how to start a Storyboard when an event occurs. Using code, you can also interactively control a Storyboard declared in XAML after it starts: you can pause, resume, and stop the Storyboard. For more information, see the Interactive Animations Overview.

What Happens After an Animation Ends?

The FillBehavior property specifies how a timeline behaves when it ends. By default, a timeline starts Filling when it ends. An animation that is Filling holds its final output value.

The DoubleAnimation in the previous example does not end because its RepeatBehavior property is set to Forever. The following example animates a rectangle by using a similar animation. Unlike the previous example, the RepeatBehavior and AutoReverse properties of this animation are left at their default values. Therefore, the animation progresses from 1 to 0 over five seconds and then stops.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Rectangle
    x:Name="MyAnimatedRectangle"
    Width="100"
    Height="100"
    Fill="Blue">
    <Rectangle.Triggers>

      <!-- Animates the rectangle's opacity. -->
      <EventTrigger RoutedEvent="Rectangle.Loaded">
        <BeginStoryboard>
          <Storyboard>
            <DoubleAnimation
              Storyboard.TargetName="MyAnimatedRectangle"
              Storyboard.TargetProperty="Opacity"
              From="1.0" To="0" Duration="0:0:5" />
          </Storyboard>
        </BeginStoryboard>
      </EventTrigger>
    </Rectangle.Triggers>
  </Rectangle>
</Canvas>

Because its FillBehavior was not changed from its default value, which is HoldEnd, the animation holds it final value, 0, when it ends. Therefore, the Opacity of the rectangle remains at 0 after the animation ends. Attempting to change the Opacity value in code will appear to have no effect until the animation is stopped.

The animation in the next example is identical to that in the preceding example, except that this example changes the FillBehavior property of the animation to Stop. As a result, the Opacity value of the rectangle reverts to 1 after the animation ends.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Rectangle
    x:Name="MyAnimatedRectangle"
    Width="100"
    Height="100"
    Fill="Blue">
    <Rectangle.Triggers>

      <!-- Animates the rectangle's opacity. -->
      <EventTrigger RoutedEvent="Rectangle.Loaded">
        <BeginStoryboard>
          <Storyboard>
            <DoubleAnimation
              Storyboard.TargetName="MyAnimatedRectangle"
              Storyboard.TargetProperty="Opacity"
              From="1.0" To="0" Duration="0:0:5" FillBehavior="Stop" />
          </Storyboard>
        </BeginStoryboard>
      </EventTrigger>
    </Rectangle.Triggers>
  </Rectangle>
</Canvas>

See Also

Timeline
Storyboard
Interactive Animations Overview
Key-Frame Animations Overview


Interactive Animations Overview

Silverlight SDK

Interactive Animation Overview

This topic describes how to interactively control Storyboard animations. It also describes how to declare Storyboard animations as resources to prevent them from playing automatically.

This topic contains the following sections.

  • Prerequisites
  • Storyboard Interactive Methods
  • Storyboard as Resources
  • Related Topics

Prerequisites

To understand this topic, you should be familiar with Silverlight animations. For an introduction, see the Animation Overview.

Storyboard Interactive Methods

To interactively control a Storyboard, you retrieve the Storyboard and use its interactive methods.

  • Begin: Initiates the Storyboard.
  • Pause: Pauses the Storyboard.
  • Resume: Resumes a paused Storyboard.
  • Stop: Stops the Storyboard.
  • Seek: Skips to a specific part of the Storyboard animation.

The following example is a modified version of the fading rectangle from the Animation Overview. This version of the example assigns a name to its Storyboard so that it can be retrieved. It also registers for the rectangle's MouseLeftButtonDown event. The Storyboard begins as soon as the Rectangle is loaded, and restarts whenever the user presses the left mouse button over the Rectangle, the animation begins again.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Rectangle
    x:Name="MyAnimatedRectangle"
    Width="100"
    Height="100"
    Fill="Blue"
    MouseLeftButtonDown="startAnimation">
    <Rectangle.Triggers>

      <!-- Animates the rectangle's opacity. -->
      <EventTrigger RoutedEvent="Rectangle.Loaded">
        <BeginStoryboard>
          <Storyboard x:Name="myStoryboard">
            <DoubleAnimation
              Storyboard.TargetName="MyAnimatedRectangle"
              Storyboard.TargetProperty="Opacity"
              From="1.0" To="0.0" Duration="0:0:5"
              AutoReverse="True" />
          </Storyboard>
        </BeginStoryboard>
      </EventTrigger>
    </Rectangle.Triggers>
  </Rectangle>
</Canvas>

The following JavaScript handles the MouseLeftButtonDown event. It retrieves the Storyboard and calls its Begin method.

JavaScript
function startAnimation(sender, mouseEventArgs)
{
    // Retrieve the Storyboard and begin it.
    sender.findName("myStoryboard").begin();

}

Storyboards as Resources

The Storyboard in the preceding example begins playing as soon as the Rectangle object is loaded, and again whenever the left mouse button is pressed over the Rectangle. Suppose that you didn't want the Storyboard to play until the user pressed the left mouse button. Instead of using an EventTrigger to create the Storyboard, declare the Storyboard as a resource.

The following example makes a rectangle fade from view when the user presses the left mouse button over it. Unlike the previous example, the animation does not start automatically.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Canvas.Resources>
    <Storyboard x:Name="myStoryboard">
      <DoubleAnimation
        Storyboard.TargetName="MyAnimatedRectangle"
        Storyboard.TargetProperty="Opacity"
        From="1.0" To="0.0" Duration="0:0:5"
        AutoReverse="True" />
    </Storyboard>
  </Canvas.Resources>
  <Rectangle
    x:Name="MyAnimatedRectangle"
    Width="100"
    Height="100"
    Fill="Blue"
    MouseLeftButtonDown="startAnimation">
  </Rectangle>
</Canvas>
JavaScript
function startAnimation(sender, mouseEventArgs)
{
    // Retrieve the Storyboard and begin it.
    sender.findName("myStoryboard").begin();

}

See Also

Reference

Storyboard

Conceptual

Animation Overview
Key-Frame Animations Overview


Silverlight Key-Frame Animations Overview

This topic introduces you to key-frame animations. Key-frame animations enable you to animate using more than two target values, and control an animation's interpolation method.

This topic contains the following sections.

  • Prerequisites
  • What is a Key-Frame Animation?
  • Key-Frame Animation Types
  • Target Values (key frames) and Key Times
  • Interpolation Methods
  • More about Duration and Key Times
  • Related Topics

Prerequisites

To understand this overview, you should be familiar with Silverlight animations. For an introduction to animations, see the Animation Overview.

What is a Key-Frame Animation?

Like a From/To/By animation, a key-frame animation animates the value of a target property. It creates a transition among its target values over its Duration. However, while a From/To/By animation creates a transition between two values, a single key-frame animation can create transitions among any number of target values.

Unlike a From/To/By animation, a key frame animation has no From, To, or By properties with which to set its target values; instead, you describe a key-frame animation's target values by using key frames objects (hence the term, "key-frame animation"). To specify the animation's target values, you create key frame objects and add them to the animation's KeyFrames property. When the animation runs, it transitions between the frames you specified.

In addition to supporting multiple target values, some key-frame methods even support multiple interpolation methods. An animation's interpolation method defines how it transitions from one value to the next. There are three types of interpolations: discrete, linear, and splined.

To animate with a key-frame animation, you complete the following steps.

  • Declare the animation and specify its Duration, just like you would for a from/to/by animation.

  • For each target value, create a key frame of the appropriate type, set its value and KeyTime, and add it to the animation's KeyFrames collection.

  • Associate the animation with a property, just like you would with a From/To/By animation.

The following example uses a DoubleAnimationUsingKeyFrames to animate a Rectangle element to four different locations.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Width="400" Height="300">
  <Rectangle Fill="Blue"
    Width="50" Height="50">
    <Rectangle.RenderTransform>
      <TranslateTransform
        x:Name="MyAnimatedTranslateTransform"
        X="0" Y="0" />
    </Rectangle.RenderTransform>
    <Rectangle.Triggers>
      <EventTrigger RoutedEvent="Rectangle.Loaded">
        <BeginStoryboard>
          <Storyboard>

            <!-- Animate the TranslateTransform's X property
                 from 0 to 350, then 50,
                 then 200 over 10 seconds. -->

            <DoubleAnimationUsingKeyFrames
              Storyboard.TargetName="MyAnimatedTranslateTransform"
              Storyboard.TargetProperty="X"
              Duration="0:0:10">
              <LinearDoubleKeyFrame Value="0" KeyTime="0:0:0" />
              <LinearDoubleKeyFrame Value="350" KeyTime="0:0:2" />
              <LinearDoubleKeyFrame Value="50" KeyTime="0:0:7" />
              <LinearDoubleKeyFrame Value="200" KeyTime="0:0:8" />
            </DoubleAnimationUsingKeyFrames>
          </Storyboard>
        </BeginStoryboard>
      </EventTrigger>
    </Rectangle.Triggers>
  </Rectangle>
</Canvas>

Like a From/To/By animation, you use a Storyboard object to apply a key-frame animation to a property.

Key-Frame Animation Types

There are different animation types for different property types. To animate a property that takes a Double (such as an element's Width property), you use an animation that produces Double values. To animate a property that takes a Point, you use an animation that produces Point values, and so on.

The key-frame animation classes adhere to the following naming convention:

<Type> AnimationUsingKeyFrames

Where <Type> is the type of value that the class animates.

Silverlight provides the following key-frame animation classes.

Property type | Corresponding key frame animation class | Interpolation methods supported
Color | ColorAnimationUsingKeyFrames | Discrete, Linear, Splined
Double | DoubleAnimationUsingKeyFrames | Discrete, Linear, Splined
Point | PointAnimationUsingKeyFrames | Discrete, Linear, Splined

Target Values (Key Frames) and Key Times

The primary purpose of a key frame is to specify a KeyTime and a target Value. Every key frame type (the abstract types that type the value, and the derived types that define the interpolation technique) provides these two properties.

  • The Value property specifies the target value for that key-frame.

  • The KeyTime property specifies when (within the animation's Duration) a key frame's Value is reached.

When a key frame animation begins, iterates through its key frames in the order defined by their KeyTime properties.

  • If there is no key frame at time 0, the animation creates a transition between the target property's current value and the Value of the first key frame; otherwise, the animation's output value becomes the value of the first key frame.

  • The animation creates a transition between the Value of the first and second key frames using the interpolation method specified by the second key frame. The transition starts at the first key frame's KeyTime and ends when the second key frame's KeyTime is reached.

  • The animation continues, creating transitions between each subsequent key frame and its preceding key frame.

  • Finally, the animation transitions to the value of the key frame with the greatest key time that is equal to or smaller than the animation's Duration.

If the animation's Duration is Automatic or its Duration is equal to the time of the last key frame, the animation ends. If the animation's Duration is greater than the key time of the last key frame, the animation holds the key frame value until it reaches the end of its Duration. If the animation's Duration is shorter than the latest key frame, the animation enters its fill period as soon as its duration is reached.

Like all animations, a key-frame animation uses its FillBehavior property to determine whether it holds it final value when it reaches the end of its active period.

Types of Key Frames

Just as there are different types of key-frame animations for animating different property types, there are also different types of key frame objects: one for each type of value animated and interpolation method supported. Key frame types adhere to the following naming convention:

<InterpolationMethod><Type> KeyFrame

Where <InterpolationMethod> is the interpolation method the key frame uses and <Type> is the type of value that the class animates.

A key-frame animation that supports all three interpolation methods will have three key frame types that you can use. For example, you can use three key frame types with a DoubleAnimationUsingKeyFrames: DiscreteDoubleKeyFrame, LinearDoubleKeyFrame, and SplineDoubleKeyFrame. (Interpolation methods are described in detail in a later section.)

Target Values and Key Times Example

The following example uses the DoubleAnimationUsingKeyFrames object defined in the preceding example to demonstrate how the Value and KeyTime properties work.

  • The first key frame immediately sets the animation's output value to 0.

  • The second key frame animates from 0 to 350. It starts after the first key frame ends (at time = 0 seconds) and plays for 2 seconds, ending at time = 0:0:2.

  • The third key frame animates from 350 to 50. It starts when the second key frame ends (at time = 2 seconds) and plays for 5 seconds, ending at time = 0:0:7.

  • The fourth key frame animates from 50 to 200. It starts when the third key frame ends (at time = 7 seconds) and plays for 1 second, ending at time = 0:0:8.

  • Because the Duration property of the animation was set to 10 seconds, the animation holds its final value for two seconds before ending at time = 0:0:10.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Width="400" Height="300">
  <Rectangle Fill="Blue"
    Width="50" Height="50">
    <Rectangle.RenderTransform>
      <TranslateTransform
        x:Name="MyAnimatedTranslateTransform"
        X="0" Y="0" />
    </Rectangle.RenderTransform>
    <Rectangle.Triggers>
      <EventTrigger RoutedEvent="Rectangle.Loaded">
        <BeginStoryboard>
          <Storyboard>

            <!-- Animate the TranslateTransform's X property
                 from 0 to 350, then 50,
                 then 200 over 10 seconds. -->

            <DoubleAnimationUsingKeyFrames
              Storyboard.TargetName="MyAnimatedTranslateTransform"
              Storyboard.TargetProperty="X"
              Duration="0:0:10">
              <LinearDoubleKeyFrame Value="0" KeyTime="0:0:0" />
              <LinearDoubleKeyFrame Value="350" KeyTime="0:0:2" />
              <LinearDoubleKeyFrame Value="50" KeyTime="0:0:7" />
              <LinearDoubleKeyFrame Value="200" KeyTime="0:0:8" />
            </DoubleAnimationUsingKeyFrames>
          </Storyboard>
        </BeginStoryboard>
      </EventTrigger>
    </Rectangle.Triggers>
  </Rectangle>
</Canvas>

Interpolation Methods

The preceding sections mentioned that some key-frame animations support multiple interpolation methods. An animation's interpolation describes how an animation transitions between values over its duration. By selecting which key frame type you use with your animation, you can define the interpolation method for that key frame segment. There are three different types of interpolation methods: linear, discrete, and splined.

Linear Interpolation

With linear interpolation, the animation progresses at a constant rate of the segment duration. For example, if a key frame segment transitions from 0 to 10 over a duration of 5 seconds, the animation will output the following values at the specified times:

Time | Output value
0 | 0
1 | 2
2 | 4
3 | 6
4 | 8
4.25 | 8.5
4.5 | 9
5 | 10

Discrete Interpolation

With discrete interpolation, the animation function jumps from one value to the next without interpolation. If a key frame segment transitions from 0 to 10 over a duration of 5 seconds, the animation will output the following values at the specified times:

Time | Output value
0 | 0
1 | 0
2 | 0
3 | 0
4 | 0
4.25 | 0
4.5 | 0
5 | 10

Notice how the animation does not change its output value until the very end of the segment duration.

Splined interpolation is more complex. It is described in the next section.

Splined Interpolation

Splined interpolation can be used to achieve more realistic timing effects. Because animations are so often used to imitate effects that occur in the real world, developers might need fine control of the acceleration and deceleration of objects, and close manipulation of timing segments. Spline key frames enable you to animate with splined interpolation. With other key frames, you specify a Value and KeyTime. With a spline key frame, you also specify a KeySpline. The following example shows a single spline key frame for a DoubleAnimationUsingKeyFrames. Notice the KeySpline property; that's what makes a spline key frame different from the other types of key frames.

XAML
              <SplineDoubleKeyFrame Value="500"
                KeyTime="0:0:7" KeySpline="0.0,1.0 1.0,0.0" />

A cubic Bezier curve is defined by a start point, an end point, and two control points. The KeySpline property of a spline key frame defines the two control point of a Bezier curve that extends from (0,0) to (1,1). The first control point controls the curve factor of the first half of the Bezier curve, and the second control point controls the curve factor of the second half of the Bezier segment. The resulting curve describes the rate of change for that spline key frame. The steeper the curve, the faster the key frame changes its values. As the curve gets flatter, the key frame changes its values more slowly.

You might use KeySpline to simulate physical trajectories like falling water or bouncing balls, or apply other "ease in" and "ease out" effects to motion animations. For user interaction effects like background fades or control button rebound, you might apply splined interpolation to speed up or slow down the rate of change for an animation in a specific way.

The following example specifies a KeySpline of 0,1 1,0, which creates the following Bezier curve.

A key spline with control points (0.0, 1.0) and (1.0, 0.0)
A Bezier curve
XAML
              <SplineDoubleKeyFrame Value="500"
                KeyTime="0:0:7" KeySpline="0.0,1.0 1.0,0.0" />

The preceding key frame animates rapidly when it begins, slows down, and then speeds up again before it ends.

The following example specifies a KeySpline of 0.5,0.25 0.75,1.0, which creates the following Bezier curve.

A key spline with control points (0.25, 0.5) and (0.75, 1.0)
A Bezier curve
XAML
              <SplineDoubleKeyFrame Value="350"
                KeyTime="0:0:15" KeySpline="0.25,0.5 0.75,1" />

Because the curvature of the Bezier curve changes very little, this key frame animates at an almost constant rate; it slows down somewhat toward its very end.

The following example uses a DoubleAnimationUsingKeyFrames to animate the position of rectangle. Because the DoubleAnimationUsingKeyFrames uses SplineDoubleKeyFrame objects, the transition between each key frame value uses splined interpolation.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Width="600" Height="300">
  <Rectangle Fill="Blue"
    Width="50" Height="50">
    <Rectangle.RenderTransform>
      <TranslateTransform
        x:Name="SplineAnimatedTranslateTransform"
        X="0" Y="0" />
    </Rectangle.RenderTransform>
    <Rectangle.Triggers>
      <EventTrigger RoutedEvent="Rectangle.Loaded">
        <BeginStoryboard>
          <Storyboard>

            <!-- Animate the TranslateTransform's X property
                 from its base value (0) to 500, then 200,
                 then 350 over 15 seconds. -->
            <DoubleAnimationUsingKeyFrames
              Storyboard.TargetName="SplineAnimatedTranslateTransform"
              Storyboard.TargetProperty="X"
              Duration="0:0:15"
              RepeatBehavior="Forever">

              <SplineDoubleKeyFrame Value="500"
                KeyTime="0:0:7" KeySpline="0.0,1.0 1.0,0.0" />

              <SplineDoubleKeyFrame Value="200"
                KeyTime="0:0:10" KeySpline="0.0,0.0 1.0,0.0" />

              <SplineDoubleKeyFrame Value="350"
                KeyTime="0:0:15" KeySpline="0.25,0.5 0.75,1" />

            </DoubleAnimationUsingKeyFrames>
          </Storyboard>
        </BeginStoryboard>
      </EventTrigger>
    </Rectangle.Triggers>
  </Rectangle>
</Canvas>

Splined interpolation can be difficult to understand; experimenting with different settings can help.

Combining Interpolation Methods

You can use key frames with different interpolation types in a single key frame animation. When two key frame animations with different interpolations follow each other, the interpolation method of the second key frame is used to create the transition from the first value to the second.

In the following example, a DoubleAnimationUsingKeyFrames is created that uses linear, splined, and discrete interpolation.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Width="600" Height="300">
  <Rectangle Fill="Blue"
    Width="50" Height="50">
    <Rectangle.RenderTransform>
      <TranslateTransform
        x:Name="ComboAnimatedTranslateTransform"
        X="0" Y="0" />
    </Rectangle.RenderTransform>
    <Rectangle.Triggers>
      <EventTrigger RoutedEvent="Rectangle.Loaded">
        <BeginStoryboard>
          <Storyboard>

            <!-- Animate the TranslateTransform's X property
                    from its base value (0) to 500, then 200,
                    then 350 over 15 seconds. -->
            <DoubleAnimationUsingKeyFrames
              Storyboard.TargetName="ComboAnimatedTranslateTransform"
              Storyboard.TargetProperty="X"
              Duration="0:0:15"
              RepeatBehavior="Forever">
              <DiscreteDoubleKeyFrame Value="500" KeyTime="0:0:7" />
              <LinearDoubleKeyFrame Value="200" KeyTime="0:0:10" />
              <SplineDoubleKeyFrame Value="350" KeyTime="0:0:15"
                KeySpline="0.25,0.5 0.75,1" />
            </DoubleAnimationUsingKeyFrames>
          </Storyboard>
        </BeginStoryboard>
      </EventTrigger>
    </Rectangle.Triggers>
  </Rectangle>
</Canvas>

More about Duration and Key Times

Like other animations, key-frame animations have a Duration property. In addition to specifying the animation's Duration, you need to specify what portion of that duration is given to each key frame. You do so by describing a KeyTime for each of the animation's key frames. Each key frame's KeyTime specifies when that key frame ends.

The KeyTime property does not specify how long the key time plays. The amount of time a key frame plays is determined by when the key frame ends, when the previous key frame ended, and the animation's duration.

You may use time values to specify a KeyTime. The value should be greater than or equal to 0. The following example shows an animation with a duration of 10 seconds and four key frames whose key times are specified as time values.

  • The first key frame animates from the base value to 100 over the first 3 seconds, ending at time = 0:0:03.

  • The second key frame animates from 100 to 200. It starts after the first key frame ends (at time = 3 seconds) and plays for 5 seconds, ending at time = 0:0:8.

  • The third key frame animates from 200 to 500. It starts when the second key frame ends (at time = 8 seconds) and plays for 1 second, ending at time = 0:0:9.

  • The fourth key frame animates from 500 to 600. It starts when the third key frame ends (at time = 9 seconds) and plays for 1 second, ending at time = 0:0:10.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Width="650" Height="300">
  <Rectangle Fill="Blue"
    Width="50" Height="50">
    <Rectangle.RenderTransform>
      <TranslateTransform
        x:Name="MyAnimatedTranslateTransform"
        X="0" Y="0" />
    </Rectangle.RenderTransform>
    <Rectangle.Triggers>
      <EventTrigger RoutedEvent="Rectangle.Loaded">
        <BeginStoryboard>
          <Storyboard>
            <DoubleAnimationUsingKeyFrames
              Storyboard.TargetName="MyAnimatedTranslateTransform"
              Storyboard.TargetProperty="X"
              Duration="0:0:10">

                <!-- KeyTime properties are expressed as TimeSpan values. -->
                <LinearDoubleKeyFrame Value="100" KeyTime="0:0:3" />
                <LinearDoubleKeyFrame Value="200" KeyTime="0:0:8" />
                <LinearDoubleKeyFrame Value="500" KeyTime="0:0:9" />
                <LinearDoubleKeyFrame Value="600" KeyTime="0:0:10" />
                </DoubleAnimationUsingKeyFrames>
          </Storyboard>
        </BeginStoryboard>
      </EventTrigger>
    </Rectangle.Triggers>
  </Rectangle>
</Canvas>

See Also

Reference

KeyTime
KeySpline
Timeline

Concepts

Animation Overview
Interactive Animations Overview


Silverlight References

Silverlight SDK

Silverlight Reference

This topic contains the following section:

  • Objects
  • Methods
  • Properties
  • Events
  • Enumerations

Objects

Accessibility

ArcSegment

BeginStoryboard

BezierSegment

Boolean

Brush

Canvas

Collection

Color

ColorAnimation

ColorAnimationUsingKeyFrames

ColorKeyFrame

ColorKeyFrameCollection

DependencyObject

DiscreteColorKeyFrame

DiscreteDoubleKeyFrame

DiscretePointKeyFrame

Double

DoubleAnimation

DoubleAnimationUsingKeyFrames

DoubleKeyFrame

DoubleKeyFrameCollection

Downloader

DrawingAttributes

Duration

Ellipse

EllipseGeometry

ErrorEventArgs

EventTrigger

Geometry

GeometryCollection

GeometryGroup

Glyphs

GradientStop

GradientStopCollection

Image

ImageBrush

InkPresenter

Inlines

KeyboardEventArgs

KeySpline

KeyTime

Line

LinearColorKeyFrame

LinearDoubleKeyFrame

LinearGradientBrush

LinearPointKeyFrame

LineBreak

LineGeometry

LineSegment

Matrix

MatrixTransform

MediaAttribute

MediaAttributeCollection

MediaElement

MouseEventArgs

ParserErrorEventArgs

Path

PathFigure

PathFigureCollection

PathGeometry

PathSegment

PathSegmentCollection

Point

PointAnimation

PointAnimationUsingKeyFrames

PointKeyFrame

PointKeyFrameCollection

PolyBezierSegment

Polygon

Polyline

PolyLineSegment

PolyQuadraticBezierSegment

QuadraticBezierSegment

RadialGradientBrush

Rect

Rectangle

RectangleGeometry

RepeatBehavior

ResourceDictionary

RotateTransform

Run

RuntimeErrorEventArgs

ScaleTransform

Shape

Silverlight Plug-in

SkewTransform

SolidColorBrush

SplineColorKeyFrame

SplineDoubleKeyFrame

SplinePointKeyFrame

Storyboard

Stroke

StrokeCollection

StylusInfo

StylusPoint

StylusPointCollection

TextBlock

Timeline

TimelineCollection

TimelineMarker

TimelineMarkerCollection

TimelineMarkerEventArgs

TimeSpan

Transform

TransformCollection

TransformGroup

TranslateTransform

TriggerActionCollection

TriggerCollection

UIElement

VideoBrush

VisualCollection

Methods

Abort

Add

AddEventListener

AddStylusPoints

Begin

CaptureMouse

Clear

CreateFromXAML

CreateFromXAMLDownloader

CreateObject

Equals

FindName (Silverlight Control)

FindName (UIElement)

GetBounds (Stroke)

GetBounds (StrokeCollection)

GetHost

GetItem

GetItemByName

GetParent

GetPosition

GetResponseText

GetStylusInfo

GetStylusPoints

GetValue

HitTest (Stroke)

HitTest (StrokeCollection)

Insert

IsVersionSupported

Open

Pause (MediaElement)

Pause (Storyboard)

Play

ReleaseMouseCapture

Remove

RemoveAt

RemoveEventListener

Resume

Seek

Send

SetFontSource

SetSource (Image)

SetSource (ImageBrush)

SetSource (MediaElement)

SetValue

Stop (MediaElement)

Stop (Storyboard)

Properties

Accessibility

ActionDescription

Actions

ActualHeight (Silverlight Plug-in)

ActualHeight (TextBlock)

ActualWidth (Silverlight Plug-in)

ActualWidth (TextBlock)

AlignmentX (ImageBrush)

AlignmentX (VideoBrush)

AlignmentY (ImageBrush)

AlignmentY (VideoBrush)

Angle

AngleX

AngleY

Attributes

AudioStreamCount

AudioStreamIndex

AutoPlay

AutoReverse

Background (Canvas)

Background (Silverlight Plug-in)

Balance

BeginTime

BufferingProgress

BufferingTime

By (ColorAnimation)

By (DoubleAnimation)

By (PointAnimation)

CanPause

CanSeek

Canvas.Left

Canvas.Top

Canvas.ZIndex

Center (EllipseGeometry)

Center (RadialGradientBrush)

CenterX (RotateTransform)

CenterX (ScaleTransform)

CenterX (SkewTransform)

CenterY (RotateTransform)

CenterY (ScaleTransform)

CenterY (SkewTransform)

CharPosition (ParserErrorEventArgs)

CharPosition (RuntimeErrorEventArgs)

Children (Canvas)

Children (GeometryGroup)

Children (Storyboard)

Children (TransformGroup)

Clip

Color (DrawingAttributes)

Color (GradientStop)

Color (SolidColorBrush)

ColorInterpolationMode (LinearGradientBrush)

ColorInterpolationMode (RadialGradientBrush)

Count

Ctrl (KeyboardEventArgs)

Ctrl (MouseEventArgs)

CurrentState

Cursor

Data

Description

DeviceType

DownloadProgress (Downloader)

DownloadProgress (MediaElement)

DownloadProgress (Image)

DownloadProgress (ImageBrush)

DrawingAttributes

Duration

EnableFramerateCounter

EnableHtmlAccess

EnableRedrawRegions

EndPoint (LinearGradientBrush)

EndPoint (LineGeometry)

ErrorCode

ErrorMessage

ErrorType

Figures

Fill (Glyphs)

Fill (Shape)

FillBehavior

FillRule (Geometry)

FillRule (Polygon)

FillRule (Polyline)

FontFamily

FontRenderingEmSize

FontSize

FontStretch

FontStyle

FontUri

FontWeight

Foreground

From (ColorAnimation)

From (DoubleAnimation)

From (PointAnimation)

FullScreen

GradientOrigin

GradientStops (LinearGradientBrush)

GradientStops (RadialGradientBrush)

Height (DrawingAttributes)

Height (Rect)

Height (UIElement)

ImageSource

Indices

InitParams

Inlines

IsClosed

IsHitTestVisible

IsInverted

IsLargeArc

IsLoaded

IsMuted

Key

KeyFrames (ColorAnimationUsingKeyFrames)

KeyFrames DoubleAnimationUsingKeyFrames)

KeyFrames PointAnimationUsingKeyFrames)

KeySpline (SplineColorKeyFrame)

KeySpline (SplineDoubleKeyFrame)

KeySpline (SplinePointKeyFrame)

KeyTime (ColorKeyFrame)

KeyTime (DoubleKeyFrame)

KeyTime (PointKeyFrame)

LineNumber (ParserErrorEventArgs)

LineNumber (RuntimeErrorEventArgs)

M11

M12

N21

M22

MappingMode (LinearGradientBrush)

MappingMode (RadialGradientBrush)

Marker

Markers

MaxFrameRate

MethodName

Name

NaturalDuration

NaturalVideoHeight

NaturalVideoWidth

Offset

OffsetX.htm

Offsety.htm

Opacity (Brush)

Opacity (UIElement)

OpacityMask

OriginX

OriginY

OutlineColor

PlatformKeyCode

Point (ArcSegment)

Point (LineSegment)

Point1 (BezierSegment)

Point1 (QuadraticBezierSegment)

Point2 (BezierSegment)

Point2 (QuadraticBezierSegment)

Point3

Points (PolyBezierSegment)

Points (Polygon)

Points (Polyline)

Points (PolyLineSegment)

Points (PolyQuadraticBezierSegment)

Position

PressureFactor

RadiusX (EllipseGeometry)

RadiusX (RadialGradientBrush)

RadiusX (Rectangle)

RadiusX (RectangleGeometry)

RadiusY (EllipseGeometry)

RadiusY (RadialGradientBrush)

RadiusY (Rectangle)

RadiusY (RectangleGeometry)

Rect

RelativeTransform

RenderTransform

RenderTransformOrigin

RepeatBehavior

Resources

Root

RotationAngle

RoutedEvent

ScaleX

ScaleY

Seconds (Duration)

Seconds (KeyTime)

Seconds (RepeatBehavior)

Seconds (TimeSpan)

Segments

Shift (KeyboardEventArgs)

Shift (MouseEventArgs)

Size

Source (Image)

Source (MediaElement)

Source (Silverlight Plug-in)

SourceName

SpeedRatio

SpreadMethod (LinearGradientBrush)

SpreadMethod (RadialGradientBrush)

StartPoint (LinearGradientBrush)

StartPoint (LineGeometry)

StartPoint (PathFigure)

Status

StatusText

Storyboard

Stretch (Image)

Stretch (ImageBrush)

Stretch (MediaElement)

Stretch (Shape)

Stretch (VideoBrush)

Stroke

StrokeDashArray

StrokeDashCap

StrokeDashOffset

StrokeEndLineCap

StrokeLineJoin

StrokeMiterLimit

Strokes

StrokeStartLineCap

StrokeThickness

StyleSimulations

StylusPoints

SweepDirection

Tag

TargetName

TargetProperty

Text (TextElement)

Text (TimelineMarker)

TextDecorations

TextWrapping

Time

Title

To (ColorAnimation)

To (DoubleAnimation)

To (PointAnimation)

Transform (Brush)

Transform (Geometry)

Transform (MatrixTransform)

Triggers

Type (TimelineMarker)

UnicodeString

Uri

Value (ColorKeyFrame)

Value (DoubleKeyFrame)

Value (MediaAttribute)

Value (PointKeyFrame)

Visibility

Volume

Width (DrawingAttributes)

Width (Rect)

Width (UIElement)

Windowless

X (Point)

X (Rect)

X (StylusPoint)

X (TranslateTransfrom)

X1

X2

XamlFile

XmlAttribute

XmlElement

Y (Point)

Y (Rect)

Y (StylusPoint)

Y (TranslateTransform)

Y1

Y2

Events

BufferingProgressChanged

Completed (Downloader)

Completed (Storyboard)

CurrentStateChanged

DownloadFailed

DownloadProgressChanged (Downloader)

DownloadProgressChanged (Image)

DownloadProgressChanged (ImageBrush)

DownloadProgressChanged (MediaElement)

GotFocus

ImageFailed (Image)

ImageFailed (ImageBrush)

KeyDown

KeyUp

Loaded

LostFocus

MarkerReached

MediaEnded

MediaFailed

MediaOpened

MouseEnter

MouseLeave

MouseLeftButtonDown

MouseLeftButtonUp

MouseMove

OnError

OnFullScreenChange

OnLoad

OnResize

PerformAction

Enumerations

AlignmentX

AlignmentY

BrushMappingMode

ColorInterpolationMode

DeviceType

ErrorType

FillBehavior

FillRule

FontStretch

FontStyle

FontWeight

GradientSpreadMethod

Key

MediaState

MouseCursor

PenLineCap

PenLineJoin

Stretch

StyleSimulations

SweepDirection

TextDecorations

TextWrapping

Visibility

See Also

Silverlight Overviews


Silverlight Objects

This section contains a list of the objects exposed by the Silverlight Object Model.

Objects

Accessibility

ArcSegment

BeginStoryboard

BezierSegment

Boolean

Brush

Canvas

Collection

Color

ColorAnimation

ColorAnimationUsingKeyFrames

ColorKeyFrame

ColorKeyFrameCollection

DependencyObject

DiscreteColorKeyFrame

DiscreteDoubleKeyFrame

DiscretePointKeyFrame

Double

DoubleAnimation

DoubleAnimationUsingKeyFrames

DoubleKeyFrame

DoubleKeyFrameCollection

Downloader

DrawingAttributes

Duration

Ellipse

EllipseGeometry

ErrorEventArgs

EventTrigger

Geometry

GeometryCollection

GeometryGroup

Glyphs

GradientStop

GradientStopCollection

Image

ImageBrush

InkPresenter

KeyboardEventArgs

KeySpline

KeyTime

Line

LinearColorKeyFrame

LinearDoubleKeyFrame

LinearGradientBrush

LinearPointKeyFrame

LineBreak

LineGeometry

LineSegment

Matrix

MatrixTransform

MediaAttribute

MediaAttributeCollection

MediaElement

MouseEventArgs

ParserErrorEventArgs

Path

PathFigure

PathFigureCollection

PathGeometry

PathSegment

PathSegmentCollection

Point

PointAnimation

PointAnimationUsingKeyFrames

PointKeyFrame

PointKeyFrameCollection

PolyBezierSegment

Polygon

Polyline

PolyLineSegment

PolyQuadraticBezierSegment

QuadraticBezierSegment

RadialGradientBrush

Rect

Rectangle

RectangleGeometry

RepeatBehavior

ResourceDictionary

RotateTransform

Run

RuntimeErrorEventArgs

ScaleTransform

Shape

Silverlight Plug-in

SkewTransform

SolidColorBrush

SplineColorKeyFrame

SplineDoubleKeyFrame

SplinePointKeyFrame

Storyboard

Stretch

Stroke

StrokeCollection

StylusInfo

StylusPoint

StylusPointCollection

TextBlock

Timeline

TimelineCollection

TimelineMarker

TimelineMarkerCollection

TimelineMarkerEventArgs

TimeSpan

Transform

TransformCollection

TransformGroup

TranslateTransform

TriggerActionCollection

TriggerCollection

UIElement

VisualCollection

VideoBrush

See Also

Silverlight Reference, Silverlight Conceptual Topics


Accessibility Object

Provides accessibility properties that report information about your Silverlight content.

XAML | Cannot be used in XAML.
Scripting | var accessibilityObject = silverlightPlugin.content.accessibility

Properties

ActionDescription, Description, Name, Title,

Methods

Equals, FindName, GetHost, GetValue, SetValue

Events

PerformAction

See Also

Accessibility Overview


ArcSegment Object

Represents an elliptical arc between two points.

XAML | <ArcSegment .../>
JavaScript | To create an object using scripting, see the CreateFromXAML method.

Properties

IsLargeArc, Name, Point, RotationAngle, Size, SweepDirection

Methods

GetValue, SetValue

Events

None

Remarks

See Also

PathFigure, PathSegment


BeginStoryboard Object

A trigger action that begins a Storyboard and distributes its animations to their targeted objects and properties.

XAML
<BeginStoryboard>
  <Storyboard .../>
</BeginStoryboard>
Scripting
To create an object using scripting, see CreateFromXAML.

Properties

Name, Storyboard

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

BeginStoryboard is used as a wrapper around a Storyboard that is being triggered. A BeginStoryboard can only contain one Storyboard, not a collection of them.

In addition to starting a storyboard automatically when an object loads, you can use the interactive methods of the Storyboard object to start, pause, resume, and stop an animation. For more information, see the Interactive Animations Overview.

Examples

The following example shows how to use a Storyboard and a BeginStoryboard object to make a rectangle that fades in and out of view after it is loaded.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Rectangle
    x:Name="MyAnimatedRectangle"
    Width="100"
    Height="100"
    Fill="Blue">
    <Rectangle.Triggers>

      <!-- Animates the rectangle's opacity. -->
      <EventTrigger RoutedEvent="Rectangle.Loaded">
        <BeginStoryboard>
          <Storyboard>
            <DoubleAnimation
              Storyboard.TargetName="MyAnimatedRectangle"
              Storyboard.TargetProperty="Opacity"
              From="1.0" To="0.0" Duration="0:0:5" AutoReverse="True" RepeatBehavior="Forever" />
          </Storyboard>
        </BeginStoryboard>
      </EventTrigger>
    </Rectangle.Triggers>
  </Rectangle>
</Canvas>

See Also

Animation Overview


BezierSegment Object

Represents a cubic Bezier curve drawn between two points.

XAML | <BezierSegment .../>
Scripting | To create an object using scripting, see the CreateFromXAML method.

Properties

Name, Point1, Point2, Point3

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

To specify a Bezier type segment with more control points, see PolyBezierSegment.

Examples

The following example uses a BezierSegment as one of the PathSegments in a PathGeometry.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <Path Stroke="Black" StrokeThickness="1" >
    <Path.Data>
      <PathGeometry>
        <PathGeometry.Figures>
          <PathFigure StartPoint="10,50">
            <PathFigure.Segments>
              <BezierSegment
                Point1="100,0"
                Point2="200,200"
                Point3="300,100"/>
              <LineSegment Point="400,100" />
              <ArcSegment
                Size="50,50" RotationAngle="45"
                IsLargeArc="True" SweepDirection="Clockwise"
                Point="200,100"/>
            </PathFigure.Segments>
          </PathFigure>
        </PathGeometry.Figures>
      </PathGeometry>
    </Path.Data>
  </Path>
</Canvas>

See Also

PathFigure, PathSegment, QuadraticBezierSegment, PolyQuadraticBezierSegment, Silverlight Geometries Overview


Boolean Structure

Silverlight SDK

Boolean Class

Represents a Boolean value.

XAML
<object property = "True" ... />
-or-
<object property = "False" ... />
Scripting
See Remarks

Remarks

Boolean does not have any callable APIs.

Silverlight defines Boolean as a class in order to provide type conversion and parsing behavior for XAML. For property values or method parameters in scripting, use either true or false. For XAML attributes, use a string value of "true or "false", case insensitive. Integer values are also type-convertible, with 0 converting to false, and all other values converting to true.


Brush Object (Abstract)

Defines objects used to paint graphical objects.

XAML | Cannot be used in XAML, see Remarks.
Scripting | Must use derived objects.

Properties

Name, Opacity, RelativeTransform, Transform

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

For XAML syntaxes that take a Brush, you need to specify one of the following:

  • A Color, specified as a string to directly fill a Brush-type property in XAML attribute form. That string is implied to create a SolidColorBrush to fill the value, and the Color you specify becomes the SolidColorBrush.Color property value.
  • A nonabstract derived type of Brush as an object element, with the Brush-type property in question being specified in property element form. For details, see the XAML syntax on the reference pages for SolidColorBrush, LinearGradientBrush, RadialGradientBrush, ImageBrush, and VideoBrush.

For more information and examples of the XAML syntax and illustrations of the types of brushes, see Brush Overview.

A Brush "paints" an area with its output. Different brushes have different types of output. Some brushes paint an area with a solid color, gradient, or image. The following list describes the different types of brushes:

  • SolidColorBrush: Paints an area with a solid Color.

  • LinearGradientBrush: Paints an area with a linear gradient.

  • RadialGradientBrush: Paints an area with a radial gradient.

  • ImageBrush: Paints an area with an image.

  • VideoBrush: Paints an area with a running video.

See Also

Brush Overview


Canvas Object

Defines an area within which you can explicitly position child elements by using coordinates that are relative to the area.

XAML
<Canvas ...>
  oneOrMoreUIElements
</Canvas>
-or-
<Canvas .../>
Scripting
To create an object using scripting, see the CreateFromXAML method.

Properties

Background, Canvas.Left, Canvas.Top, Canvas.ZIndex, Children, Clip, Cursor, Height, IsHitTestVisible, Name, Opacity, OpacityMask, RenderTransform, RenderTransformOrigin, Resources, Tag, Triggers, Visibility, Width

Methods

AddEventListener, CaptureMouse, Equals, FindName, GetHost, GetParent, GetValue, ReleaseMouseCapture, RemoveEventListener, SetValue

Events

GotFocus, KeyDown, KeyUp, Loaded, LostFocus, MouseEnter, MouseLeave, MouseLeftButtonDown, MouseLeftButtonUp, MouseMove

Remarks

In many cases, a Canvas object is used solely as a container for other objects and does not have any visible properties. A Canvas object is not visible if one or more of the following conditions are true:

  • The Height property is equal to 0.
  • The Width property is equal to 0.
  • The Background property is equal to null.
  • The Opacity property is equal to 0.
  • The Visibility property is equal to Collapsed.
  • One of the ancestors of the Canvas object is not visible.

See Also

Referencing and Modifying Silverlight Objects, InkPresenter, Silverlight Object Layout


Collection Object (Abstract)

Represents a collection of objects.

XAML | Cannot be used in XAML.
Scripting | Must use derived objects.

Properties

Count, Name

Methods

Add, Clear, Equals, FindName, GetHost, GetItem, GetValue, Insert, Remove, RemoveAt, SetValue

Remarks

You can access the child objects of a parent object by using the methods of the Collection object. The most common collection used for this purpose is the VisualCollection that is the value of the Canvas.Children property.

A Collection also has access to methods of DependencyObject.

For more information on using properties and methods of the Collection object, see Referencing and Modifying Silverlight Objects.

Examples

The following JavaScript example shows to retrieve the collection of an object and access the members of the collection:

JavaScript
function getChildren(parent, index)
{
    // Enumerate the children of the Canvas object.
    for (i = 0; i < parent.children.count; i++)
    {
        var child = parent.children.getItem(i);

        // Display the index and type of the child object.
        alert(i + ": " + child.toString());
    }
}

See Also

ColorKeyFrameCollection, DoubleKeyFrameCollection, GeometryCollection, GradientStopCollection, Inlines, PathFigureCollection, PathSegmentCollection, TransformCollection, TriggerCollection, VisualCollection


Color Structure

Describes a color in terms of alpha, red, green, and blue channels.

XAML | <object.property = "colorString" .../>
Scripting | object.property = "colorString"

Properties

Name

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

Colors are specified through a string that is parsed by one of three conventions: a named color, a hex string, or an ScRGB string. The latter two conventions use hex values (either singles or duples, representing 8-bit and 16-bit colors) for alpha, red, green, blue components, preceded by a hash sign (#).

The following table describes an approximate grammar with examples. All of these examples produce the same color value in this case, with the exception of those that specify an alpha value (and these all specify 50% alpha).

Scheme | Grammar | Example
Predefined Color Name | predefinedColorName | "Blue"
8-bit hex, no alpha | #RGB | "#00f"
8-bit hex, alpha | #ARGB | "#800f"
16-bit hex, no alpha | #RRGGBB | "#0000ff"
16-bit hex, alpha | #AARRGGBB | "#800000ff"
scRGB, no alpha | sc#R,G,B | "sc#0,0,1"
scRGB, alpha | sc#A,R,G,B | "sc#0.5,0,0,1"

In unmanaged code, there is often no true structure or object representing a color, it is merely a convention for the common string conversion behavior for properties that take colors, both in scripting and XAML. A case where Color is maintained as an object is for the By, From, To, or Value properties of animations that you use to animate a property that takes a Color.

In scripting, you specify a color as a quoted string (either a named color or an AxRxGxBx string), and the same type conversion behavior is used. If you get the value of a Color property (such as SolidColorBrush.Color) through scripting, the script value from out of the JavaScript scripting engine will not match these conventions. You can compare colors between existing instances, but you will not get expected results if you compare to strings of named colors or either hex or scRGB strings.

The Silverlight color names match the Microsoft .NET Framework version 1.0, Windows Forms, and Microsoft Internet Explorer color names. This representation is based on UNIX X11 named color values.

The following image shows each predefined color, its name, and its hexadecimal value.

See Also

Silverlight Brushes Overview


ColorAnimation Object

Animates the value of a Color property between two target values using linear interpolation over a specified Duration.

XAML | <ColorAnimation .../>
Scripting | To create an object using scripting, see CreateFromXAML.

Properties

AutoReverse, BeginTime, By, Duration, FillBehavior, From, Name, RepeatBehavior, SpeedRatio, Storyboard.TargetName, Storyboard.TargetProperty, To

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

An animation updates the value of a property over a period of time. An animation effect can be subtle, such as moving a Shape a few pixels left or right, or dramatic, such as enlarging an object to 200 times its original size while spinning it and changing its color. To create an animation, you associate an animation with an object's property value.

The ColorAnimation class creates a transition between two target values. To set its target values, use its From, To, and By properties. The following table summarizes how the From, To, and By properties may be used together or separately to determine an animation's target values.

Properties specified | Resulting behavior
From | The animation progresses from the value specified by the From property to the base value of the property being animated.
From and To | The animation progresses from the value specified by the From property to the value specified by the To property.
From and By | The animation progresses from the value specified by the From property to the value specified by the sum of the From and By properties.
To | The animation progresses from the animated property's base value or a previous animation's output value to the value specified by the To property.
By | The animation progresses from the base value of the property being animated or a previous animation's output value to the sum of that value and the value specified by the By property.

Note If you set both the To and By properties, the To property takes precedence and the By property is ignored.

To use other interpolation methods or animate between more than two target values, use a ColorAnimationUsingKeyFrames object.

Examples

The following example shows how to use ColorAnimation to animate the background color of a Canvas.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Width="200" Height="200"
  Background="White"
  x:Name="Page">
  <Canvas.Triggers>
    <EventTrigger RoutedEvent="Canvas.Loaded">
      <BeginStoryboard>
        <Storyboard x:Name="ColorStoryboard">

          <!-- Animate the background color of the canvas from red to green
               over 4 seconds. -->
          <ColorAnimation BeginTime="00:00:00" Storyboard.TargetName="Page"
           Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)"
           From="Red" To="Green" Duration="0:0:4" />

        </Storyboard>
      </BeginStoryboard>
    </EventTrigger>
  </Canvas.Triggers>
</Canvas>

See Also

Animation Overview
Interactive Animations Overview


ColorAnimationUsingKeyFrames Object

Animates the value of a Color property along a set of KeyFrames over a specified Duration.

XAML
<ColorAnimationUsingKeyFrames>
  oneOrMoreColorKeyFrames
</ColorAnimationUsingKeyFrames>
Scripting
To create an object using scripting, see CreateFromXAML.

Properties

AutoReverse, BeginTime, Duration, FillBehavior, KeyFrames, Name, RepeatBehavior, SpeedRatio, Storyboard.TargetName, Storyboard.TargetProperty

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

A key frame animation's target values are defined by its KeyFrames property, which contains a collection of ColorKeyFrame objects. Each ColorKeyFrame defines a segment of the animation with its own target Value and KeyTime. When the animation runs, it progresses from one key value to the next at the specified key times.

Unlike a ColorAnimation, a ColorAnimationUsingKeyFrames can have more than two of target values. You can also control the interpolation method of individual ColorKeyFrame segments. There are three types of ColorKeyFrame classes, one for each supported interpolation method: LinearColorKeyFrame, DiscreteColorKeyFrame, and SplineColorKeyFrame.

Examples

The following example uses the ColorAnimationUsingKeyFrames class to animate the Background property of a Canvas. This animation uses three key frames in the following manner:

  1. During the first two seconds, LinearColorKeyFrame gradually changes the color from green to red. Linear key frames like LinearColorKeyFrame create a smooth linear transition between values.
  2. During the end of the next half second, DiscreteColorKeyFrame quickly changes the color from red to yellow. Discrete key frames like DiscreteColorKeyFrame create sudden changes between values, that is, the color change in this part of the animation occurs quickly and is not subtle.
  3. During the final two seconds, SplineColorKeyFrame changes the color again�this time from yellow back to green. Spline key frames like SplineColorKeyFrame create a variable transition between values according to the values of the KeySpline property. In this example, the change in color begins slowly and speeds up exponentially toward the end of the time segment.
XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Width="200" Height="200"
  Background="White"
  x:Name="Page">
  <Canvas.Triggers>
    <EventTrigger RoutedEvent="Canvas.Loaded">
      <BeginStoryboard>
        <Storyboard x:Name="ColorStoryboard">
          <ColorAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="Page" Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)">

            <!-- Go from green to red in the first 2 seconds. LinearColorKeyFrame creates
            a smooth, linear animation between values. -->
            <LinearColorKeyFrame Value="Red" KeyTime="00:00:02" />

            <!-- In the next half second, go to yellow. DiscreteColorKeyFrame creates a
            sudden jump between values. -->
            <DiscreteColorKeyFrame Value="Yellow" KeyTime="00:00:2.5" />

            <!-- In the final 2 seconds of the animation, go from yellow back to green. SplineColorKeyFrame
            creates a variable transition between values depending on the KeySpline property. In this example,
            the animation starts off slow but toward the end of the time segment, it speeds up exponentially.-->
            <SplineColorKeyFrame Value="Green" KeyTime="00:00:4.5" KeySpline="0.6,0.0 0.9,0.00" />

          </ColorAnimationUsingKeyFrames>
        </Storyboard>
      </BeginStoryboard>
    </EventTrigger>
  </Canvas.Triggers>
</Canvas>

See Also

Key-Frame Animations Overview
Animation Overview
Interactive Animations Overview


ColorKeyFrame Object (Abstract)

Base class for specific animation key frame techniques that define an animation segment with its own target value and interpolation method for a ColorAnimationUsingKeyFrames.

XAML | Cannot be used in XAML
Scripting | Must use derived objects.

Properties

KeyTime, Name, Value

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

ColorKeyFrame is an abstract class that defines Color value type key frames for three different techniques of key frame animation: DiscreteColorKeyFrame, LinearColorKeyFrame, SplineColorKeyFrame. To animate a Color with key frames, you define a ColorAnimationUsingKeyFrames animation, and populate its KeyFrames property with one or more DiscreteColorKeyFrame, LinearColorKeyFrame, or SplineColorKeyFrame elements that define the key frames.

For more information, see the following ColorKeyFrame derived objects: DiscreteColorKeyFrame, LinearColorKeyFrame, SplineColorKeyFrame.

See Also

Animation Overview, ColorAnimationUsingKeyFrames


ColorKeyFrameCollection Object

Represents a collection of ColorKeyFrame objects that can be individually accessed by index.

XAML
<ColorKeyFrameCollection .../>
  oneOrMoreColorKeyFrames
</ColorKeyFrameCollection/>
Scripting
To create an object using scripting, see CreateFromXAML.

Properties

Count, Name

Methods

Add, Clear, Equals, FindName, GetHost, GetItem, GetValue, Insert, Remove, RemoveAt, SetValue

Remarks

ColorKeyFrameCollection defines no methods or properties beyond the basic Collection methods and properties. Methods such as Add or GetItem will expect or return objects that are of type ColorKeyFrame. ColorKeyFrame itself is an abstract class, so the items might be DiscreteColorKeyFrame, LinearColorKeyFrame, or SplineColorKeyFrame.

The XAML syntax for properties that use a ColorKeyFrameCollection is an example of an implicit collection syntax, where you can omit an actual ColorKeyFrameCollection object element. Instead, you generally include one or more DiscreteColorKeyFrame, LinearColorKeyFrame, or SplineColorKeyFrame object elements as child elements of a ColorAnimationUsingKeyFrames. For more information about XAML implicit collection syntax, see XAML Syntax Overview. (Explicitly including a ColorKeyFrameCollection object element is permissible XAML syntax, and might be useful if you intend to name the collection in XAML and manipulate its contents through script later.)

See Also

Collection, ColorAnimationUsingKeyFrames, Animation Overview


DependencyObject Object (Abstract)

Provides Silverlight property system services.

XAML | Must use derived objects.
Scripting | Must use derived objects.

Properties

Name

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

The DependencyObject class enables Silverlight property system services on its many derived objects, such as UIElement. It provides get and set utility methods for values of any dependency properties that exist on the DependencyObject.

See Also

Referencing and Modifying Silverlight Objects


DiscreteColorKeyFrame Object

Animates from the Color value of the previous key frame to its own Value using discrete interpolation.

XAML | <DiscreteColorKeyFrame .../>
Scripting | To create an object using scripting, see CreateFromXAML.

Properties

KeyTime, Name, Value

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

A key frame defines a segment of the ColorAnimationUsingKeyFrames to which it belongs. Each key frame has a target Value and a KeyTime. The KeyTime specifies the time at which the key frame's Value should be reached. A key frame animates from the target value of the previous key frame to its own target value. It starts when the previous key frame ends and ends when its own key time is reached.

Discrete key frames like DiscreteColorKeyFrame create sudden "jumps" between values (no Interpolation). In other words, the animated property does not change until the key frame's key time is reached at which point the animated property goes suddenly to the target value.

Examples

The following example uses the ColorAnimationUsingKeyFrames class to animate the Background property of a Canvas. This animation uses three key frames in the following manner:

  1. During the first two seconds, LinearColorKeyFrame gradually changes the color from green to red. Linear key frames like LinearColorKeyFrame create a smooth linear transition between values.
  2. During the end of the next half second, DiscreteColorKeyFrame quickly changes the color from red to yellow. Discrete key frames like DiscreteColorKeyFrame create sudden changes between values, that is, the color change in this part of the animation occurs quickly and is not subtle.
  3. During the final two seconds, SplineColorKeyFrame changes the color again�this time from yellow back to green. Spline key frames like SplineColorKeyFrame create a variable transition between values according to the values of the KeySpline property. In this example, the change in color begins slowly and speeds up exponentially toward the end of the time segment.
XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Width="200" Height="200"
  Background="White"
  x:Name="Page">
  <Canvas.Triggers>
    <EventTrigger RoutedEvent="Canvas.Loaded">
      <BeginStoryboard>
        <Storyboard x:Name="ColorStoryboard">
          <ColorAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="Page" Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)">

            <!-- Go from green to red in the first 2 seconds. LinearColorKeyFrame creates
            a smooth, linear animation between values. -->
            <LinearColorKeyFrame Value="Red" KeyTime="00:00:02" />

            <!-- In the next half second, go to yellow. DiscreteColorKeyFrame creates a
            sudden jump between values. -->
            <DiscreteColorKeyFrame Value="Yellow" KeyTime="00:00:2.5" />

            <!-- In the final 2 seconds of the animation, go from yellow back to green. SplineColorKeyFrame
            creates a variable transition between values depending on the KeySpline property. In this example,
            the animation starts off slow but toward the end of the time segment, it speeds up exponentially.-->
            <SplineColorKeyFrame Value="Green" KeyTime="00:00:4.5" KeySpline="0.6,0.0 0.9,0.00" />

          </ColorAnimationUsingKeyFrames>
        </Storyboard>
      </BeginStoryboard>
    </EventTrigger>
  </Canvas.Triggers>
</Canvas>

See Also

Animation Overview, ColorAnimationUsingKeyFrames


DiscreteDoubleKeyFrame Object

Animates from the Double value of the previous key frame to its own Value using discrete interpolation.

XAML | <DiscreteDoubleKeyFrame .../>
Scripting | To create an object using scripting, see CreateFromXAML.

Properties

KeyTime, Name, Value

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

A key frame defines a segment of the DoubleAnimationUsingKeyFrames to which it belongs. Each key frame has a target Value and a KeyTime. The KeyTime specifies the time at which the key frame's Value should be reached. A key frame animates from the target value of the previous key frame to its own target value. It starts when the previous key frame ends and ends when its own key time is reached.

Discrete key frames like DiscreteDoubleKeyFrame create sudden "jumps" between values (no Interpolation). In other words, the animated property does not change until the key frame's key time is reached at which point the animated property goes suddenly to the target value.

Examples

The following example moves a rectangle across a screen. The example uses the DoubleAnimationUsingKeyFrames class to animate the X property of a TranslateTransform applied to a Rectangle. This animation, which repeats indefinitely, uses three key frames in the following manner:

  1. During the first three seconds, uses an instance of the LinearDoubleKeyFrame class to move the rectangle along a path at a steady rate from its starting position to the 500 position. Linear key frames like LinearDoubleKeyFrame create a smooth linear transition between values.
  2. At the end of the fourth second, uses an instance of the DiscreteDoubleKeyFrame class to suddenly move the rectangle to the next position. Discrete key frames like DiscreteDoubleKeyFrame create sudden jumps between values. In this example, the rectangle is at the starting position and then suddenly appears at the 500 position.
  3. In the final two seconds, uses an instance of the SplineDoubleKeyFrame class to move the rectangle back to its starting position. Spline key frames like SplineDoubleKeyFrame create a variable transition between values according to the value of the KeySpline property. In this example, the rectangle begins by moving slowly and then speeds up exponentially toward the end of the time segment.
XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Width="400" Height="300">
  <Rectangle Fill="Blue"
    Width="50" Height="50">
    <Rectangle.RenderTransform>
      <TranslateTransform
        x:Name="MyAnimatedTranslateTransform"
        X="0" Y="0" />
    </Rectangle.RenderTransform>
    <Rectangle.Triggers>
      <EventTrigger RoutedEvent="Rectangle.Loaded">
        <BeginStoryboard>
          <Storyboard>

            <!-- Animate the TranslateTransform's X property
                 from 0 to 350, then 50,
                 then 200 over 10 seconds. -->
            <DoubleAnimationUsingKeyFrames
              Storyboard.TargetName="MyAnimatedTranslateTransform"
              Storyboard.TargetProperty="X"
              Duration="0:0:10">

                <!-- Using a LinearDoubleKeyFrame, the rectangle moves
                     steadily from its starting position to 500 over
                     the first 3 seconds.  -->
                <LinearDoubleKeyFrame Value="500" KeyTime="0:0:3" />

                <!-- Using a DiscreteDoubleKeyFrame, the rectangle suddenly
                     appears at 400 after the fourth second of the animation. -->
                <DiscreteDoubleKeyFrame Value="400" KeyTime="0:0:4" />

                <!-- Using a SplineDoubleKeyFrame, the rectangle moves
                     back to its starting point. The
                     animation starts out slowly at first and then speeds up.
                     This KeyFrame ends after the 6th
                     second. -->
                <SplineDoubleKeyFrame KeySpline="0.6,0.0 0.9,0.00" Value="0" KeyTime="0:0:6" />

            </DoubleAnimationUsingKeyFrames>
          </Storyboard>
        </BeginStoryboard>
      </EventTrigger>
    </Rectangle.Triggers>
  </Rectangle>
</Canvas>

See Also

Animation Overview, DoubleAnimationUsingKeyFrames


DiscretePointKeyFrame Object

Animates from the Point value of the previous key frame to its own Value using discrete interpolation.

XAML | <DiscretePointKeyFrame .../>
Scripting | To create an object using scripting, see CreateFromXAML.

Properties

KeyTime, Name, Value

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

A key frame defines a segment of the PointAnimationUsingKeyFrames to which it belongs. Each key frame has a target Value and a KeyTime. The KeyTime specifies the time at which the key frame's Value should be reached. A key frame animates from the target value of the previous key frame to its own target value. It starts when the previous key frame ends and ends when its own key time is reached.

Discrete key frames like DiscretePointKeyFrame create sudden "jumps" between values (no Interpolation). In other words, the animated property does not change until the key frame's key time is reached at which point the animated property goes suddenly to the target value.

Examples

The following example moves an ellipse along a triangular path. The example uses the PointAnimationUsingKeyFrames class to animate the Center property of an EllipseGeometry. This animation uses three key frames in the following manner:

  1. During the first half second, uses an instance of the LinearPointKeyFrame class to move the ellipse along a path at a steady rate from its starting position. Linear key frames like LinearPointKeyFrame create a smooth linear interpolation between values.
  2. During the end of the next half second, uses an instance of the DiscretePointKeyFrame class to suddenly move the ellipse along the path to the next position. Discrete key frames like DiscretePointKeyFrame create sudden jumps between values.
  3. During the final two seconds, uses an instance of the SplinePointKeyFrame class to move the ellipse back to its starting position. Spline key frames like SplinePointKeyFrame create a variable transition between values according to the values of the KeySpline property. In this example, the animation begins slowly and speeds up exponentially toward the end of the time segment.
XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Width="400" Height="300">
  <Path Fill="Blue">
    <Path.Data>

      <!-- Describes an ellipse. -->
      <EllipseGeometry x:Name="MyAnimatedEllipseGeometry"
       Center="200,100" RadiusX="15" RadiusY="15" />
    </Path.Data>

    <Path.Triggers>
      <EventTrigger RoutedEvent="Path.Loaded">
        <BeginStoryboard>
          <Storyboard>

            <!-- Animating the Center property uses 3 KeyFrames, which animate
                 the ellipse allong a triangular path. -->
            <PointAnimationUsingKeyFrames
              Storyboard.TargetProperty="Center"
              Storyboard.TargetName="MyAnimatedEllipseGeometry"
              Duration="0:0:5" RepeatBehavior="Forever">

              <!-- Over the first half second, Using a LinearPointKeyFrame, the ellipse
                   moves steadily from its starting position along the first line of the
                   trianglar path.  -->
              <LinearPointKeyFrame
                KeyTime="0:0:0.5"
                Value="100,300" />

              <!-- Using a DiscretePointKeyFrame, the ellipse suddenly changes position
                   after the first second of the animation. -->
              <DiscretePointKeyFrame
                KeyTime="0:0:1"
                Value="400,300" />

              <!-- Using a SplinePointKeyFrame, the ellipse moves back to its starting
                   position. It moves slowly at first and then speeds up. This key frame
                   takes 2 seconds to complete. -->
              <SplinePointKeyFrame
                KeySpline="0.6,0.0 0.9,0.00"
                KeyTime="0:0:3"
                Value="200,100" />
            </PointAnimationUsingKeyFrames>
          </Storyboard>
        </BeginStoryboard>
      </EventTrigger>
    </Path.Triggers>
  </Path>
</Canvas>

See Also

Animation Overview, PointAnimationUsingKeyFrames


Double Structure

Silverlight SDK

Double Class

Represents a double-precision floating-point number.

XAML
<object property = "nnnn" ... />
-or-
<object property = "nnnn.nnnn" .... />
Scripting
See Remarks

Remarks

Double does not have any callable APIs.

Silverlight defines Double as a class in order to provide type conversion behavior for XAML and to support animating a Double. For property values or method parameters in scripting, use a floating-point value (you do not need to specify a decimal point, integers are evaluated correctly). For attributes, use a string value, again either with or without a decimal point. A Double value is inherently signed, however, not all properties that use the Double type will accept negative values. See Remarks or Property Value sections of the specific property for guidance.

For Double values that specify pixels or measurements for objects that are rendered onscreen, values that exceed one million are not respected.

See Also

XAML Syntax Overview


DoubleAnimation Object

Animates the value of a Double property between two target values by using linear interpolation over a specified Duration.

XAML | <DoubleAnimation .../>
Scripting | To create an object using scripting, see the CreateFromXAML method.

Properties

AutoReverse, BeginTime, By, Duration, FillBehavior, From, Name, RepeatBehavior, SpeedRatio, Storyboard.TargetName, Storyboard.TargetProperty, To

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

An animation updates the value of a property over a period of time. An animation effect can be subtle, such as moving a Shape a few pixels left or right, or dramatic, such as enlarging an object to 200 times its original size while spinning it and changing its color. To create an animation, you associate an animation with an object's property value.

The DoubleAnimation class creates a transition between two target values. To set the target values, use the object's From, To, and By properties. The following table summarizes how the From, To, and By properties may be used together or separately to determine an animation's target values.

Properties specified | Resulting behavior
From | The animation progresses from the value specified by the From property to the base value of the property being animated.
From and To | The animation progresses from the value specified by the From property to the value specified by the To property.
From and By | The animation progresses from the value specified by the From property to the value specified by the sum of the From and By properties.
To | The animation progresses from the animated property's base value or a previous animation's output value to the value specified by the To property.
By | The animation progresses from the base value of the property being animated or a previous animation's output value to the sum of that value and the value specified by the By property.

Note If you set both the To and By properties, the To property takes precedence and the By property is ignored.

To use other interpolation methods or to animate between more than two target values, use a DoubleAnimationUsingKeyFrames object.

Examples

The following example shows how to use DoubleAnimation to create a rectangle that fades in and out of view after it is loaded.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Rectangle
    x:Name="MyAnimatedRectangle"
    Width="100"
    Height="100"
    Fill="Blue">
    <Rectangle.Triggers>

      <!-- Animates the rectangle's opacity. -->
      <EventTrigger RoutedEvent="Rectangle.Loaded">
        <BeginStoryboard>
          <Storyboard>
            <DoubleAnimation
              Storyboard.TargetName="MyAnimatedRectangle"
              Storyboard.TargetProperty="Opacity"
              From="1.0" To="0.0" Duration="0:0:5" AutoReverse="True" RepeatBehavior="Forever" />
          </Storyboard>
        </BeginStoryboard>
      </EventTrigger>
    </Rectangle.Triggers>
  </Rectangle>
</Canvas>

The following example makes a rectangle fade from view when the user presses the left mouse button over it. Unlike the previous example, the animation does not start automatically.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Canvas.Resources>
    <Storyboard x:Name="myStoryboard">
      <DoubleAnimation
        Storyboard.TargetName="MyAnimatedRectangle"
        Storyboard.TargetProperty="Opacity"
        From="1.0" To="0.0" Duration="0:0:5"
        AutoReverse="True" />
    </Storyboard>
  </Canvas.Resources>
  <Rectangle
    x:Name="MyAnimatedRectangle"
    Width="100"
    Height="100"
    Fill="Blue"
    MouseLeftButtonDown="startAnimation">
  </Rectangle>
</Canvas>
JavaScript
function startAnimation(sender, mouseEventArgs)
{
    // Retrieve the Storyboard and begin it.
    sender.findName("myStoryboard").begin();

}

See Also

Animation Overview
Interactive Animations Overview


DoubleAnimationUsingKeyFrames Object

Animates the value of a Double property along a set of KeyFrames.

XAML
<DoubleAnimationUsingKeyFrames ...>
  oneOrMoreDoubleKeyFrames
</DoubleAnimationUsingKeyFrames>
Scripting
To create an object using scripting, see CreateFromXAML.

Properties

AutoReverse, BeginTime, Duration, FillBehavior, KeyFrames, Name, RepeatBehavior, SpeedRatio, Storyboard.TargetName, Storyboard.TargetProperty

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

A key frame animation's target values are defined by its KeyFrames property, which contains a collection of DoubleKeyFrame objects. Each DoubleKeyFrame defines a segment of the animation with its own target Value and KeyTime. When the animation runs, it progresses from one key value to the next at the specified key times.

There are three types of DoubleKeyFrame classes, one for each supported interpolation method: LinearDoubleKeyFrame, DiscreteDoubleKeyFrame, and SplineDoubleKeyFrame.

Examples

The following example moves a rectangle across a screen. The example uses the DoubleAnimationUsingKeyFrames class to animate the X property of a TranslateTransform applied to a Rectangle. This animation, which repeats indefinitely, uses three key frames in the following manner:

  1. During the first three seconds, uses an instance of the LinearDoubleKeyFrame class to move the rectangle along a path at a steady rate from its starting position to the 500 position. Linear key frames like LinearDoubleKeyFrame create a smooth linear transition between values.
  2. At the end of the fourth second, uses an instance of the DiscreteDoubleKeyFrame class to suddenly move the rectangle to the next position. Discrete key frames like DiscreteDoubleKeyFrame create sudden jumps between values. In this example, the rectangle is at the starting position and then suddenly appears at the 500 position.
  3. In the final two seconds, uses an instance of the SplineDoubleKeyFrame class to move the rectangle back to its starting position. Spline key frames like SplineDoubleKeyFrame create a variable transition between values according to the value of the KeySpline property. In this example, the rectangle begins by moving slowly and then speeds up exponentially toward the end of the time segment.
XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Width="400" Height="300">
  <Rectangle Fill="Blue"
    Width="50" Height="50">
    <Rectangle.RenderTransform>
      <TranslateTransform
        x:Name="MyAnimatedTranslateTransform"
        X="0" Y="0" />
    </Rectangle.RenderTransform>
    <Rectangle.Triggers>
      <EventTrigger RoutedEvent="Rectangle.Loaded">
        <BeginStoryboard>
          <Storyboard>

            <!-- Animate the TranslateTransform's X property
                 from 0 to 350, then 50,
                 then 200 over 10 seconds. -->
            <DoubleAnimationUsingKeyFrames
              Storyboard.TargetName="MyAnimatedTranslateTransform"
              Storyboard.TargetProperty="X"
              Duration="0:0:10">

                <!-- Using a LinearDoubleKeyFrame, the rectangle moves
                     steadily from its starting position to 500 over
                     the first 3 seconds.  -->
                <LinearDoubleKeyFrame Value="500" KeyTime="0:0:3" />

                <!-- Using a DiscreteDoubleKeyFrame, the rectangle suddenly
                     appears at 400 after the fourth second of the animation. -->
                <DiscreteDoubleKeyFrame Value="400" KeyTime="0:0:4" />

                <!-- Using a SplineDoubleKeyFrame, the rectangle moves
                     back to its starting point. The
                     animation starts out slowly at first and then speeds up.
                     This KeyFrame ends after the 6th
                     second. -->
                <SplineDoubleKeyFrame KeySpline="0.6,0.0 0.9,0.00" Value="0" KeyTime="0:0:6" />

            </DoubleAnimationUsingKeyFrames>
          </Storyboard>
        </BeginStoryboard>
      </EventTrigger>
    </Rectangle.Triggers>
  </Rectangle>
</Canvas>

See Also

Key-Frame Animations Overview
Animation Overview
Interactive Animations Overview


DoubleKeyFrame Object (Abstract)

Base class for specific animation key frame techniques that define an animation segment with its own target value and interpolation method for a DoubleAnimationUsingKeyFrames.

XAML | Cannot be used in XAML
Scripting | See derived types.

Properties

KeyTime, Name, Value

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

DoubleKeyFrame is an abstract class that defines Double value type key frames for three different techniques of key frame animation: DiscreteDoubleKeyFrame, LinearDoubleKeyFrame, SplineDoubleKeyFrame. To animate a Double with key frames, you define a DoubleAnimationUsingKeyFrames animation, and populate its KeyFrames property with one or more DiscreteDoubleKeyFrame, LinearDoubleKeyFrame, or SplineDoubleKeyFrame elements that define the key frames.

For more information, see the following DoubleKeyFrame derived objects: DiscreteDoubleKeyFrame, LinearDoubleKeyFrame, SplineDoubleKeyFrame.

See Also

Animation Overview, DoubleAnimationUsingKeyFrames


DoubleKeyFrameCollection Object

Represents a collection of DoubleKeyFrame objects that can be individually accessed by index.

XAML
<DoubleKeyFrameCollection ...>
  oneOrMoreDoubleKeyFrames
</DoubleKeyFrameCollection>
Scripting
To create an object using scripting, see CreateFromXAML.

Properties

Count, Name

Methods

Add, Clear, Equals, FindName, GetHost, GetItem, GetValue, Insert, Remove, RemoveAt, SetValue

Remarks

DoubleKeyFrameCollection defines no methods or properties beyond the basic Collection methods and properties. Methods such as Add or GetItem will expect or return objects that are of type DoubleKeyFrame. DoubleKeyFrame itself is an abstract class, so the items might be DiscreteDoubleKeyFrame, LinearDoubleKeyFrame, or SplineDoubleKeyFrame.

The XAML syntax for properties that use a DoubleKeyFrameCollection is an example of an implicit collection syntax, where you can omit an actual DoubleKeyFrameCollection object element. Instead, you generally include one or more DiscreteDoubleKeyFrame, LinearDoubleKeyFrame, or SplineDoubleKeyFrame object elements as child elements of a DoubleAnimationUsingKeyFrames. For more information about XAML implicit collection syntax, see XAML Syntax Overview. (Explicitly including a DoubleKeyFrameCollection object element is permissible XAML syntax, and might be useful if you intend to name the collection in XAML and manipulate its contents through script later.)

See Also

Collection, DoubleAnimationUsingKeyFrames, Animation Overview


Downloader Object

Represents the set of download functionality for a Silverlight plug-in. The downloader can asynchronously download content that can be obtained through an HTTP GET request.

HTML | You cannot use this object in HTML.
Scripting | To create an object using scripting, see CreateObject.

Properties

DownloadProgress, Name, ResponseText Status, StatusText, Uri

Methods

Abort, Equals, FindName, GetHost, GetResponseText, GetValue, Open, Send, SetValue

Events

Completed, DownloadFailed, DownloadProgressChanged

Remarks

The Downloader object is a special-purpose Silverlight object that provides the ability to download content, such as XAML content, JavaScript content, or media assets, such as images. By using the Downloader object you do not have to provide all application content when the Silverlight plug-in is instantiated. Rather, you can download content on demand in response to application needs. More importantly, you can render downloaded content without the need to refresh the entire Web page. The Downloader object provides functionality for initiating the data transfer, monitoring the progress of the data transfer, and retrieving the downloaded content.

The properties and methods of the Downloader object are modeled after the XMLHttpRequest (XHR) set of APIs. XMLHttpRequest provides JavaScript and other web browser scripting languages the ability to transfer and manipulate XML data to and from a web server using HTTP.

Generally you do not specify the URI scheme of the Downloader source URI; you instead use relative pathing, and use the URI scheme that is being used by the host HTML page that contains the Silverlight plug-in. The Downloader cannot be used to download files across domains (cannot access content that is not from the site of origin for the hosting HTML page). For information about URI limitations and other aspects of using the Downloader object, see Using a Downloader Object.

Performance Tip When using the Downloader object, after the Completed event fires, detach all event handlers from the Downloader and then set Downloader to null.

Examples

The following JavaScript example shows how to create, initialize, and execute a download request. This example hooks event handlers for two events ( Completed, DownloadProgressChanged), but these handlers are not shown in this example. Also, there is a third event DownloadFailed that it is sometimes prudent to define a handler for. See the complete example in the topic Using a Downloader Object.

JavaScript
// Event handler for initializing and executing a download request.
function onMouseLeftButtonUp(sender, eventArgs)
{
    // Retrieve a reference to the plug-in.
    var slPlugin = sender.getHost();

    // Create a Downloader object.
    var downloader = slPlugin.createObject("downloader");

    // Add DownloadProgressChanged and Completed events.
    downloader.addEventListener("downloadProgressChanged", onDownloadProgressChanged);
    downloader.addEventListener("completed", onCompleted);

    // Initialize the Downloader request.
    // NOTE: downloader APIs disallow file:\\ scheme
    // you must run this sample over localhost: or off a server or the following call will fail

    downloader.open("GET", "promo.png");

    // Execute the Downloader request.
    downloader.send();
}

See Also

CreateFromXamlDownloader, CreateObject, SetSource (Image), SetSource (MediaElement), Using a Downloader Object


DrawingAttributes Object

Represents the appearance of a Stroke.

Syntax

XAML
<DrawingAttributes .../>
Scripting
To create an object using scripting, see CreateFromXAML.

Properties

Color, Height, Name, OutlineColor, Width

Methods

Equals, FindName, GetHost, GetValue, SetValue

Examples

The following JavaScript example simulates 3 different pen types (pen, marker and highlighter) by setting the Color, Height, OutlineColor and Width DrawingAttributes properties . First a DrawingAttributes object is created, then it is appended to the Stroke object. The DrawingAttributes properties are then set by one of the three events that simulate a pen type. The EraseCanvas event clears all the Strokes from the Canvas.

JavaScript
var agCtrl;
var inkPresenter; // Corresponds to InkPresenter element in xaml
var newStroke = null; // The Stroke variable we'll use here in mouse handlers
// DrawingAttributes variables
var daWidth = 2;
var daHeight = 2;
var daColor = "Black";
var daOutlineColor = "Black";

function root_Loaded(sender, args)
{
    // Get the html object which contains the Silverlight plug-in
    agCtrl = sender.GetHost();
    inkPresenter = sender.findname("inkPresenterElement");
}

// Capture mouse movement when the left button is pressed and create the stroke
function InkPresenterMouseDown(sender,args)
{
   inkPresenter.CaptureMouse();

   newStroke = agCtrl.content.createFromXaml('<Stroke/>');

   var da = agCtrl.content.CreateFromXaml('<DrawingAttributes/>');
   newStroke.DrawingAttributes = da;

   // Set the drawing attributes properties
   newStroke.DrawingAttributes.Width = daWidth;
   newStroke.DrawingAttributes.Height = daHeight;
   newStroke.DrawingAttributes.Color = daColor;
   newStroke.DrawingAttributes.OutlineColor = daOutlineColor;

   newStroke.StylusPoints.AddStylusPoints(args.GetStylusPoints(inkPresenter));
   inkPresenter.Strokes.Add(newStroke);
}

// Add the new points to the Stroke we're working with
function InkPresenterMouseMove(sender,args)
{
   if (newStroke != null)
   {
      newStroke.StylusPoints.AddStylusPoints(args.GetStylusPoints(inkPresenter));
   }
}

// Release the mouse
function InkPresenterMouseUp(sender,args)
{
   newStroke = null;
   inkPresenter.ReleaseMouseCapture();
}

// Set the Drawing Attributes for a pen
function SelectPen(sender, args)
{
  daWidth = 1;
  daHeight = 1;
  daColor = "Black";
  daOutlineColor = "Black";
}

// Set the Drawing Attributes for a marker
function SelectMarker(sender, args)
{
  daWidth = 10;
  daHeight = 4;
  daColor = "Blue";
  daOutlineColor = "Blue";
}

// Set the Drawing Attributes for a highlighter
function SelectHighlighter(sender, args)
{
  daWidth = 25;
  daHeight = 5;
  daColor = "Yellow";
  daOutlineColor = "Yellow";
}

// Erase all strokes from the canvas
function EraseCanvas(sender, args)
{
  inkPresenter.Strokes.Clear();
}

The XAML sample below creates the canvas and 4 buttons that are used to select the different pen types and the erase all feature that is simulated by the Javascript events above.

XAML
<Canvas xmlns="http://schemas.microsoft.com/client/2007"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Loaded="root_Loaded"
        x:Name="root"
        Width="600" Height="400">
  <InkPresenter
         x:Name="inkPresenterElement"
        Background="transparent"
        Width="600" Height="400"
        MouseLeftButtonDown="InkPresenterMouseDown"
        MouseMove="InkPresenterMouseMove"
        MouseLeftButtonUp="InkPresenterMouseUp"/>

<!-- Pen Button -->
    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="40"
      Stroke="Gray" Fill="Black" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>
    <TextBlock
      Height="21" Width="78"
      Canvas.Top="380" Canvas.Left="71"
      Foreground="Gray"
      FontFamily="Verdana" FontSize="12">Select Pen</TextBlock>

    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="40"
      x:Name="selectPen" MouseLeftButtonDown="SelectPen"
      Stroke="Transparent" Fill="Transparent" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>

<!-- Marker Button -->
    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="170"
      Stroke="Gray" Fill="Black" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>

    <TextBlock
      Height="21" Width="78"
      Canvas.Top="380" Canvas.Left="191"
      Foreground="Gray"
      FontFamily="Verdana" FontSize="12">Select Marker</TextBlock>

    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="170"
      x:Name="selectMarker" MouseLeftButtonDown="SelectMarker"
      Stroke="Transparent" Fill="Transparent" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>

<!-- Highlighter Button -->
    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="300"
      Stroke="Gray" Fill="Black" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>

    <TextBlock
      Height="21" Width="78"
      Canvas.Top="380" Canvas.Left="310"
      Foreground="Gray"
      FontFamily="Verdana" FontSize="12">Select Highlighter</TextBlock>

    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="300"
      x:Name="selectHighlighter" MouseLeftButtonDown="SelectHighlighter"
      Stroke="Transparent" Fill="Transparent" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>

<!-- Erase Canvas Button -->
    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="430"
      Stroke="Gray" Fill="Black" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>

    <TextBlock
      Height="21" Width="78"
      Canvas.Top="380" Canvas.Left="463"
      Foreground="Gray"
      FontFamily="Verdana" FontSize="12">Erase All</TextBlock>

    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="430"
      x:Name="eraseCanvas" MouseLeftButtonDown="EraseCanvas"
      Stroke="Transparent" Fill="Transparent" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>
</Canvas>

See Also

Stroke, Color, Height, Width, OutlineColor, DrawingAttributes(Stroke)


Duration Object

Represents the duration of time that a Timeline is active.

XAML
<object property="[days.]hours:minutes:seconds[.fractionalSeconds]" .../>
- or -
<object property="days" .../>
- or -
<object property="Automatic" .../>
- or -
<object property="Forever" .../>
Scripting
See Remarks.

Properties

Name, Seconds

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

Creating a Duration, KeyTime, RepeatBehavior, or TimeSpan in XAML or in script is only possible through a type conversion syntax when setting a property such as Duration that takes one of these types, with the value specified as a string. The string format for specifying a time in each of these types is identical. Duration can also take the literals "Automatic" and "Forever". RepeatBehavior can take the literal "Forever" and also an iterations syntax "#x".

The main scenario for working with a Duration as an object in script is to get or set its Seconds property in order to query or change an existing animation value.

See Also

Animation Overview


Ellipse Object

Draws an ellipse.

XAML | <Ellipse .../>
Scripting | To create an object using scripting, see CreateFromXAML.

Properties

Canvas.Left, Canvas.Top, Canvas.ZIndex, Clip, Cursor, Fill, Height, Name, Opacity, OpacityMask, RenderTransform, RenderTransformOrigin, Resources, Stretch, Stroke, StrokeDashArray, StrokeDashCap, StrokeDashOffset, StrokeEndLineCap, StrokeLineJoin, StrokeMiterLimit, StrokeStartLineCap, StrokeThickness, Tag, Triggers, Width

Methods

AddEventListener, CaptureMouse, Equals, FindName, GetHost, GetParent, GetValue, ReleaseMouseCapture, RemoveEventListener, SetValue

Events

Loaded, MouseEnter, MouseLeave, MouseLeftButtonDown, MouseLeftButtonUp, MouseMove

Examples

The following example shows how to create an Ellipse.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <Ellipse
    Fill="Yellow"
    Height="100"
    Width="200"
    StrokeThickness="2"
    Stroke="Black"/>
</Canvas>

See Also

Shape, Shapes Overview


EllipseGeometry Object

Represents the geometry of a circle or ellipse.

XAML | <EllipseGeometry .../>
Scripting | To create an object using scripting, see CreateFromXAML.

Properties

Center, FillRule Name, RadiusX, RadiusY, Transform

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

FillRule is technically a property inherited from the base Geometry class, but setting it has no effect on an EllipseGeometry.

Examples

The following example shows how to create an ellipse using EllipseGeometry.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <Path Fill="Gold" Stroke="Black" StrokeThickness="1">
    <Path.Data>
      <EllipseGeometry Center="50,50" RadiusX="50" RadiusY="50" />
    </Path.Data>
  </Path>
</Canvas>

See Also

Geometry Overview, Geometry, GeometryCollection, GeometryGroup, Ellipse


ErrorEventArgs Object

Provides data for the onError event.

XAML | You cannot use this object in XAML.
Scripting | Obtained as arguments for certain event handlers.

Properties

Properties

ErrorCode, ErrorMessage, ErrorType, Name,

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

ErrorEventArgs is the base error event argument class for Silverlight. ParserErrorEventArgs and RuntimeErrorEventArgs both inherit from ErrorEventArgs and contain all of its properties in addition to the properties they define themselves.

Examples

The following JavaScript example shows how to create an onError event handler that displays specific error information pertaining to the type of error. The ErrorType property on the ErrorEventArgs is used to determine the type of error.

JavaScript
function OnErrorEventHandler(sender, errorArgs)
{
    // The error message to display.
    var errorMsg = "Silverlight Error: \n\n";

    // Error information common to all errors.
    errorMsg += "Error Type:    " + errorArgs.errorType + "\n";
    errorMsg += "Error Message: " + errorArgs.errorMessage + "\n";
    errorMsg += "Error Code:    " + errorArgs.errorCode + "\n";

    // Determine the type of error and add specific error information.
    switch(errorArgs.errorType)
    {
        case "RuntimeError":
            // Display properties specific to RuntimeErrorEventArgs.
            if (errorArgs.lineNumber != 0)
            {
                errorMsg += "Line: " + errorArgs.lineNumber + "\n";
                errorMsg += "Position: " +  errorArgs.charPosition + "\n";
            }
            errorMsg += "MethodName: " + errorArgs.methodName + "\n";
            break;
        case "ParserError":
            // Display properties specific to ParserErrorEventArgs.
            errorMsg += "Xaml File:      " + errorArgs.xamlFile      + "\n";
            errorMsg += "Xml Element:    " + errorArgs.xmlElement    + "\n";
            errorMsg += "Xml Attribute:  " + errorArgs.xmlAttribute  + "\n";
            errorMsg += "Line:           " + errorArgs.lineNumber    + "\n";
            errorMsg += "Position:       " + errorArgs.charPosition  + "\n";
            break;
        default:
            break;
    }
    // Display the error message.
    alert(errorMsg);
}

See Also

ParserErrorEventArgs, RuntimeErrorEventArgs


EventTrigger Object

Represents a trigger that applies a set of actions in response to an event.

XAML
<EventTrigger>
Actions
</EventTrigger>
Scripting
To create an object using scripting, see CreateFromXAML.

Properties

Actions, Name, RoutedEvent

Methods

Equals, FindName, GetHost, GetValue, SetValue

Examples

The following example shows how to use a Storyboard and an EventTrigger to make a rectangle that fades in and out of view after it is loaded.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Rectangle
    x:Name="MyAnimatedRectangle"
    Width="100"
    Height="100"
    Fill="Blue">
    <Rectangle.Triggers>

      <!-- Animates the rectangle's opacity. -->
      <EventTrigger RoutedEvent="Rectangle.Loaded">
        <BeginStoryboard>
          <Storyboard>
            <DoubleAnimation
              Storyboard.TargetName="MyAnimatedRectangle"
              Storyboard.TargetProperty="Opacity"
              From="1.0" To="0.0" Duration="0:0:5" AutoReverse="True" RepeatBehavior="Forever" />
          </Storyboard>
        </BeginStoryboard>
      </EventTrigger>
    </Rectangle.Triggers>
  </Rectangle>
</Canvas>

See Also

Animation Overview, Interactive Animations Overview


Geometry Object (Abstract)

Classes that derive from this abstract base class define geometric shapes. Geometry objects can be used for clipping, hit-testing, and rendering 2-D graphic data.

XAML | Cannot be used in XAML. See Remarks.
Scripting | Must use derived objects.

Properties

Name, FillRule, Transform

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

For XAML syntaxes that take a Geometry, you need to specify a nonabstract derived type of Geometry as an object element. For details, see the XAML syntax on the reference pages for EllipseGeometry, GeometryGroup, LineGeometry, PathGeometry, or RectangleGeometry.

For more information, see the following Geometry objects: EllipseGeometry, GeometryGroup, LineGeometry, PathGeometry, RectangleGeometry.

Geometry is abstract, and is not returned as that object type by any APIs in Silverlight 1.0. You also cannot create a true Geometry in XAML. For this reason, Geometry is not listed in the "Applies To" lists for APIs that Geometry itself defines, because it is abstract and those APIs can only be exercised on a practical derived class.

See Also

Geometry Overview, Path Markup Syntax


GeometryCollection Object

Represents a collection of Geometry objects.

XAML
<GeometryCollection ...>
  oneOrMoreGeometries
</GeometryCollection>
Scripting
To create an object using scripting, see CreateFromXAML.

Properties

Count, Name

Methods

Add, Equals, FindName, GetHost, GetItem, GetValue, Insert, Remove, RemoveAt, SetValue

GetValue, SetValue

Remarks

GeometryCollection defines no methods or properties beyond the basic Collection methods and properties. Methods such as Add or GetItem will expect or return objects that are of type Geometry. Geometry itself is an abstract class, so the items might be any of the Geometry defined types (for details, see Geometry or Silverlight Geometries Overview).

The XAML syntax for properties that use a GeometryCollection is an example of an implicit collection syntax, where you can omit an actual GeometryCollection object element. Instead, you generally include one or more geometry-type object elements as child elements of a GeometryGroup. For more information about XAML implicit collection syntax, see XAML Syntax Overview. (Explicitly including a GeometryCollection object element is permissible XAML syntax, and might be useful if you intend to name the collection in XAML and manipulate its contents through script later.)

A GeometryCollection is not itself a composite geometry, but is used by the GeometryGroup class to store Geometry objects that define a composite geometry.

See Also

Geometry Overview, Geometry, GeometryGroup, PathGeometry


GeometryGroup Object

Represents a composite geometry, composed of other Geometry objects.

XAML
<GeometryGroup ...>
  oneOrMoreGeometries
</GeometryGroup>
Scripting
To create an object using scripting, see CreateFromXAML.

Properties

Children, FillRule Name, Transform

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

FillRule is relevant for a GeometryGroup because the combined geometry can potentially have segment combinations where the application of a fill rule will have an effect.

In XAML usages, GeometryGroup uses Children as its content property and supports implicit collection usage. Therefore, to declare transforms that will be in a GeometryGroup in XAML, you declare one or more geometries as object elements, placing them in order as the child elements of the GeometryGroup. Nesting GeometryGroups is permitted.

Examples

Composite geometry objects can be created using a GeometryGroup. The GeometryGroup object creates an amalgamation of the Geometry objects it contains without combining their area. Any number of Geometry objects can be added to a GeometryGroup. The following example uses a GeometryGroup to create a composite Geometry.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Path Stroke="Black" StrokeThickness="1" Fill="#CCCCFF">
    <Path.Data>

      <!-- Creates a composite shape from three geometries. -->
      <GeometryGroup FillRule="EvenOdd">
        <LineGeometry StartPoint="10,10" EndPoint="50,30" />
        <EllipseGeometry Center="40,70" RadiusX="30" RadiusY="30" />
        <RectangleGeometry Rect="30,55 100 30" />
      </GeometryGroup>
    </Path.Data>
  </Path>
</Canvas>

A composite Geometry

See Also

Geometry Overview, EllipseGeometry, Geometry, GeometryCollection, LineGeometry, PathGeometry, RectangleGeometry


Glyphs Object

Represents a set of glyphs that are used for rendering fixed text.

XAML | <Glyphs .../>
Scripting | To create an object using scripting, see CreateFromXAML.

Properties

Canvas.Left, Canvas.Top, Canvas.ZIndex, Clip, Cursor, Fill, FontRenderingEmSize, FontUri, Height, Indices, Name, Opacity, OpacityMask, OriginX, OriginY, RenderTransform, RenderTransformOrigin, Resources, StyleSimulations, Tag, Triggers, UnicodeString, Width

Methods

AddEventListener, CaptureMouse, Equals, FindName, GetHost, GetParent, GetValue, ReleaseMouseCapture, RemoveEventListener, SetValue

Events

Loaded, MouseEnter, MouseLeave, MouseLeftButtonDown, MouseLeftButtonUp, MouseMove

Remarks

Glyphs does not have a content property (you do not define the glyphs by declaring text as the inner text of a Glyphs object element). Instead, you specify the individual glyphs through one of two properties:

  • UnicodeString: a string value, which captures the Unicode in an XML-compatible encoding.
  • Indices: also a string, but this property uses a specialized mini-language that references glyphs by their font index order, and also optionally specifies advance and offset spacings.

Of these techniques, using UnicodeString is probably the most common, because it is the easiest to capture from the output of applications that are used to compose text.

In addition to the glyph information, a Glyphs element must always specify a FontUri. There is no default or fallback characteristic that will provide a valid value. If you are defining Glyphs in XAML, failure to specify FontUri, and/or failure to specify any glyph information either by UnicodeString or GlyphIndex values in Indices, will raise a parser error.

One way to use Glyphs is to use the XPS document format output of a document producing application such as Microsoft Office Word 2007. The XPS format produces packages that define the document, and one of the parts of this package format is a XAML page that declares a FixedPage element defined by the XPS schema (this schema has the namespace http://schemas.microsoft.com/xps/2005/06). Glyphs is also an element of that schema. You can open up the package, find your FixedPage parts, extract the Glyphs from them, and paste the Glyphs into your Silverlight XAML. Note that the XPS Glyphs uses some attributes that are not part of the Silverlight XAML subset, such as BidiLevel, so you might have to remove some attributes before the transferred Glyphs is valid for Silverlight. Also, note that the transferred Glyphs will frequently reference a FontUri already. The URI it references is another part of the XPS package, and it generally references a font that is obfuscated, subsetted and packaged explicitly for the XPS content that was authored. To use this same Glyphs in Silverlight, extract that font information from the XPS package, save it as a file with the appropriate extension, and make that font information available and downloadable as part of your application. Depending on your deployment and application structure, you might need to slightly adjust the pathing in the FontUri output from the original XPS, but do not change the filename or extension of the obfuscated font file; changing the name will almost always invalidate the file.

Another technique for obtaining the necessary parts for Glyphs usage in Silverlight is to use the XPS printer driver that is a component of Microsoft Windows Vista.

Note that the default Fill for Glyphs is null, and the default FontRenderingEmSize is 0. Therefore in order to render anything with Glyphs you should specify working values either in XAML or script. This is in contrast to TextBlock, which defaults to Black and 14.666 for its analogous properties.

Note As with most types of software, font files are licensed, rather than sold, and licenses that govern the use of fonts vary from vendor to vendor. As a developer it is your responsibility to ensure that you have the required license rights for any font you embed within a document or application, or otherwise redistribute.

Examples

The following example defines a Glyphs element in XAML. The source for this Glyphs output is an XPS package, which was then modified slightly for Silverlight XAML conformance and FontUri pathing. The referenced FontUri is the GUID-named subsetted font that was also produced in the XPS output. The Indices attribute is also set based on that output. The Indices adjust the advances (not the actual glyph index information), with the glyphs information in the UnicodeString.

XAML
  <Canvas
    xmlns="http://schemas.microsoft.com/client/2007"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
        <Glyphs Fill="#FF000000"
  FontUri="Resources/23460227-2793-4F9D-DB34-7D3834712823.odttf"
  FontRenderingEmSize="18" StyleSimulations="None" OriginX="72.024"
  OriginY="87.624" UnicodeString="Hello, World!"
  Indices=",85.333;,64;,57.333;,57.333;,70.667;,30.667;,25.333;,113.33;,70.667;,68;,57.333;,70.667;">
  </Glyphs>
  </Canvas>

This code produces the following fixed text:

Gradient stops in a linear gradient

See Also

Text and Fonts Overview


GradientStop Object

Describes the location and color of a transition point in a gradient.

XAML | <GradientStop .../>
Scripting | To create an object using scripting, see CreateFromXAML.

Properties

Color, Name, Offset

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

Use this class to describe the colors in a LinearGradientBrush or RadialGradientBrush.

Note GradientStop does not provide an opacity property; to make a GradientStop semi-transparent, set its GradientStop.Color property with a transparent Color.

For more information on GradientStop, see Linear Gradients.

Examples

The following example creates a linear gradient with four colors and uses it to paint a Rectangle.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <!-- This rectangle is painted with a diagonal linear gradient. -->
  <Rectangle Width="200" Height="100">
    <Rectangle.Fill>
      <LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
        <GradientStop Color="Yellow" Offset="0.0" />
        <GradientStop Color="Red" Offset="0.25" />
        <GradientStop Color="Blue" Offset="0.75" />
        <GradientStop Color="LimeGreen" Offset="1.0" />
      </LinearGradientBrush>
    </Rectangle.Fill>
  </Rectangle>
</Canvas>

This code produces the following gradient with the highlighted gradient stops:

Gradient stops in a linear gradient

See Also

Brush Overview, RadialGradientBrush, LinearGradientBrush


GradientStopCollection Object

Represents a collection of GradientStop objects that can be individually accessed by index.

XAML
<GradientStopCollection ...>
  oneOrMoreGradientStops
</GradientStopCollection>
Scripting
To create an object using scripting, see CreateFromXAML.

Properties

Count, Name

Methods

Add, Clear, Equals, FindName, GetHost, GetItem, GetValue, Insert, Remove, RemoveAt, SetValue

Remarks

GradientStopCollection is used by LinearGradientBrush and RadialGradientBrush to store GradientStop information.

GradientStopCollection defines no methods or properties beyond the basic Collection methods and properties. Methods such as Add or GetItem will expect or return objects that are of type LinearGradientBrush or RadialGradientBrush .

The XAML syntax for properties that use a GradientStopCollection is an example of an implicit collection syntax, where you can omit an actual GradientStopCollection object element. Instead, you generally include one or more GradientStop object elements as child elements of a LinearGradientBrush or RadialGradientBrush. For more information about XAML implicit collection syntax, see XAML Syntax Overview. (Explicitly including a GradientStopCollection object element is permissible XAML syntax, and might be useful if you intend to name the collection in XAML and manipulate its contents through script later.)

See Also

Brush Overview, LinearGradientBrush, RadialGradientBrush


Image Object

Represents an image which is displayed.

XAML | <Image .../>
Scripting | To create an object using scripting, see CreateFromXAML.

Properties

Canvas.Left, Canvas.Top, Canvas.ZIndex, Clip, Cursor, DownloadProgress, Height, Name, Opacity, OpacityMask, RenderTransform, RenderTransformOrigin, Resources, Source, Stretch, Tag, Triggers, Width

Methods

AddEventListener, CaptureMouse, Equals, FindName, GetHost, GetParent, GetValue, ReleaseMouseCapture, RemoveEventListener, SetSource SetValue

Events

Loaded, DownloadProgressChanged, MouseEnter, MouseLeave, MouseLeftButtonDown, MouseLeftButtonUp, MouseMove, ImageFailed

Remarks

The Source property can be used to reference images in the JPEG and PNG file formats.

If the Source property is set to an invalid format, or is specified to a URI that cannot be resolved, then the ImageFailed event is raised. Also, an error is thrown, reporting a failure in SetValue for Source.

Examples

The following XAML example shows how to set the Source property of the Image object to a PNG file. In addition, the same PNG image file is used as an ImageBrush for the TextBlock that is used to display a photo caption:

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  Background="Wheat">

  <!-- Photo of Coco. -->
  <Image
    Source="CocoInTheSnow.png"
    Canvas.Left="30" Canvas.Top="30" />

  <!-- Caption of the photo consists of shadow text and image text. -->
  <!-- Offset the shadow text using a TranslateTransform. -->
  <TextBlock
    Text="Coco's Day in the Snow"
    Canvas.Left="34" Canvas.Top="336"
    FontFamily="Verdana"
    FontWeight="Bold"
    FontSize="30">
    <TextBlock.RenderTransform>
      <TranslateTransform X="2" Y="2" />
    </TextBlock.RenderTransform>
  </TextBlock>

  <!-- Use an ImageBrush for the fill of the TextBlock. -->
  <TextBlock
    Text="Coco's Day in the Snow"
    Canvas.Left="34" Canvas.Top="336"
    FontFamily="Verdana"
    FontWeight="Bold"
    FontSize="30">
    <TextBlock.Foreground>
      <ImageBrush ImageSource="CocoInTheSnow.png" />
    </TextBlock.Foreground>
  </TextBlock>

</Canvas>

The following screenshot shows the results of the previous XAML example:

An image file used by Image and ImageBrush objects

See Also

ImageBrush, MediaElement


ImageBrush Object

Paints an area with an image.

XAML | <ImageBrush .../>
Scripting | To create an object using scripting, see CreateFromXAML.

Properties

AlignmentX, AlignmentY, DownloadProgress, ImageSource, Name, Opacity, RelativeTransform, Stretch, Transform

Methods

Equals, FindName, GetHost, GetValue, SetSource, SetValue

Events

DownloadProgressChanged

Remarks

An ImageBrush can be used to create a decorative effect for text in your application. For example, the Foreground property of the TextBlock can specify an ImageBrush.

Examples

The following XAML example shows how to set the Foreground property to an ImageBrush, whose image is used as the fill for the TextBlock's rendered text.

XAML
<!-- TextBlock with an image brush applied to the text. -->
<TextBlock
  Canvas.Top="120"
  FontFamily="Verdana"
  FontSize="72"
  FontStyle="Italic"
  FontWeight="Bold">
  SHRUBBERY
  <TextBlock.Foreground>
    <ImageBrush ImageSource="forest.jpg"/>
  </TextBlock.Foreground>
</TextBlock>

The following image shows the rendered text from the previous XAML example:

TextBlock rendering an image brush

See Also

Brush Overview, Brush, Image


InkPresenter Object

An element that displays ink strokes and can be a child, sibling or parent of other elements.

Syntax

XAML
<InkPresenter ...>
  oneOrMoreUIElements
</InkPresenter ...>
Scripting
To create an object using scripting, see CreateFromXAML.

Properties

Background, Canvas.Left, Canvas.Top, Canvas.ZIndex, Children, Clip, Cursor, Height, IsHitTestVisible, Name, Opacity, OpacityMask, RenderTransform, RenderTransformOrigin, Resources, Strokes, Tag, Triggers, Visibility Width

Methods

AddEventListener, CaptureMouse, Equals, FindName, GetHost, GetParent, GetValue, ReleaseMouseCapture, RemoveEventListener, SetValue

Events

GotFocus, KeyDown, KeyUp, Loaded, LostFocus, MouseEnter, MouseLeave, MouseLeftButtonDown, MouseLeftButtonUp, MouseMove

Remarks

InkPresenter is a derived class of Canvas. In particular it inherits two properties that relate to presentation, Background and Children. The Background for an InkPresenter is applied behind any strokes that are presented on the surface.

The Children property is the content property for InkPresenter, which is why it is referenced as the oneOrMoreUIElements placeholder in the XAML syntax above. Because the primary purpose of InkPresenter is to display strokes, it might not be quite as common to specify Children UI elements for InkPresenter as it is to set Children for a Canvas.

The Children for an InkPresenter render on the InkPresenter surface just as they do on a Canvas. However, the collection of strokes is stored in a separate property, Strokes. By default a Canvas will draw Children elements in the order that they are declared for purposes of overlaps in rendering; the last element declared will draw on top. You can also adjust this order with Canvas.ZIndex attached property values set on the child elements. All the Children items draw over the Background. All of the Strokes draw over both Children and Background, and you cannot adjust Strokes with Canvas.ZIndex. Therefore, if you want any content to always remain on top of strokes, you should declare that content in a separate Canvas that overlays the InkPresenter, rather than in the InkPresenter Children property in script or as direct element content in XAML.

Examples

JavaScript
var agCtrl;
var inkPresenter; // Corresponds to InkPresenter element in xaml
var newStroke = null; // The Stroke variable we'll use here in mouse handlers
// DrawingAttributes variables
var daWidth = 2;
var daHeight = 2;
var daColor = "Black";
var daOutlineColor = "Black";

function root_Loaded(sender, args)
{
    // Get the html object which contains the Silverlight plug-in
    agCtrl = sender.GetHost();
    inkPresenter = sender.findname("inkPresenterElement");
}

// Capture mouse movement when the left button is pressed and create the stroke
function InkPresenterMouseDown(sender,args)
{
   inkPresenter.CaptureMouse();

   newStroke = agCtrl.content.createFromXaml('<Stroke/>');

   var da = agCtrl.content.CreateFromXaml('<DrawingAttributes/>');
   newStroke.DrawingAttributes = da;

   // Set the drawing attributes properties
   newStroke.DrawingAttributes.Width = daWidth;
   newStroke.DrawingAttributes.Height = daHeight;
   newStroke.DrawingAttributes.Color = daColor;
   newStroke.DrawingAttributes.OutlineColor = daOutlineColor;

   newStroke.StylusPoints.AddStylusPoints(args.GetStylusPoints(inkPresenter));
   inkPresenter.Strokes.Add(newStroke);
}

// Add the new points to the Stroke we're working with
function InkPresenterMouseMove(sender,args)
{
   if (newStroke != null)
   {
      newStroke.StylusPoints.AddStylusPoints(args.GetStylusPoints(inkPresenter));
   }
}

// Release the mouse
function InkPresenterMouseUp(sender,args)
{
   newStroke = null;
   inkPresenter.ReleaseMouseCapture();
}

See Also

Stroke, StrokeCollection


Inlines Object

Represents a collection of Run and LineBreak objects.

XAML | Cannot be used in XAML; see Remarks.
Scripting | Cannot explicitly create, reference to existing only.

Properties

Count, Name

Methods

Add, Clear, Equals, FindName, GetHost, GetItem, GetValue, Insert, Remove, RemoveAt, SetValue

Remarks

Inlines defines no methods or properties beyond the basic Collection methods and properties. Methods such as Add or GetItem will expect or return objects that are of type Run or LineBreak.

This is the collection that underlies TextBlock.Inlines, which is the content property of a TextBlock. However, Inlines cannot be used in XAML syntax. An Inlines collection is implicitly created by XAML parsing and is available if you examine the runtime object tree through scripting, but explicit uses in XAML are disallowed. TextBlock.Inlines is marginally permitted in XAML. The marginal aspect is because even XML white space is interpreted as possible content of the TextBlock, and if any content is detected the parser will populate the implicit Inlines collection using that content as an initial Run. Defining TextBlock.Inlines thereafter is thus interpreted as an attempt to set Inlines twice. Therefore the only way to specify TextBlock.Inlines would be if there were was no white space at all between the <TextBlock> object element and <TextBlock.Inlines> object element.

The XAML syntax for properties that use Inlines is an example of an implicit collection syntax, where you omit an actual Inlines object element. Instead, you generally include one or more inline types (Run and LineBreak elements) as child elements of a TextBlock. For more information about XAML implicit collection syntax, see XAML Syntax Overview. In addition to the implicit collection syntax of inlines, TextBlock also supports setting content as inner text, or by specifically setting the value of Text with a string. For details, see TextBlock.

See Also

Text and Fonts Overview, Collection, Run, LineBreak


KeyboardEventArgs Object

Provides data for the KeyUp and KeyDown events.

XAML | You cannot use this object in XAML.
Scripting | Obtained as arguments for certain event handlers.

Properties

Ctrl, Key, Name, PlatformKeyCode, Shift

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

KeyboardEventArgs is used with the following events: KeyDown, KeyUp.

See Also

Silverlight Events, Silverlight Keyboard Support


KeySpline Object

Included by a spline key frame to define animation progress.

XAML | <object property="cp1x,cp1y cp2x,cp2y" .../>
Scripting | object.property="cp1x,cp1y cp2x,cp2y"

Properties

Name

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

Properties that take a KeySpline use a string type conversion syntax as shown in both the XAML and script syntaxes above. The definitions for this syntax follow:
Term | Definition
cp1x | x coordinate of the first control point.
cp1y | y coordinate of the first control point.
cp2x | x coordinate of the second control point.
cp2y | y coordinate of the second control point.

The delimiter can be either a comma or a space and these delimiters are interchangeable. The syntax shown here is the most conventional usage.

The values for each component of a KeySpline expressed in a string are expected to be between 0 and 1. Each control point influences the shape of the conceptual curve that controls the rate of a splined animation, changing the linear progression between 0,0 and 1,1 that would occur if there were no control points set.

A Bezier curve

KeySpline is exposed as an object to the object model (you can obtain a KeySpline through relevant properties) but none of the properties of KeySpline are settable at runtime. "ControlPoint1" and "ControlPoint2" of a KeySpline are not accessible in the Silverlight 1.0 object model.

For more information, see the following animation objects: SplineColorKeyFrame, SplineDoubleKeyFrame, SplinePointKeyFrame

See Also

Animation Overview
Key-Frame Animations Overview


KeyTime Object

During the relative course of an animation, a KeyTime instance specifies the precise timing when a particular key frame should take place.

XAML
<object property="[days.]hours:minutes:seconds[.fractionalSeconds]" .../>
- or -
<object property="[days.]hours:minutes" .../>
- or -
<object property="days" .../>
Scripting
See Remarks.

Properties

Name, Seconds

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

Creating a Duration, KeyTime, RepeatBehavior, or TimeSpan in XAML or in script is only possible through a type conversion syntax when setting a property such as KeyTime that takes one of these types, with the value specified as a string. The string format for specifying a time in each of these types is identical. Duration can also take the literals "Automatic" and "Forever". RepeatBehavior can take the literal "Forever" and also an iterations syntax "#x".

The main scenario for working with a KeyTime as an object in script is to get or set its Seconds property in order to query or change an existing animation value.

See Also

Animation Overview
Key-Frame Animations Overview


Line Object

Draws a stright line between two points.

XAML | <Line .../>
Scripting | To create an object using scripting, see CreateFromXAML.

Properties

Canvas.Left, Canvas.Top, Canvas.ZIndex, Clip, Cursor, Fill, Height, Name, Opacity, OpacityMask, RenderTransform, RenderTransformOrigin, Resources, Stretch, Stroke, StrokeDashArray, StrokeDashCap, StrokeDashOffset, StrokeEndLineCap, StrokeLineJoin, StrokeMiterLimit, StrokeStartLineCap, StrokeThickness, Tag, Triggers, Width, X1, X2, Y1, Y2

Methods

AddEventListener, CaptureMouse, Equals, FindName, GetHost, GetParent, GetValue, ReleaseMouseCapture, RemoveEventListener, SetValue

Events

Loaded, MouseEnter, MouseLeave, MouseLeftButtonDown, MouseLeftButtonUp, MouseMove

Examples

The following example shows how to use Line to create several lines.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Height="300" Width="300">

  <!-- Draws a diagonal line from (10,10) to (50,50). -->
  <Line
    X1="10" Y1="10"
    X2="50" Y2="50"
    Stroke="Black"
    StrokeThickness="4" />

  <!-- Draws a diagonal line from (10,10) to (50,50)
       and moves it 100 pixels to the right. -->
  <Line
    X1="10" Y1="10"
    X2="50" Y2="50"
    StrokeThickness="4"
    Canvas.Left="100">
    <Line.Stroke>
      <RadialGradientBrush GradientOrigin="0.5,0.5" Center="0.5,0.5" RadiusX="0.5" RadiusY="0.5">
        <RadialGradientBrush.GradientStops>
          <GradientStop Color="Red" Offset="0" />
          <GradientStop Color="Blue" Offset="0.25" />
        </RadialGradientBrush.GradientStops>
      </RadialGradientBrush>
    </Line.Stroke>
  </Line>

  <!-- Draws a horizontal line from (10,60) to (150,60). -->
  <Line
     X1="10" Y1="60"
     X2="150" Y2="60"
     Stroke="Black"
     StrokeThickness="4"/>

</Canvas>

See Also

Shape, Shapes Overview


LinearColorKeyFrame Object

Animates from the Color value of the previous key frame to its own Value using linear interpolation.

XAML | <LinearColorKeyFrame .../>
Scripting | To create an object using scripting, see CreateFromXAML.

Properties

KeyTime, Name, Value

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

A key frame defines a segment of the ColorAnimationUsingKeyFrames to which it belongs. Each key frame has a target Value and a KeyTime. The KeyTime specifies the time at which the key frame's Value should be reached. A key frame animates from the target value of the previous key frame to its own target value. It starts when the previous key frame ends and ends when its own key time is reached.

Linear key frames like LinearColorKeyFrame create a smooth, linear interpolation between values.

Examples

The following example uses the ColorAnimationUsingKeyFrames class to animate the Background property of a Canvas. This animation uses three key frames in the following manner:

  1. During the first two seconds, LinearColorKeyFrame gradually changes the color from green to red. Linear key frames like LinearColorKeyFrame create a smooth linear transition between values.
  2. During the end of the next half second, DiscreteColorKeyFrame quickly changes the color from red to yellow. Discrete key frames like DiscreteColorKeyFrame create sudden changes between values, that is, the color change in this part of the animation occurs quickly and is not subtle.
  3. During the final two seconds, SplineColorKeyFrame changes the color again�this time from yellow back to green. Spline key frames like SplineColorKeyFrame create a variable transition between values according to the values of the KeySpline property. In this example, the change in color begins slowly and speeds up exponentially toward the end of the time segment.
XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Width="200" Height="200"
  Background="White"
  x:Name="Page">
  <Canvas.Triggers>
    <EventTrigger RoutedEvent="Canvas.Loaded">
      <BeginStoryboard>
        <Storyboard x:Name="ColorStoryboard">
          <ColorAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="Page" Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)">

            <!-- Go from green to red in the first 2 seconds. LinearColorKeyFrame creates
            a smooth, linear animation between values. -->
            <LinearColorKeyFrame Value="Red" KeyTime="00:00:02" />

            <!-- In the next half second, go to yellow. DiscreteColorKeyFrame creates a
            sudden jump between values. -->
            <DiscreteColorKeyFrame Value="Yellow" KeyTime="00:00:2.5" />

            <!-- In the final 2 seconds of the animation, go from yellow back to green. SplineColorKeyFrame
            creates a variable transition between values depending on the KeySpline property. In this example,
            the animation starts off slow but toward the end of the time segment, it speeds up exponentially.-->
            <SplineColorKeyFrame Value="Green" KeyTime="00:00:4.5" KeySpline="0.6,0.0 0.9,0.00" />

          </ColorAnimationUsingKeyFrames>
        </Storyboard>
      </BeginStoryboard>
    </EventTrigger>
  </Canvas.Triggers>
</Canvas>

See Also

Animation Overview, ColorAnimationUsingKeyFrames


LinearDoubleKeyFrame Object

Animates from the Double value of the previous key frame to its own Value using linear interpolation.

XAML | <LinearDoubleKeyFrame .../>
Scripting | To create an object using scripting, see CreateFromXAML.

Properties

KeyTime, Name, Value

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

A key frame defines a segment of the DoubleAnimationUsingKeyFrames to which it belongs. Each key frame has a target Value and a KeyTime. The KeyTime specifies the time at which the key frame's Value should be reached. A key frame animates from the target value of the previous key frame to its own target value. It starts when the previous key frame ends and ends when its own key time is reached.

Linear key frames like LinearDoubleKeyFrame create a smooth, linear interpolation between values.

Examples

The following example moves a rectangle across a screen. The example uses the DoubleAnimationUsingKeyFrames class to animate the X property of a TranslateTransform applied to a Rectangle. This animation, which repeats indefinitely, uses three key frames in the following manner:

  1. During the first three seconds, uses an instance of the LinearDoubleKeyFrame class to move the rectangle along a path at a steady rate from its starting position to the 500 position. Linear key frames like LinearDoubleKeyFrame create a smooth linear transition between values.
  2. At the end of the fourth second, uses an instance of the DiscreteDoubleKeyFrame class to suddenly move the rectangle to the next position. Discrete key frames like DiscreteDoubleKeyFrame create sudden jumps between values. In this example, the rectangle is at the starting position and then suddenly appears at the 500 position.
  3. In the final two seconds, uses an instance of the SplineDoubleKeyFrame class to move the rectangle back to its starting position. Spline key frames like SplineDoubleKeyFrame create a variable transition between values according to the value of the KeySpline property. In this example, the rectangle begins by moving slowly and then speeds up exponentially toward the end of the time segment.
XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Width="400" Height="300">
  <Rectangle Fill="Blue"
    Width="50" Height="50">
    <Rectangle.RenderTransform>
      <TranslateTransform
        x:Name="MyAnimatedTranslateTransform"
        X="0" Y="0" />
    </Rectangle.RenderTransform>
    <Rectangle.Triggers>
      <EventTrigger RoutedEvent="Rectangle.Loaded">
        <BeginStoryboard>
          <Storyboard>

            <!-- Animate the TranslateTransform's X property
                 from 0 to 350, then 50,
                 then 200 over 10 seconds. -->
            <DoubleAnimationUsingKeyFrames
              Storyboard.TargetName="MyAnimatedTranslateTransform"
              Storyboard.TargetProperty="X"
              Duration="0:0:10">

                <!-- Using a LinearDoubleKeyFrame, the rectangle moves
                     steadily from its starting position to 500 over
                     the first 3 seconds.  -->
                <LinearDoubleKeyFrame Value="500" KeyTime="0:0:3" />

                <!-- Using a DiscreteDoubleKeyFrame, the rectangle suddenly
                     appears at 400 after the fourth second of the animation. -->
                <DiscreteDoubleKeyFrame Value="400" KeyTime="0:0:4" />

                <!-- Using a SplineDoubleKeyFrame, the rectangle moves
                     back to its starting point. The
                     animation starts out slowly at first and then speeds up.
                     This KeyFrame ends after the 6th
                     second. -->
                <SplineDoubleKeyFrame KeySpline="0.6,0.0 0.9,0.00" Value="0" KeyTime="0:0:6" />

            </DoubleAnimationUsingKeyFrames>
          </Storyboard>
        </BeginStoryboard>
      </EventTrigger>
    </Rectangle.Triggers>
  </Rectangle>
</Canvas>

See Also

Animation Overview, DoubleAnimationUsingKeyFrames


LinearGradientBrush Object

Paints an area with a linear gradient.

XAML
<LinearGradientBrush ...>
  oneOrMoreGradientStops
</LinearGradientBrush>
Scripting
To create an object using scripting, see CreateFromXAML.

Properties

ColorInterpolationMode, EndPoint, GradientStops, MappingMode, Name, Opacity, RelativeTransform, SpreadMethod, StartPoint, Transform

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

A LinearGradientBrush paints an area with a linear gradient. A linear gradient defines a gradient along a line. The line's end points are defined by the StartPoint and EndPoint properties of the linear gradient. A LinearGradientBrush brush paints its GradientStops along this line.

The default linear gradient is diagonal. In the default, the StartPoint of a linear gradient is (0,0), the upper-left corner of the area being painted, and its EndPoint is (1,1), the lower-right corner of the area being painted. The colors in the resulting gradient are interpolated along the diagonal path.

The following illustration shows a diagonal gradient. A line was added to highlight the interpolation path of the gradient from the start point to the end point.

Gradient axis for a diagonal linear gradient

The next illustration shows the same linear gradient, but with highlighted gradient stops.

Gradient stops in a linear gradient

Examples

The following example creates a linear gradient with four colors and uses it to paint a Rectangle.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <!-- This rectangle is painted with a diagonal linear gradient. -->
  <Rectangle Width="200" Height="100">
    <Rectangle.Fill>
      <LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
        <GradientStop Color="Yellow" Offset="0.0" />
        <GradientStop Color="Red" Offset="0.25" />
        <GradientStop Color="Blue" Offset="0.75" />
        <GradientStop Color="LimeGreen" Offset="1.0" />
      </LinearGradientBrush>
    </Rectangle.Fill>
  </Rectangle>
</Canvas>

This code produces the following gradient with the highlighted gradient stops:

Gradient stops in a linear gradient

See Also

Brush Overview, RadialGradientBrush


LinearPointKeyFrame Object

Animates from the Point value of the previous key frame to its own Value using linear interpolation.

XAML | <LinearPointKeyFrame .../>
Scripting | To create an object using scripting, see CreateFromXAML.

Properties

KeyTime, Name, Value

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

A key frame defines a segment of the PointAnimationUsingKeyFrames to which it belongs. Each key frame has a target Value and a KeyTime. The KeyTime specifies the time at which the key frame's Value should be reached. A key frame animates from the target value of the previous key frame to its own target value. It starts when the previous key frame ends and ends when its own key time is reached.

Linear key frames like LinearPointKeyFrame create a smooth, linear interpolation between values.

Examples

The following example moves an ellipse along a triangular path. The example uses the PointAnimationUsingKeyFrames class to animate the Center property of an EllipseGeometry. This animation uses three key frames in the following manner:

  1. During the first half second, uses an instance of the LinearPointKeyFrame class to move the ellipse along a path at a steady rate from its starting position. Linear key frames like LinearPointKeyFrame create a smooth linear interpolation between values.
  2. During the end of the next half second, uses an instance of the DiscretePointKeyFrame class to suddenly move the ellipse along the path to the next position. Discrete key frames like DiscretePointKeyFrame create sudden jumps between values.
  3. During the final two seconds, uses an instance of the SplinePointKeyFrame class to move the ellipse back to its starting position. Spline key frames like SplinePointKeyFrame create a variable transition between values according to the values of the KeySpline property. In this example, the animation begins slowly and speeds up exponentially toward the end of the time segment.
XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Width="400" Height="300">
  <Path Fill="Blue">
    <Path.Data>

      <!-- Describes an ellipse. -->
      <EllipseGeometry x:Name="MyAnimatedEllipseGeometry"
       Center="200,100" RadiusX="15" RadiusY="15" />
    </Path.Data>

    <Path.Triggers>
      <EventTrigger RoutedEvent="Path.Loaded">
        <BeginStoryboard>
          <Storyboard>

            <!-- Animating the Center property uses 3 KeyFrames, which animate
                 the ellipse allong a triangular path. -->
            <PointAnimationUsingKeyFrames
              Storyboard.TargetProperty="Center"
              Storyboard.TargetName="MyAnimatedEllipseGeometry"
              Duration="0:0:5" RepeatBehavior="Forever">

              <!-- Over the first half second, Using a LinearPointKeyFrame, the ellipse
                   moves steadily from its starting position along the first line of the
                   trianglar path.  -->
              <LinearPointKeyFrame
                KeyTime="0:0:0.5"
                Value="100,300" />

              <!-- Using a DiscretePointKeyFrame, the ellipse suddenly changes position
                   after the first second of the animation. -->
              <DiscretePointKeyFrame
                KeyTime="0:0:1"
                Value="400,300" />

              <!-- Using a SplinePointKeyFrame, the ellipse moves back to its starting
                   position. It moves slowly at first and then speeds up. This key frame
                   takes 2 seconds to complete. -->
              <SplinePointKeyFrame
                KeySpline="0.6,0.0 0.9,0.00"
                KeyTime="0:0:3"
                Value="200,100" />
            </PointAnimationUsingKeyFrames>
          </Storyboard>
        </BeginStoryboard>
      </EventTrigger>
    </Path.Triggers>
  </Path>
</Canvas>

See Also

Animation Overview, PointAnimationUsingKeyFrames


LineBreak Object

Represents an explicit new line in a TextBlock.

XAML | <LineBreak .../>
Scripting | To create an object using scripting, see CreateFromXAML.

Properties

FontFamily, FontSize, FontStretch, FontStyle, FontWeight, Foreground, Name, TextDecorations

Methods

Equals, FindName, GetHost, GetValue, SetValue

Examples

The following XAML example shows how to use LineBreak objects to force the formatted text strings defined in the Run objects to display on separate lines.

XAML
<!-- Display formatted text as Run objects within a TextBlock. -->
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007">

<TextBlock
  FontFamily="Arial" Width="400" Text="Sample text formatting runs">
  <LineBreak/>
  <Run Foreground="Maroon" FontFamily="Courier New" FontSize="24">Courier New 24</Run>
  <LineBreak/>
  <Run Foreground="Teal" FontFamily="Times New Roman" FontSize="18" FontStyle="Italic">Times New Roman Italic 18</Run>
  <LineBreak/>
  <Run Foreground="SteelBlue" FontFamily="Verdana" FontSize="14" FontWeight="Bold">Verdana Bold 14</Run>
</TextBlock>

</Canvas>

The following screenshot shows the rendered formatted text from the previous XAML content example.

Without the LineBreak object, the text in each Run would flow together as one line, and eventually be truncated after exceeding the TextBlock's Width value. Here is how the formatted text would render without using LineBreak objects:

See Also

Text and Fonts Overview, TextBlock, Run


LineGeometry Object

Represents the geometry of a line.

XAML | <LineGeometry .../>
Scripting | To create an object using scripting, see CreateFromXAML.

Properties

EndPoint, FillRule, Name, StartPoint, Transform

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

FillRule is technically a property inherited from the base Geometry class, but setting it has no effect on a LineGeometry.

Examples

The following example shows how to create and render a LineGeometry. A Geometry object only defines the geometry of the object, it does not render anything directly, so the example uses a Path shape to render the line. Because a line has no area, setting the Fill property of the Path would have no effect; instead, only the Stroke and StrokeThickness properties are specified. The following illustration shows the output from the example.

A LineGeometry drawn from (10,20) to (100,130)

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Width="200" Height="200">
  <Path Stroke="Black" StrokeThickness="1" >
    <Path.Data>
      <LineGeometry StartPoint="10,20" EndPoint="100,130" />
    </Path.Data>
  </Path>
</Canvas>

See Also

Geometry Overview, Geometry, GeometryCollection, GeometryGroup


LineSegment Object

Represents a line drawn between two points.

XAML | <LineSegment .../>
Scripting | To create an object using scripting, see the CreateFromXAML method.

Properties

Name, Point

Methods

Equals, FindName, GetHost, GetValue, SetValue

Examples

The following example creates a simple PathGeometry made up of a single PathFigure with a LineSegment and displays it using a Path element. The PathFigure object's StartPoint is set to 10,20 and a LineSegment is defined with an end point of 100,130. The following illustration shows the PathGeometry created by this example.

A PathGeometry that contains a single LineSegment

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <Path Stroke="Black" StrokeThickness="1">
    <Path.Data>
      <PathGeometry>
        <PathGeometry.Figures>
          <PathFigure StartPoint="10,20">
            <PathFigure.Segments>
              <LineSegment Point="100,130"/>
            </PathFigure.Segments>
          </PathFigure>
        </PathGeometry.Figures>
      </PathGeometry>
    </Path.Data>
  </Path>
</Canvas>

See Also

Silverlight Objects


Matrix Object

Represents a 3x3 affine transformation matrix used for transformations in 2-D space.

XAML | <Matrix ... />
Scripting | To create an object using scripting, see CreateFromXAML.

Properties

M11, M12, M21, M22, Name, OffsetX, OffsetY

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

Properties of a Matrix are animatable (as one or more DoubleAnimations or DoubleAnimationUsingKeyFrames).

A Matrix provides the property value for the MatrixTransform.Matrix property. Often, it is more practical to manipulate the transforms by using one of the other transform objects and properties that constrain the transform into a particular type. These are RotateTransform, ScaleTransform, SkewTransform, and TranslateTransform.

Examples

The following example transforms the position and skew of a rectangle using a MatrixTransform.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Width="400" Height="300">
  <Rectangle Width="60" Height="60" Fill="Blue">

    <Rectangle.RenderTransform>
      <MatrixTransform>
        <MatrixTransform.Matrix >

          <!-- This matrix transforms the x,y position of
               the rectangle and skews it. -->
          <Matrix OffsetX="30" OffsetY="100" M12="0.5" />
        </MatrixTransform.Matrix>
      </MatrixTransform>
    </Rectangle.RenderTransform>

  </Rectangle>
</Canvas>

See Also

Transform, Silverlight Transforms Overview


MatrixTransform Object

Creates an arbitrary affine matrix transformation that is used to manipulate objects or coordinate systems in a 2-D plane.

XAML | <MatrixTransform .../>
Scripting | To create an object using scripting, see CreateFromXAML.

Properties

Matrix, Name

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

Use the MatrixTransform class to create custom transformations that are not provided by the RotateTransform, ScaleTransform, SkewTransform, and TranslateTransform classes.

A 3x3 matrix is used for transformations in a 2-D x-y plane. You can multiply affine matrix transformations to form linear transformations, such as rotation and skew (shear) that are followed by translation.

An affine matrix transformation has its final column equal to (0, 0, 1); therefore, you only have to specify the members in the first two columns.

The local 0,0 for an object can be offset on a Canvas using Canvas.Left and Canvas.Top, but this does not count as a transform; the object retains its own local 0,0 in this case for transform purposes. For details on this concept, see Object Layout in Silverlight.

Multiple transforms can be applied with a TransformGroup.

Examples

The following example transforms the position and skew of a rectangle using a MatrixTransform.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Width="400" Height="300">
  <Rectangle Width="60" Height="60" Fill="Blue">

    <Rectangle.RenderTransform>
      <MatrixTransform>
        <MatrixTransform.Matrix >

          <!-- This matrix transforms the x,y position of
               the rectangle and skews it. -->
          <Matrix OffsetX="30" OffsetY="100" M12="0.5" />
        </MatrixTransform.Matrix>
      </MatrixTransform>
    </Rectangle.RenderTransform>

  </Rectangle>
</Canvas>

See Also

Transform Overview, Transform


MediaAttribute Object

Represents an attribute from an entry in a ASX file.

XAML | See Remarks.
Scripting | To create an object using scripting, see CreateFromXAML.

Properties

Name, Value

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

MediaAttribute technically does have a XAML usage and can be instantiated as a XAML object element. However, this usage does not really have an application. The useful collection of MediaAttribute objects is contained within the metadata of each given source that is loaded by a MediaElement. You can get this collection as the Attributes property through scripting, and this collection is not valid until the MediaOpened event is raised. Specifying a MediaAttribute in XAML ahead of time as part of a MediaElement will only result in that entire Attributes value being erased and replaced as soon as a media source is loaded by the MediaElement.

Examples

The following JavaScript example shows how to retrieve the Attributes property of a MediaElement that has a Source property set to an ASX playlist file. The retrieved MediaAttributeCollection is iterated through and the Name and Value properties of each MediaAttribute is displayed.

JavaScript
    // Get the MediaElement name MediaPlayer.
    player = sender.findName("MediaPlayer");

    // The display message.
    var msg;
    msg =  "MediaElement Source: " + player.source + "\n\n";
    msg += "Attributes: \n";

    // Variable to hold the MediaAttribute.
    var attribute;

    // Iterate through the collection of MediaAttributes.
    var loop = 0;
    while(loop < player.Attributes.count)
    {
        // Get the current Attribute.
        attribute = player.Attributes.getItem(loop);

        msg += "Name: "  + attribute.Name + "\n";
        msg += "Value: " + attribute.Value + " \n\n";
        loop++;
    }

    // Display the MediaAttribute information.
    alert(msg);
}

See Also

MediaAttributeCollection, MediaElement Attributes, Media Overview


MediaAttributeCollection Object

Represents a collection of MediaAttribute objects.

XAML | See Remarks
Scripting | See Remarks.

Properties

Count, Name

Methods

Clear, Equals, FindName, GetHost, GetItem, GetItemByName, GetValue, Insert, Remove, RemoveAt, SetValue

Remarks

Each MediaAttribute in the collection represents a Name-Value pair that corresponds to an xml tag in the ASX file the Source property of the MediaElement is set to.

If the Source property of the MediaElement is not set, is set to a media file rather than an ASX file, or is checked prior to MediaOpened, the collection is empty. Do not attempt to script to this collection until the MediaOpened event is raised.

This collection has an Add method, but it is not usable. Generally you must treat the collection as a one-time copy of a read-only collection that reflects the ASX file, and you should not modify its contents. Other collection methods such as Remove are also not particularly useful for this reason, you would only be modifying a copy. The most useful method of this collection is the specialized method GetItemByName.

MediaAttributeCollection technically does have a XAML usage and can be instantiated as a XAML object element. However, this usage does not really have an application. The useful collection of MediaAttribute objects is contained within the metadata of an ASX source that is loaded by a MediaElement. You can get this collection as the Attributes property through scripting, and this collection is not valid until the MediaOpened event is raised. Specifying MediaAttribute values in XAML ahead of time as part of a MediaElement will only result in that entire Attributes value being erased and replaced as soon as a media source is loaded by the MediaElement.

Examples

The following JavaScript example shows how to retrieve a MediaAttribute by name from the Attributes property of a MediaElement that has a Source property set to an ASX playlist file. The Name and Value properties of the MediaAttribute is then displayed.

JavaScript
    // Get the MediaElement name MediaPlayer.
    player = sender.findName("MediaPlayer");

    // Variable to hold the MediaAttribute.
    var attribute;

    // Get the MediaAttribute named Title
    try
    {
        attribute = player.Attributes.getItemByName("Title");
    }
    catch(errorObj)
    {
        alert(errorObj.message);
    }

    // Display the Value of the MediaAttribute
    if(attribute != null)
    {
      alert("The title of the track is: " + attribute.value);
    }

See Also

Supported Media Formats and Protocols


MediaElement Object

Represents an object that contains audio, video, or both.

XAML | <MediaElement .../>
Scripting | To create an object using scripting, see the CreateFromXAML method.

Properties

Attributes, AutoPlay, AudioStreamCount, AudioStreamIndex, Balance, BufferingProgress, BufferingTime, CanPause, CanSeek, Canvas.Left, Canvas.Top, Canvas.ZIndex, Clip, CurrentState, Cursor, DownloadProgress, Height, IsMuted, Markers, Name, NaturalDuration, NaturalVideoHeight, NaturalVideoWidth, Opacity, OpacityMask, Position, RenderTransform, RenderTransformOrigin, Resources, Source, Stretch, Tag, Triggers, Volume, Width

Methods

AddEventListener, CaptureMouse, Equals, FindName, GetHost, GetParent, GetValue, Pause, Play, ReleaseMouseCapture, RemoveEventListener, SetSource, SetValue, Stop

Events

BufferingProgressChanged, CurrentStateChanged, DownloadProgressChanged, Loaded, MarkerReached, MediaEnded, MediaFailed, MediaOpened, MouseEnter, MouseLeave, MouseLeftButtonDown, MouseLeftButtonUp, MouseMove

Remarks

By default, the media that is defined by the Source property plays immediately after the MediaElement object has loaded. To suppress the media from starting automatically, set the AutoPlay property to false.

Not all media formats and protocols are supported by Silverlight. See Supported Media Formats and Protocols for more information.

In networks where a proxy server exists, special settings on the client may be required before streaming will work in Silverlight. For more information, see Proxy Servers and Streaming in Silverlight.

Performance Note: For best performance, avoid explicitly setting the width and height of a MediaElement, rather, allow the media to display at its natural size. If you need to change the size the media displays, it is best to re-encode the media to the desired size using a media encoding tool.

Examples

The following example demonstrates how to add media to your page.

XAML
  <MediaElement
    x:Name="media"
    Source="xbox.wmv"
    CurrentStateChanged="media_state_changed"
    Width="300" Height="300"/>

See Also

Using the createFromXAML Method, Silverlight Objects


MouseEventArgs Object

Provides data for mouse related events.

Obtained as arguments for certain event handlers.
XAML
You cannot use this object in XAML.
Scripting

Properties

Ctrl, Name, Shift

Methods

Equals, FindName, GetHost, GetPosition, GetStylusInfo, GetStylusPoints, GetValue, SetValue

Remarks

MouseEventArgs is used with the following events: MouseEnter, MouseLeave, MouseLeftButtonDown, MouseLeftButtonup, and MouseMove.

See Also

Silverlight Mouse Support, Silverlight Events


ParserErrorEventArgs Object

Provides data for XAML parser error events.

XAML | You cannot use this object in XAML.
Scripting | Obtained as arguments for certain event handlers.

Properties

CharPosition ErrorCode, ErrorMessage, ErrorType, LineNumber, Name, XamlFile, XmlAttribute, XmlElement

Methods

Equals, FindName, GetHost, GetValue, SetValue

Examples

The following JavaScript example shows the portion of an event handler that displays error information specific to parser errors.

JavaScript
    // errorArgs is an instance of ParserErrorEventArgs
    if(errorArgs.ErrorType == "ParserError")
    {
      var parserErrorMsg = "Silverlight Parser Error  \n\n";

      // Basic error event informaiton.
      parserErrorMsg += "Error Type:    " + errorArgs.errorType     + "\n";
      parserErrorMsg += "Error Message: " + errorArgs.errorMessage  + "\n";
      parserErrorMsg += "Error Code:    " + errorArgs.errorCode  + "\n";

      //Parser specific error event information.
      parserErrorMsg += "XamlFile:      " + errorArgs.xamlFile      + "\n";
      parserErrorMsg += "XmlElement:    " + errorArgs.xmlElement    + "\n";
      parserErrorMsg += "XmlAttribute:  " + errorArgs.xmlAttribute  + "\n";
      parserErrorMsg += "Line:          " + errorArgs.lineNumber    + "\n";
      parserErrorMsg += "Position:      " + errorArgs.charPosition  + "\n";

      // Display the error message.
      alert(parserErrorMsg);
    }

See Also

Silverlight Application Scripting Error Handling, ErrorEventArgs, RuntimeErrorEventArgs


Path Object

Draws a series of connected lines and curves.

XAML | <Path .../>
Scripting | To create an object using scripting, see CreateFromXAML.

Properties

Canvas.Left, Canvas.Top, Canvas.ZIndex, Clip, Cursor, Data, Fill, Height, Name, Opacity, OpacityMask, RenderTransform, RenderTransformOrigin, Resources, Stretch, Stroke, StrokeDashArray, StrokeDashCap, StrokeDashOffset, StrokeEndLineCap, StrokeLineJoin, StrokeMiterLimit, StrokeStartLineCap, StrokeThickness, Tag, Triggers, Width

Methods

AddEventListener, CaptureMouse, Equals, FindName, GetHost, GetParent, GetValue, ReleaseMouseCapture, RemoveEventListener, SetValue

Events

Loaded, MouseEnter, MouseLeave, MouseLeftButtonDown, MouseLeftButtonUp, MouseMove

Remarks

The Path object can draw closed or open shapes, lines, and curves. For more information on using Path in markup, see Path Markup Syntax.

Unlike the Line and PolyLine objects, you can use this object to draw curves. See the Data property for a description of the shapes that the Path element supports.

Performance Note: For best performance, avoid explicitly setting the width and height of a Path. Setting the Width and Height will result in additional stretching which has a performance cost. Instead, rely on the explicitly set coordinates of the Path to control its shape and position. See Stretch.

Examples

The following example uses a Path to draw an ellipse.

An EllipseGeometry drawn at (50,50)

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <Path Fill="Gold" Stroke="Black" StrokeThickness="1">
    <Path.Data>
      <EllipseGeometry Center="50,50" RadiusX="50" RadiusY="50" />
    </Path.Data>
  </Path>
</Canvas>

See Also

Path Markup Syntax, Shapes Overview, Shape, Stretch


PathFigure Object

Represents a subsection of a geometry, a single connected series of two-dimensional geometric segments.

XAML
<PathFigure ...>
  oneOrMorePathSegments
</PathFigure>
Scripting
To create an object using scripting, see CreateFromXAML.

Properties

IsClosed, Name, Segments, StartPoint

Methods

Equals, FindName, GetHost, GetValue, SetValue

Examples

The following example creates a simple PathGeometry made up of a single PathFigure with a LineSegment and displays it using a Path element. The PathFigure object's StartPoint is set to 10,20 and a LineSegment is defined with an end point of 100,130. The following illustration shows the PathGeometry created by this example.

A PathGeometry that contains a single LineSegment

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <Path Stroke="Black" StrokeThickness="1">
    <Path.Data>
      <PathGeometry>
        <PathGeometry.Figures>
          <PathFigure StartPoint="10,20">
            <PathFigure.Segments>
              <LineSegment Point="100,130"/>
            </PathFigure.Segments>
          </PathFigure>
        </PathGeometry.Figures>
      </PathGeometry>
    </Path.Data>
  </Path>
</Canvas>

This example uses multiple segments in a PathFigure.

Multiple Segments in a PathFigure

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <Path Stroke="Black" StrokeThickness="1" >
    <Path.Data>
      <PathGeometry>
        <PathGeometry.Figures>
          <PathFigure StartPoint="10,50">
            <PathFigure.Segments>
              <BezierSegment
                Point1="100,0"
                Point2="200,200"
                Point3="300,100"/>
              <LineSegment Point="400,100" />
              <ArcSegment
                Size="50,50" RotationAngle="45"
                IsLargeArc="True" SweepDirection="Clockwise"
                Point="200,100"/>
            </PathFigure.Segments>
          </PathFigure>
        </PathGeometry.Figures>
      </PathGeometry>
    </Path.Data>
  </Path>
</Canvas>

See Also

PathGeometry, PathSegment, Path Markup Syntax


PathFigureCollection Object

Represents a collection of PathFigure objects that collectively make up the geometry of a PathGeometry.

XAML
<PathFigureCollection ...>
  oneOrMorePathFigures
</PathFigureCollection>
Scripting
To create an object using scripting, see CreateFromXAML.

Properties

Count, Name

Methods

Add, Clear, Equals, FindName, GetHost, GetItem, GetValue, Insert, Remove, RemoveAt, SetValue

Remarks

PathFigureCollection is used by the Figures property to store PathFigure information.

PathFigureCollection defines no methods or properties beyond the basic Collection methods and properties. Methods such as Add or GetItem will expect or return objects that are of type PathFigure.

The XAML syntax for properties that use a PathFigureCollection is an example of an implicit collection syntax, where you can omit an actual PathFigureCollection object element, as well as the <PathGeometry.Figures> property element. Instead, you generally include one or more PathFigure object elements as child elements of a PathGeometry. For more information about XAML implicit collection syntax, see XAML Syntax Overview. (Explicitly including a PathFigureCollection object element is permissible XAML syntax, and might be useful if you intend to name the collection in XAML and manipulate its contents through script later.)

See Also

PathFigure


PathGeometry Object

Represents a complex shape that may be composed of arcs, curves, ellipses, lines, and rectangles.

XAML
<PathGeometry ...>
  oneOrMorePathFigures
</PathGeometry>
Scripting
To create an object using scripting, see CreateFromXAML.

Properties

Figures, FillRule, Name, Transform

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

Each PathGeometry object defines a collection of PathFigure objects. Each of the PathFigure objects is composed of one or more PathSegment objects, such as ArcSegment and LineSegment, which actually define their shape.

The filled area of the PathGeometry is defined by taking all of the contained PathFigure objects that have their IsFilled property set to true and applying the FillRule to determine the enclosed area.

Examples

The following example creates a simple PathGeometry made up of a single PathFigure with a LineSegment and displays it using a Path element. The PathFigure object's StartPoint is set to 10,20 and a LineSegment is defined with an end point of 100,130. The following illustration shows the PathGeometry created by this example.

A PathGeometry that contains a single LineSegment

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <Path Stroke="Black" StrokeThickness="1">
    <Path.Data>
      <PathGeometry>
        <PathGeometry.Figures>
          <PathFigure StartPoint="10,20">
            <PathFigure.Segments>
              <LineSegment Point="100,130"/>
            </PathFigure.Segments>
          </PathFigure>
        </PathGeometry.Figures>
      </PathGeometry>
    </Path.Data>
  </Path>
</Canvas>

This example uses multiple segments in a PathFigure.

Multiple Segments in a PathFigure

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <Path Stroke="Black" StrokeThickness="1" >
    <Path.Data>
      <PathGeometry>
        <PathGeometry.Figures>
          <PathFigure StartPoint="10,50">
            <PathFigure.Segments>
              <BezierSegment
                Point1="100,0"
                Point2="200,200"
                Point3="300,100"/>
              <LineSegment Point="400,100" />
              <ArcSegment
                Size="50,50" RotationAngle="45"
                IsLargeArc="True" SweepDirection="Clockwise"
                Point="200,100"/>
            </PathFigure.Segments>
          </PathFigure>
        </PathGeometry.Figures>
      </PathGeometry>
    </Path.Data>
  </Path>
</Canvas>

See Also

Geometry Overview, Path Markup Syntax, Geometry, GeometryCollection, GeometryGroup


PathSegment Object (Abstract)

Represents a segment of a PathFigure object.

XAML | Cannot be used in XAML, see Remarks.
Scripting | Must use derived objects.

Properties

Name

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

For XAML syntaxes that take a PathSegment, you need to specify a nonabstract derived type of PathSegment as an object element. A PathSegment obtained in script will always be an instance of one of these derived types. For details, see the XAML syntax on the reference pages for ArcSegment, BezierSegment, LineSegment, PolyBezierSegment, PolyQuadraticBezierSegment, and QuadraticBezierSegment.

For more information, see the following PathSegment objects: ArcSegment, BezierSegment, LineSegment, PolyBezierSegment, PolyQuadraticBezierSegment, QuadraticBezierSegment.

See Also

PathFigure, Silverlight Geometries Overview


PathSegmentCollection Object

Represents a collection of PathSegment objects that can be individually accessed by index.

XAML
<PathSegmentCollection ...>
  oneOrMorePathSegments
</PathSegmentCollection ...>
Scripting
To create an object using scripting, see CreateFromXAML.

Properties

Count, Name

Methods

Add, Clear, Equals, FindName, GetHost, GetItem, GetValue, Insert, Remove, RemoveAt, SetValue

Remarks

PathSegmentCollection is used by the Segments property to store PathSegment information.

PathSegmentCollection defines no methods or properties beyond the basic Collection methods and properties. Methods such as Add or GetItem will expect or return objects that are of type PathSegment. PathSegment itself is an abstract type, so this generally means that the items in a collection are one of the following:

  • BezierSegment
  • LineSegment
  • PolyBezierSegment
  • PolyLineSegment Object
  • PolyQuadraticBezierSegment
  • QuadraticBezierSegment Object

The XAML syntax for properties that use a PathSegmentCollection is an example of an implicit collection syntax, where you can omit an actual PathSegmentCollection object element, as well as the <PathFigure.Segments> property element. Instead, you generally include one or more of the PathSegment derived types as child elements of a PathFigure. For more information about XAML implicit collection syntax, see XAML Syntax Overview. (Explicitly including a PathSegmentCollection object element is permissible XAML syntax, and might be useful if you intend to name the collection in XAML and manipulate its contents through script later.)

See Also

ArcSegment, BezierSegment, Collection, LineSegment, PathSegment, PathFigure, PolyBezierSegment, PolyQuadraticBezierSegment, QuadraticBezierSegment


Point Structure

Represents an ordered pair of integer x- and y-coordinates that defines a point in a two-dimensional plane.

XAML | <object.property = "X,Y" /> -or- <object.property = "X Y" />
Scripting | See Remarks.

Properties

Name, X, Y

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

The Point structure parallels a convention that is supported by a type converter, such that properties that take a Point as their value can specify a Point as a formatted string. The type converter generates a new Point value based on processing the string. The type converter functions both for XAML usages and script usages. In both cases, you supply a quoted string. The format of that string is an X,Y value pair. Alternatively, you can use a space rather than a comma as the delimiter betweeen X and Y in the string.

X and Y can be non-integer values in terms of permitted values, but are interpreted as integers regardless during rendering. In general, you should not use noninteger values. In particular, the comma used as X,Y separator in the type converter behavior will clash with cultural usages where the comma is the decimal division symbol if that value is entered as a string.

Point is the value type that is returned from a call to the GetPosition method used in mouse event handlers. Also, a Point is used for some properties such as To and From of a PointAnimation. For these cases, Point is a true object. You can get X and Y values from the GetPosition return value, but you cannot set them. You can get and set X and Y values from a PointAnimation property.

Point is also used extensively as a property value in geometry-related objects and for InkPresenter. If you attempt to get values through scripting for these Point values, the GetValue call will fail. This is because the object model does not use Point as a true object for these particular properties, and the type conversion behavior does not provide a reverse conversion to provide a "ToString" or other value representation to the object model.

In scripting, it is generally true that you cannot construct a new Silverlight object based on a constructor. However, for cases of types that have type converter support, you can use the type converter behavior to generate the object from out of a convertible type, in this case a string. So, in order to generate a Point value in script, you must target a property that takes a Point (such as EndPoint in the example).

Examples

JavaScript
function moveLine(sender, args) {
   myPath = sender.findName("myPath");
   myPath.Data.EndPoint = "250,150";
}

In this example, myPath is a Path previously defined in XAML, and the function is attached to a Canvas root as a mouse event handler.

See Also

Path Markup Syntax, Silverlight Transforms Overview


PointAnimation Object

Animates the value of a Point property between two target values by using linear interpolation over a specified Duration.

XAML | <PointAnimation .../>
Scripting | To create an object using scripting, see the CreateFromXAML method.

Properties

AutoReverse, BeginTime, By, Duration, FillBehavior, From, Name, RepeatBehavior, SpeedRatio, Storyboard.TargetName, Storyboard.TargetProperty, To

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

An animation updates the value of a property over a period of time. An animation effect can be subtle, such as moving a Shape a few pixels left or right, or dramatic, such as enlarging an object to 200 times its original size while spinning it and changing its color. To create an animation, you associate an animation with an object's property value.

The PointAnimation class creates a transition between two target values. To set the target values, use the object's From, To, and By properties. The following table summarizes how the From, To, and By properties may be used together or separately to determine an animation's target values.

Properties specified | Resulting behavior
From | The animation progresses from the value specified by the From property to the base value of the property being animated.
From and To | The animation progresses from the value specified by the From property to the value specified by the To property.
From and By | The animation progresses from the value specified by the From property to the value specified by the sum of the From and By properties.
To | The animation progresses from the animated property's base value or a previous animation's output value to the value specified by the To property.
By | The animation progresses from the base value of the property being animated or a previous animation's output value to the sum of that value and the value specified by the By property.

Note If you set both the To and By properties, the To property takes precedence and the By property is ignored.

To use other interpolation methods or to animate between more than two target values, use a PointAnimationUsingKeyFrames object.

Examples

The following example shows how to use the PointAnimation to animate the Center property of an EllipseGeometry.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Width="400" Height="300">
  <Path Fill="Blue">
    <Path.Data>

      <!-- Describes an ellipse. -->
      <EllipseGeometry x:Name="MyAnimatedEllipseGeometry"
       Center="200,100" RadiusX="15" RadiusY="15" />
    </Path.Data>

    <Path.Triggers>
      <EventTrigger RoutedEvent="Path.Loaded">
        <BeginStoryboard>
          <Storyboard>

            <!-- Animate the center point of the ellipse from 100 X, 300 Y
                 to 400 X, 100 Y over 5 seconds. -->
            <PointAnimation
              Storyboard.TargetProperty="Center"
              Storyboard.TargetName="MyAnimatedEllipseGeometry"
              Duration="0:0:5"
              From="100,300"
              To="400,100"
              RepeatBehavior="Forever" />

          </Storyboard>
        </BeginStoryboard>
      </EventTrigger>
    </Path.Triggers>
  </Path>
</Canvas>

See Also

Animation Overview
Silverlight Objects
Interactive Animations Overview


PointAnimationUsingKeyFrames Object

Animates the value of a Point property along a set of KeyFrames.

XAML
<PointAnimationUsingKeyFrames>
  oneOrMorePointKeyFrames
</PointAnimationUsingKeyFrames>
Scripting
To create an object using scripting, see CreateFromXAML.

Properties

AutoReverse, BeginTime, Duration, FillBehavior, KeyFrames, Name, RepeatBehavior, SpeedRatio, Storyboard.TargetName, Storyboard.TargetProperty

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

A key frame animation's target values are defined by its KeyFrames property, which contains a collection of DoubleKeyFrame objects. Each DoubleKeyFrame defines a segment of the animation with its own target Value and KeyTime. When the animation runs, it progresses from one key value to the next at the specified key times.

There are three types of DoubleKeyFrame classes, one for each supported interpolation method: LinearDoubleKeyFrame, DiscreteDoubleKeyFrame, and SplineDoubleKeyFrame.

Examples

The following example moves an ellipse along a triangular path. The example uses the PointAnimationUsingKeyFrames class to animate the Center property of an EllipseGeometry. This animation uses three key frames in the following manner:

  1. During the first half second, uses an instance of the LinearPointKeyFrame class to move the ellipse along a path at a steady rate from its starting position. Linear key frames like LinearPointKeyFrame create a smooth linear interpolation between values.
  2. During the end of the next half second, uses an instance of the DiscretePointKeyFrame class to suddenly move the ellipse along the path to the next position. Discrete key frames like DiscretePointKeyFrame create sudden jumps between values.
  3. During the final two seconds, uses an instance of the SplinePointKeyFrame class to move the ellipse back to its starting position. Spline key frames like SplinePointKeyFrame create a variable transition between values according to the values of the KeySpline property. In this example, the animation begins slowly and speeds up exponentially toward the end of the time segment.
XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Width="400" Height="300">
  <Path Fill="Blue">
    <Path.Data>

      <!-- Describes an ellipse. -->
      <EllipseGeometry x:Name="MyAnimatedEllipseGeometry"
       Center="200,100" RadiusX="15" RadiusY="15" />
    </Path.Data>

    <Path.Triggers>
      <EventTrigger RoutedEvent="Path.Loaded">
        <BeginStoryboard>
          <Storyboard>

            <!-- Animating the Center property uses 3 KeyFrames, which animate
                 the ellipse allong a triangular path. -->
            <PointAnimationUsingKeyFrames
              Storyboard.TargetProperty="Center"
              Storyboard.TargetName="MyAnimatedEllipseGeometry"
              Duration="0:0:5" RepeatBehavior="Forever">

              <!-- Over the first half second, Using a LinearPointKeyFrame, the ellipse
                   moves steadily from its starting position along the first line of the
                   trianglar path.  -->
              <LinearPointKeyFrame
                KeyTime="0:0:0.5"
                Value="100,300" />

              <!-- Using a DiscretePointKeyFrame, the ellipse suddenly changes position
                   after the first second of the animation. -->
              <DiscretePointKeyFrame
                KeyTime="0:0:1"
                Value="400,300" />

              <!-- Using a SplinePointKeyFrame, the ellipse moves back to its starting
                   position. It moves slowly at first and then speeds up. This key frame
                   takes 2 seconds to complete. -->
              <SplinePointKeyFrame
                KeySpline="0.6,0.0 0.9,0.00"
                KeyTime="0:0:3"
                Value="200,100" />
            </PointAnimationUsingKeyFrames>
          </Storyboard>
        </BeginStoryboard>
      </EventTrigger>
    </Path.Triggers>
  </Path>
</Canvas>

See Also

Key-Frame Animations Overview, Animation Overview, Interactive Animations Overview


PointKeyFrame Object (Abstract)

Base class for specific animation key frame techniques that define an animation segment with its own target value and interpolation method for a PointAnimationUsingKeyFrames.

XAML | Cannot be used in XAML
Scripting | Must use derived objects.

Properties

KeyTime, Name, Value

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

PointKeyFrame is an abstract class that defines Point value type key frames for three different techniques of key frame animation: DiscretePointKeyFrame, LinearPointKeyFrame, SplinePointKeyFrame. To animate a Point with key frames, you define a PointAnimationUsingKeyFrames animation, and populate its KeyFrames property with one or more DiscretePointKeyFrame, LinearPointKeyFrame, or SplinePointKeyFrame elements that define the key frames.

For more information, see the following PointKeyFrame derived objects: DiscretePointKeyFrame, LinearPointKeyFrame, SplinePointKeyFrame.

See Also

Animation Overview, PointAnimationUsingKeyFrames


PointKeyFrameCollection Object

Represents a collection of PointKeyFrame objects that can be individually accessed by index.

XAML
<PointKeyFrameCollection ...>
  oneOrMorePointKeyFrames
</PointKeyFrameCollection>
Scripting
To create an object using scripting, see CreateFromXAML.

Properties

Count, Name

Methods

Add, Clear, Equals, FindName, GetHost, GetItem, GetValue, Insert, Remove, RemoveAt, SetValue

Remarks

PointKeyFrameCollection defines no methods or properties beyond the basic Collection methods and properties. Methods such as Add or GetItem will expect or return objects that are of type PointKeyFrame. PointKeyFrame itself is an abstract class, so the items might be DiscretePointKeyFrame, LinearPointKeyFrame, or SplinePointKeyFrame.

The XAML syntax for properties that use a PointKeyFrameCollection is an example of an implicit collection syntax, where you can omit an actual PointKeyFrameCollection object element. Instead, you generally include one or more DiscretePointKeyFrame, LinearPointKeyFrame, or SplinePointKeyFrame object elements as child elements of a PointAnimationUsingKeyFrames. For more information about XAML implicit collection syntax, see XAML Syntax Overview. (Explicitly including a PointKeyFrameCollection object element is permissible XAML syntax, and might be useful if you intend to name the collection in XAML and manipulate its contents through script later.)

See Also

Collection, PointAnimationUsingKeyFrames, Animation Overview


PolyBezierSegment Object

Represents one or more cubic Bezier curves.

XAML | <PolyBezierSegment .../>
Scripting | To create an object using scripting, see the CreateFromXAML method.

Properties

Name, Points

Methods

Equals, FindName, GetHost, GetValue, SetValue

Examples

The following example shows how to use a PolyBezierSegment to create a series of curves.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Width="500" Height="100">
      <Path Stroke="Black" StrokeThickness="1">
        <Path.Data>
          <PathGeometry>
            <PathGeometry.Figures>
              <PathFigureCollection>

                <!-- The StartPoint specifies the starting point of the first curve. -->
                <PathFigure StartPoint="10,100">
                  <PathFigure.Segments>
                    <PathSegmentCollection>

                      <!-- The PolyBezierSegment specifies two cubic Bezier curves.
                           The first curve is from 10,100 (start point specified above)
                           to 300,100 with a control point of 0,0 and another control
                           point of 200,0. The second curve is from 300,100
                           (end of the last curve) to 600,100 with a control point of 300,0
                           and another control point of 400,0. -->
                      <PolyBezierSegment Points="0,0 200,0 300,100 300,0 400,0 600,100" />
                    </PathSegmentCollection>
                  </PathFigure.Segments>
                </PathFigure>
              </PathFigureCollection>
            </PathGeometry.Figures>
          </PathGeometry>
        </Path.Data>
      </Path>
</Canvas>

See Also

PathFigure, PathSegment


Polygon Object

Draws a polygon, which is a connected series of lines that form a closed shape.

XAML | <Polygon .../>
Scripting | To create an object using scripting, see CreateFromXAML.

Properties

Canvas.Left, Canvas.Top, Canvas.ZIndex, Clip, Cursor, Fill, FillRule, Height, Name, Opacity, OpacityMask, Points, RenderTransform, RenderTransformOrigin, Resources, Stretch, Stroke, StrokeDashArray, StrokeDashCap, StrokeDashOffset, StrokeEndLineCap, StrokeLineJoin, StrokeMiterLimit, StrokeStartLineCap, StrokeThickness, Tag, Triggers, Width

Methods

AddEventListener, CaptureMouse, Equals, FindName, GetHost, GetParent, GetValue, ReleaseMouseCapture, RemoveEventListener, SetValue

Events

Loaded, MouseEnter, MouseLeave, MouseLeftButtonDown, MouseLeftButtonUp, MouseMove

Examples

The following example shows how to use a Polygon to create a triangle.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <!-- This polygon shape uses pre-defined color values for its Stroke and
       Fill properties.
       The SolidColorBrush's Opacity property affects the fill color in
       this case by making it slightly transparent (opacity of 0.4) so
       that it blends with any underlying color. -->

  <Polygon
    Points="300,200 400,125 400,275 300,200"
    Stroke="Purple"
    StrokeThickness="2">
    <Polygon.Fill>
       <SolidColorBrush Color="Blue" Opacity="0.4"/>
    </Polygon.Fill>
  </Polygon>

</Canvas>

The following illustration shows the rendered shape.

See Also

Shape, Shapes Overview


Polyline Object

Draws a series of connected straight lines.

XAML | <Polyline .../>
Scripting | To create an object using scripting, see CreateFromXAML.

Properties

Canvas.Left, Canvas.Top, Canvas.ZIndex, Clip, Cursor, Fill, FillRule, Height, Name, Opacity, OpacityMask, Points, RenderTransform, RenderTransformOrigin, Resources, Stretch, Stroke, StrokeDashArray, StrokeDashCap, StrokeDashOffset, StrokeEndLineCap, StrokeLineJoin, StrokeMiterLimit, StrokeStartLineCap, StrokeThickness, Tag, Triggers, Width

Methods

AddEventListener, CaptureMouse, Equals, FindName, GetHost, GetParent, GetValue, ReleaseMouseCapture, RemoveEventListener, SetValue

Events

Loaded, MouseEnter, MouseLeave, MouseLeftButtonDown, MouseLeftButtonUp, MouseMove

Remarks

This object is similar to the Polygon object, except that this object does not need to be a closed shape.

Examples

The following example shows how to use a PolyLine to create a closed triangle.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <Polyline Points="50,25 0,100 100,100 50,25"
    Stroke="Blue" StrokeThickness="10"
    Canvas.Left="75" Canvas.Top="50" />

</Canvas>

See Also

Shape, Shapes Overview


PolyLineSegment Object

Represents a set of line segments defined as a series of points, where each point specifies the end point of a line segment.

XAML | <PolyLineSegment .../>
Scripting | To create an object using scripting, see the CreateFromXAML method.

Properties

Name, Points

Methods

Equals, FindName, GetHost, GetValue, SetValue

Examples

The following example creates a PathGeometry with two PathFigure objects, each of which contains multiple PathSegment objects.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Path Stroke="Black" StrokeThickness="1" >
    <Path.Data>
      <PathGeometry>
        <PathGeometry.Figures>
          <PathFigure StartPoint="10,50">
            <PathFigure.Segments>
              <BezierSegment
                Point1="100,0"
                Point2="200,200"
                Point3="300,100"/>
              <LineSegment Point="400,100" />
              <ArcSegment
                Size="50,50" RotationAngle="45"
                IsLargeArc="True" SweepDirection="Clockwise"
                Point="200,100"/>
            </PathFigure.Segments>
          </PathFigure>

          <PathFigure StartPoint="10,100">
            <PathFigure.Segments>
              <PolyLineSegment Points="50,100 50,150" />
              <QuadraticBezierSegment Point1="200,200" Point2="300,100"/>
            </PathFigure.Segments>
          </PathFigure>
        </PathGeometry.Figures>
      </PathGeometry>
    </Path.Data>
  </Path>
</Canvas>

The following illustration shows the shape created by this example.

A PathGeometry with multiple figures

See Also

Silverlight Objects


PolyQuadraticBezierSegment Object

Represents a set of quadratic Bezier segments.

XAML | <PolyQuadraticBezierSegment .../>
Scripting | To create an object using scripting, see the CreateFromXAML method.

Properties

Name, Points

Methods

Equals, FindName, GetHost, GetValue, SetValue

Examples

The following example creates two curves using a PolyQuadraticBezierSegment to specify the coordinates.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Width="500" Height="100">
      <Path Stroke="Black" StrokeThickness="1">
        <Path.Data>
          <PathGeometry>
            <PathGeometry.Figures>
              <PathFigureCollection>

                <!-- The StartPoint specifies the starting point of the first curve. -->
                <PathFigure StartPoint="10,100">
                  <PathFigure.Segments>
                    <PathSegmentCollection>

                      <!-- The PolyQuadraticBezierSegment specifies two Bezier curves.
                           The first curve is from 10,100 (start point specified above)
                           to 300,100 with a control point of 200,200. The second curve
                           is from 200,200 (end of the last curve) to 30,400 with a
                           control point of 0,200. -->
                      <PolyQuadraticBezierSegment Points="200,200 300,100 0,200 30,400" />
                    </PathSegmentCollection>
                  </PathFigure.Segments>
                </PathFigure>
              </PathFigureCollection>
            </PathGeometry.Figures>
          </PathGeometry>
        </Path.Data>
      </Path>
</Canvas>

See Also

PathFigure, PathSegment


QuadraticBezierSegment Object

Creates a quadratic Bezier curve between two points in a PathFigure.

XAML | <QuadraticBezierSegment .../>
Scripting | To create an object using scripting, see the CreateFromXAML method.

Properties

Name, Point1, Point2

Methods

Equals, FindName, GetHost, GetValue, SetValue

Examples

The following example creates a PathGeometry with two PathFigure objects, each of which contains multiple PathSegment objects.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Path Stroke="Black" StrokeThickness="1" >
    <Path.Data>
      <PathGeometry>
        <PathGeometry.Figures>
          <PathFigure StartPoint="10,50">
            <PathFigure.Segments>
              <BezierSegment
                Point1="100,0"
                Point2="200,200"
                Point3="300,100"/>
              <LineSegment Point="400,100" />
              <ArcSegment
                Size="50,50" RotationAngle="45"
                IsLargeArc="True" SweepDirection="Clockwise"
                Point="200,100"/>
            </PathFigure.Segments>
          </PathFigure>

          <PathFigure StartPoint="10,100">
            <PathFigure.Segments>
              <PolyLineSegment Points="50,100 50,150" />
              <QuadraticBezierSegment Point1="200,200" Point2="300,100"/>
            </PathFigure.Segments>
          </PathFigure>
        </PathGeometry.Figures>
      </PathGeometry>
    </Path.Data>
  </Path>
</Canvas>

The following illustration shows the shape created by this example.

A PathGeometry with multiple figures

See Also

PathFigure, PathSegment


RadialGradientBrush Object

Paints an area with a radial gradient. A focal point defines the beginning of the gradient, and a circle defines the end point of the gradient.

XAML
<RadialGradientBrush ...>
  oneOrMoreGradientStops
</RadialGradientBrush>
Scripting
To create an object using scripting, see CreateFromXAML.

Properties

Center, ColorInterpolationMode, GradientOrigin, GradientStops, MappingMode, Name, Opacity, RadiusX, RadiusY, RelativeTransform, SpreadMethod, Transform

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

The RadialGradientBrush is similar in programming model to the LinearGradientBrush. However, the linear gradient has a start and an end point to define the gradient vector, while the radial gradient has a circle, along with a focal point (the GradientOrigin), to define the gradient behavior. The circle defines the end point of the gradient. In other words, a gradient stop at 1.0 defines the color at the circle's circumference. The focal point defines the center of the gradient. A gradient stop at 0 defines the color at the focal point.

The following image shows a rectangle filled with a radial gradient. The radial gradient that goes from white to gray. The outside circle represents the gradient circle while the red dot denotes the focal point. This gradient has its SpreadMethod set to Pad.

A radial gradient with highlighted components

Examples

In the following example, a radial gradient brush is used to paint the interior of a rectangle.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <!-- This rectangle is painted with a radial gradient. -->
  <Rectangle Width="200" Height="100">
    <Rectangle.Fill>
      <RadialGradientBrush GradientOrigin="0.5,0.5" Center="0.5,0.5"
        RadiusX="0.5" RadiusY="0.5">
        <GradientStop Color="Yellow" Offset="0" />
        <GradientStop Color="Red" Offset="0.25" />
        <GradientStop Color="Blue" Offset="0.75" />
        <GradientStop Color="LimeGreen" Offset="1" />
      </RadialGradientBrush>
    </Rectangle.Fill>
  </Rectangle>

</Canvas>

The following illustration shows the gradient created in the previous example. The brush's gradient stops have been highlighted. Notice that, even though the results are different, the gradient stops in this example are identical to the gradient stops in the previous linear gradient brush examples.

Gradient stops in a radial gradient

See Also

Brush Overview, LinearGradientBrush


Rect Structure

A Rect object stores the upper-left corner, width, and height of a rectangle.

XAML | <object.property = "X,Y,width,height" /> -or- <object.property = "X Y width height" />
Scripting | See Remarks.

Properties

Height, Name, Width, X, Y

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

The Rect structure parallels a convention that is supported by a type converter, such that properties that take a Rect as their value can specify a Rect as a formatted string. The type converter generates a new Rect value based on processing the string. The type converter functions both for XAML usages and script usages. In both cases, you supply a quoted string. The format of that string is an X,Y,width,height value set. Alternatively, you can use a space rather than a comma as the delimiter between X,Y,width,height in the string.

X and Y, and height and width, can be non-integer values in terms of permitted values, but are interpreted as integers regardless during rendering. In general, you should not use noninteger values. In particular, the comma used as separator in the type converter behavior will clash with cultural usages where the comma is the decimal division symbol if that value is entered as a string.

Rect is the value type that is returned from a call to the GetBounds and GetBounds methods used for ink information capture. For these cases, Rect is returned as an object. However, you cannot set the values of this bounding Rect, it is for reference only.

Rect is also used as a property value in geometry-related objects (such as RectangleGeometry.Rect). If you attempt to get values through scripting for these geometry cases where the value is a Rect, the GetValue call will fail. This is because the object model does not use Rect as a true object for these particular properties, and the type conversion behavior does not provide a reverse conversion to provide a "ToString" or other value representation to the object model.

In scripting, it is generally true that you cannot construct a new Silverlight object based on a constructor. However, for cases of types that have type converter support, you can use the type converter behavior to generate the object from out of a convertible type, in this case a string. So, in order to generate a Rect value in script, you must target a property that takes a Rect (such as RectangleGeometry.Rect). For instance, if myRectGeometry is a reference to an existing RectangleGeometry, use this syntax: myRectGeometry.Rect = "100,100,200,300"; //place at point 100,100, width 200 height 300

See Also

RectangleGeometry, Ink Support In Microsoft Silverlight, Silverlight Geometries Overview


Rectangle Object

Draws a rectangle.

XAML | <Rectangle .../>
Scripting | To create an object using scripting, see CreateFromXAML.

Properties

Canvas.Left, Canvas.Top, Canvas.ZIndex, Clip, Cursor, Fill, Height, Name, Opacity, OpacityMask, RadiusX, RadiusY, RenderTransform, RenderTransformOrigin, Resources, Stretch, Stroke, StrokeDashArray, StrokeDashCap, StrokeDashOffset, StrokeEndLineCap, StrokeLineJoin, StrokeMiterLimit, StrokeStartLineCap, StrokeThickness, Tag, Triggers, Width

Methods

AddEventListener, CaptureMouse, Equals, FindName, GetHost, GetParent, GetValue, ReleaseMouseCapture, RemoveEventListener, SetValue

Events

Loaded, MouseEnter, MouseLeave, MouseLeftButtonDown, MouseLeftButtonUp, MouseMove

Examples

The following example shows how to create a rectangle.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <Rectangle Width="100" Height="100" Fill="Blue" Stroke="Red"
   Canvas.Top="20" Canvas.Left="20" StrokeThickness="3" />

</Canvas>

See Also

Shape, Shapes Overview


RectangleGeometry Object

Describes a two-dimensional rectangle.

XAML | <RectangleGeometry .../>
Scripting | To create an object using scripting, see CreateFromXAML.

Properties

FillRule, Name, RadiusX, RadiusY, Rect, Transform

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

FillRule is technically a property inherited from the base Geometry class, but setting it has no effect on a RectangleGeometry.

Examples

The following example shows how to create and render a RectangleGeometry. The position and the dimensions of the rectangle are defined by a Rect structure. The position is 50,50 and the height and width are both 25, which creates a square. The following illustration shows the output of the example.

A RectangleGeometry drawn at 50,50

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <Path Fill="LemonChiffon" Stroke="Black" StrokeThickness="1">
    <Path.Data>
      <RectangleGeometry Rect="50,50,25,25" />
    </Path.Data>
  </Path>
</Canvas>

See Also

Geometry Overview, Geometry, GeometryCollection, GeometryGroup


RepeatBehavior Object

Describes how a Timeline repeats its simple duration.

XAML
<object property="[days.]hours:minutes:seconds[.fractionalSeconds]" .../>
- or -
<object RepeatBehavior="iterationsx" .../>
- or -
<object property="Forever" .../>
Scripting
See Remarks.

Properties

Name, Seconds

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

Creating a Duration, KeyTime, RepeatBehavior, or TimeSpan in XAML or in script is only possible through a type conversion syntax when setting a property such as RepeatBehavior that takes one of these types, with the value specified as a string. The string format for specifying a time in each of these types is identical. Duration can also take the literals "Automatic" and "Forever". RepeatBehavior can take the literal "Forever" and also an iterations syntax "#x".

The main scenario for working with a RepeatBehavior as an object in script is to get or set its Seconds property in order to query or change an existing animation value.

See Also

Animation Overview


ResourceDictionary Object

Represents a collection of Resource objects.

XAML
<ResourceDictionary ...>
  oneOrMoreNamedStoryboards
</ResourceDictionary>
Scripting
To create an object using scripting, see CreateFromXAML.

Properties

Count, Name

Methods

Add, Clear, Equals, FindName, GetHost, GetItem, GetValue, Insert, Remove, RemoveAt, SetValue

Remarks

In Silverlight 1.0, the only valid content of a ResourceDictionary is one or more Storyboard elements. Each Storyboard must have a Name or x:Name attribute and each name value must be unique in the global namescope. Also, the ResourceDictionary object element is typically omitted, in favor of using the implicit collection syntax implied by the UIElement.Resources property element. Instead, you specify one or more Storyboard elements as content of <UIElement.Resources>. See Interactive Animations Overview.

See Also

Storyboard, Animation Overview, Interactive Animations Overview


RotateTransform Object

Rotates an object clockwise about a specified point in a 2-D x-y coordinate system.

XAML | <RotateTransform .../>
Scripting | To create an object using scripting, see CreateFromXAML.

Properties

Angle, CenterX, CenterY, Name

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

Angle rotates an object by a specified angle about the point CenterX, CenterY.

When you use a RotateTransform, the transformation rotates the coordinate system for a particular object about the point 0, 0. Therefore, depending on the position of the object, it might not rotate in place (around its center). For example, if an object is positioned 200 units from 0 along the x-axis, a rotation of 30 degrees can swing the object 30 degrees along a circle that has a radius of 200, which is drawn around the origin. To rotate an object in place, set the CenterX and CenterY of the RotateTransform to the center of the object to rotate.

The local 0,0 for an object can be offset on a Canvas using Canvas.Left and Canvas.Top, but this does not count as a transform; the object retains its own local 0,0 in this case for transform purposes. For details on this concept, see Object Layout in Silverlight.

Multiple transforms can be applied with a TransformGroup.

Examples

Transforms can alter the display of text in your application to create a decorative effect. The following example shows text rotated 90 degrees using a RotateTransform.

TextBlock using a RotateTransform

The following code example uses a RotateTransform to rotate text. An Angle value of 90 rotates the element 90 degrees clockwise.

XAML
<!-- Rotate the text 90 degrees using a RotateTransform. -->
<TextBlock Text="Rotated Text" FontSize="32" Foreground="Teal">
  <TextBlock.RenderTransform>
    <RotateTransform Angle="90" />
  </TextBlock.RenderTransform>
</TextBlock>

See Also

Transform Overview, Transform


Run Object

Represents a discrete section of formatted or unformatted text.

XAML | <Run .../>
Scripting | To create an object using scripting, see CreateFromXAML.

Properties

FontFamily, FontSize, FontStretch, FontStyle, FontWeight, Foreground, Name, Text, TextDecorations

Methods

Equals, FindName, GetHost, GetValue, SetValue

Examples

The following XAML example shows how to define several differently-formatted text strings within a TextBlock by using Run objects.

XAML
<!-- Display formatted text as Run objects within a TextBlock. -->
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007">

<TextBlock
  FontFamily="Arial" Width="400" Text="Sample text formatting runs">
  <LineBreak/>
  <Run Foreground="Maroon" FontFamily="Courier New" FontSize="24">Courier New 24</Run>
  <LineBreak/>
  <Run Foreground="Teal" FontFamily="Times New Roman" FontSize="18" FontStyle="Italic">Times New Roman Italic 18</Run>
  <LineBreak/>
  <Run Foreground="SteelBlue" FontFamily="Verdana" FontSize="14" FontWeight="Bold">Verdana Bold 14</Run>
</TextBlock>

</Canvas>

The following screenshot shows the rendered formatted text from the previous XAML content example.

Notice that the LineBreak object forces the text in each Run to display on a separate line. Without the LineBreak object, the text in each Run would flow together as one line, and eventually be truncated after exceeding the TextBlock's Width value. Here is how the formatted text would render without using LineBreak objects:

See Also

Text and Fonts Overview, LineBreak, TextBlock


RuntimeErrorEventArgs Object

Provides data for runtime error events.

XAML | You cannot use this object in XAML.
Scripting | Obtained as arguments for certain event handlers.

Properties

CharPosition, ErrorCode, ErrorMessage, ErrorType, LineNumber, MethodName, Name

Methods

Equals, FindName, GetHost, GetValue, SetValue

Examples

The following JavaScript example shows the portion of an event handler that displays error information specific to runtime errors.

JavaScript
    // errorArgs is an instance of RuntimeErrorEventArgs
    if(errorArgs.ErrorType == "RuntimeError")
    {
      var runtimeErrorMsg = "Silverlight Runtime Error  \n\n";

      // Basic error event informaiton.
      runtimeErrorMsg += "Error Type:    " + errorArgs.errorType     + "\n";
      runtimeErrorMsg += "Error Message: " + errorArgs.errorMessage  + "\n";
      runtimeErrorMsg += "Error Code:    " + errorArgs.errorCode  + "\n";

      // Runtime specific error event information.
      if (errorArgs.lineNumber != 0)
      {
        runtimeErrorMsg += "Line:     " + errorArgs.lineNumber     + "\n";
        runtimeErrorMsg += "Position: " +  errorArgs.charPosition  + "\n";
      }

     runtimeErrorMsg += "MethodName: " + errorArgs.methodName     + "\n";

     alert(runtimeErrorMsg);
    }

See Also

Silverlight Application Scripting Error Handling, ErrorEventArgs, ParserErrorEventArgs


ScaleTransform Object

Scales an object in the 2-D x-y coordinate system.

XAML | <ScaleTransform .../>
Scripting | To create an object using scripting, see CreateFromXAML.

Properties

CenterX, CenterY, Name, ScaleX, ScaleY

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

Use a ScaleTransform to stretch or shrink an object horizontally or vertically. The ScaleX property specifies by how much to stretch or shrink an object along the x-axis, and the ScaleY property specifies by how much to stretch or shrink an object along the y-axis. Scale operations are centered on the point specified by the CenterX and CenterY properties.

The local 0,0 for an object can be offset on a Canvas using Canvas.Left and Canvas.Top, but this does not count as a transform; the object retains its own local 0,0 in this case for transform purposes. For details on this concept, see Object Layout in Silverlight.

Multiple transforms can be applied with a TransformGroup. Custom transforms can be created with a MatrixTransform.

Transforms can alter the display of text in your application to create a decorative effect. The following illustration shows the second line of text scaled by 150% along the x-axis, and the third line of text scaled by 150% along the y-axis.

TextBlock using a ScaleTransform

Examples

The following XAML example uses a ScaleTransform to scale text from its original size.

XAML
<TextBlock
  FontFamily="Verdana"
  FontSize="32"
  FontWeight="Bold"
  Foreground="SteelBlue"
  Text="Scaled Text" />

<!-- Scale the text width using a ScaleTransform. -->
<TextBlock
  Canvas.Top="40"
  FontFamily="Verdana"
  FontSize="32"
  FontWeight="Bold"
  Foreground="SteelBlue"
  Text="Scaled Text">
  <TextBlock.RenderTransform>
    <ScaleTransform ScaleX="1.5" ScaleY="1.0" />
  </TextBlock.RenderTransform>
</TextBlock>

<!-- Scale the text height using a ScaleTransform. -->
<TextBlock
  Canvas.Top="80"
  FontFamily="Verdana"
  FontSize="32"
  FontWeight="Bold"
  Foreground="SteelBlue"
  Text="Scaled Text">
  <TextBlock.RenderTransform>
    <ScaleTransform ScaleX="1.0" ScaleY="1.5" />
  </TextBlock.RenderTransform>
</TextBlock>

Note Scaling text is not the same as increasing the font size of text. Font sizes are calculated independently of each other in order to provide the best resolution at different sizes. Scaled text, on the other hand, preserves the proportions of the original-sized text.

See Also

Transform Overview, Transform


Shape Object (Abstract)

Provides a base class for shape elements, such as Ellipse, Polygon, and Rectangle.

XAML | Cannot be used in XAML, must use derived objects.
Scripting | Must use derived objects.

Properties

Canvas.Left, Canvas.Top, Canvas.ZIndex, Clip, Cursor, Fill, Height, Name, Opacity, OpacityMask, RenderTransform, RenderTransformOrigin, Resources, Stretch, Stroke, StrokeDashArray, StrokeDashCap, StrokeDashOffset, StrokeEndLineCap, StrokeLineJoin, StrokeMiterLimit, StrokeStartLineCap, StrokeThickness, Tag, Triggers, Width

Methods

AddEventListener, CaptureMouse, Equals, FindName, GetHost, GetParent, GetValue, ReleaseMouseCapture, RemoveEventListener, SetValue

Events

Loaded, MouseEnter, MouseLeave, MouseLeftButtonDown, MouseLeftButtonUp, MouseMove

Remarks

For more information, see the following Shape objects: Ellipse, Line, Path, Polygon, Polyline, Rectangle.

Shape is abstract, and is not returned as that object type by any APIs in Silverlight 1.0. You also cannot create a true Shape in XAML. For this reason, Shape is not listed in the "Applies To" lists for various UIElement APIs, even though technically Shape is an intermediate class between UIElement and derived shapes such as Rectangle. Shape is also not listed in the "Applies To" lists for APIs that Shape itself defines, again because it is abstract and those APIs can only be exercised on a practical derived class.

See Also

Shapes Overview


Silverlight Plug-in Object

Represents a Silverlight plug-in instance that is hosted in an HTML page.

Scripting (Instantiation) | Silverlight.CreateObject(...) -or- Silverlight.CreateObjectEx(...)
Scripting (Runtime) | See Remarks.

Properties

Accessibility, ActualHeight, ActualWidth, Background, EnableFramerateCounter, EnableHtmlAccess, EnableRedrawRegions, FullScreen, InitParams, IsLoaded, MaxFrameRate, Root, Source, Windowless

Methods

CreateFromXaml, CreateFromXamlDownloader, CreateObject, FindName, IsVersionSupported

Events

OnError, OnFullScreenChange, OnLoad, OnResize

Remarks

When you install the Silverlight runtime components, you install a browser plug-in that exposes a Silverlight object model for scripting. Silverlight content is displayed within or more Silverlight plug-in instances that are defined on an HTML page. The Silverlight plug-in is packaged differently on the supported platforms. Internet Explorer on Windows uses an ActiveX model to host Silverlight plug-in instances, while all other browser and platform combinations use the Netscape plug-in technology to host Silverlight plug-in instances. For more information, see Using a Silverlight Plug-in.

The following diagram shows the relationship of the Web page, a single hosted Silverlight plug-in, and its content:

Relationship of Web page to Silverlight content

Relationship of Web page to Silverlight content

HTML DOM vs Siverlight Scripting Object Model

Once you have created the Silverlight plug-in instance, you can access it either from the HTML DOM of the surrounding HTML, or from the Silverlight object model once you have an entry point, such as an event handler. From within any object that is part of the Silverlight content, you can call GetHost to get the object for the plug-in that contains that content. For more information, see Silverlight Object Models.

Instantiation Parameters vs Object Model Topology for the Silverlight Plugin

The properties of the Silverlight plug-in that you use for scripting have a different topology than the parameters that you use for instantiation. In particular, many of the properties for scripting, as well as some methods, are grouped under the sub-objects content and settings.

For more information about the sub-objects and scripting to methods and properties of the Silverlight plug-in, see Using Silverlight Plug-ins.

Examples

The following JavaScript example shows how to retrieve the id value of the Silverlight plug-in from the HTML DOM by using the document.getElementById method:

JavaScript
var plugin_1 = document.getElementById("SLPlugin_1");

Using the GetHost Method

The GetHost method can be used by any UIElement-derived object to retrieve the Silverlight plug-in instance that contains the object. This method is especially useful for retrieving the Silverlight plug-in in an event handling function, in which the sender parameter often identifies a UIElement-derived object.

The following JavaScript example shows how to get a reference to a Silverlight plug-in in a Loaded event handler function:

JavaScript
// Event handler function for Loaded event.
function onLoaded(sender, eventArgs)
{
    // Retrieve a reference to the plug-in.
    var slPlugin = sender.getHost();

        // Determine whether the 1.0 version of Silverlight is available.
        alert("Silverlight 1.0: " + slPlugin.isVersionSupported("1.0"));
}

See Also

GetHost, Silverlight Object Models, Using CreateSilverlight.js and Silverlight.js, Using a Silverlight Plug-in, Referencing and Modifying Silverlight Objects


SkewTransform Object

Represents a 2-D skew.

XAML | <SkewTransform .../>
Scripting | To create an object using scripting, see CreateFromXAML.

Properties

AngleX, AngleY, CenterX, CenterY, Name

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

The local origin (0,0) for an object can be offset on a Canvas using Canvas.Left and Canvas.Top, but this does not count as a transform; the object retains its own local 0,0 in this case for transformation purposes. For details on this concept, see Object Layout in Silverlight.

Multiple transforms can be applied with a TransformGroup. Custom transforms can be created with a MatrixTransform.

The following illustration shows three examples of a SkewTransform applied to a Rectangle.

Transforms can alter the display of text in your application to create a decorative effect. The following illustration shows text skewed along the x-axis.

TextBlock using a SkewTransform

Examples

The following JavaScript example uses a SkewTransform to skew text. A skew, also known as a shear, is a transformation that stretches the coordinate space in a non-uniform manner. In this example, the two text strings are skewed -30 degrees and 30 degrees along the x-coordinate.

XAML
<!-- Skew the text using a SkewTransform. -->
<TextBlock
  FontSize="32"
  FontWeight="Bold"
  Foreground="Maroon"
  Text="Skewed Text">
  <TextBlock.RenderTransform>
    <SkewTransform AngleX="-30" AngleY="0" />
  </TextBlock.RenderTransform>
</TextBlock>

<TextBlock
  Canvas.Top="60"
  FontSize="32"
  FontWeight="Bold"
  Foreground="Maroon"
  Text="Skewed Text">
  <TextBlock.RenderTransform>
    <SkewTransform AngleX="30" AngleY="0" />
  </TextBlock.RenderTransform>
</TextBlock>

Note A typeface can simulate an italic style by shearing, or skewing, a glyph. However, a non-simulated italic typeface is typically designed to have a better visual appearance than a simulated italic typeface.

See Also

Transform Overview, Transform


SolidColorBrush Object

Silverlight SDK

SolidColorBrush

Paints an area with a solid color.

Syntax

XAML
<SolidColorBrush .../>
Scripting
To create an object using scripting, see CreateFromXAML.

Properties

Color, Name, Opacity, RelativeTransform, Transform

Methods

Equals, FindName, GetHost, GetValue, SetValue

Examples

One of the most common operations in any platform is to paint an area with a solid color. To accomplish this task, Silverlight provides the SolidColorBrush class. The following sections describe the different ways to paint with a SolidColorBrush.

To paint an area with a solid color in XAML, use one of the following options:

  • Select a predefined SolidColorBrush by name. For example, you can set the Fill of a Rectangle to "Red" or "MediumBlue". The example uses the name of a predefined SolidColorBrush to set the Fill of a Rectangle.

    XAML
    <Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <!-- This rectangle's fill is painted with a red SolidColorBrush,
       described using a named color. -->
  <Rectangle Width="100" Height="100" Fill="Red" />
</Canvas>

  • Choose a color from the 32-bit color palette by specifying the amounts of red, green, and blue to combine into a single solid color. The format for specifying a color from the 32-bit palette is #rrggbb, where rr is a two digit hexadecimal number specifying the relative amount of red, gg specifies the amount of green, and bb specifies the amount of blue. Additionally, the color can be specified as #aarrggbb, where aa specifies the alpha value, or transparency, of the color. This approach enables you to create colors that are partially transparent. In the following example, the Fill of a Rectangle is set to fully opaque red using hexadecimal notation.

    XAML
    <Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <!-- This rectangle's background is painted with a red SolidColorBrush,
       described using hexadecimal notation. -->
  <Rectangle Width="100" Height="100" Fill="#FFFF0000" />
</Canvas>

  • Use property element syntax to describe a SolidColorBrush. This syntax is more verbose but enables you to specify additional settings, such as the brush's opacity. In the following example, the Fill properties of two Rectangle elements are set to fully opaque red. The first brush's color is described using a predefined color name. The second brush's color is described using hexadecimal notation.

    XAML
    <Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <!-- Both of these rectangles' fills are painted with red
       SolidColorBrush objects, described using object element
       syntax. -->
  <Rectangle Width="100" Height="100">
    <Rectangle.Fill>
      <SolidColorBrush Color="Red" />
    </Rectangle.Fill>
  </Rectangle>

  <Rectangle Width="100" Height="100" Canvas.Top="110">
    <Rectangle.Fill>
      <SolidColorBrush Color="#FFFF0000" />
    </Rectangle.Fill>
  </Rectangle>
</Canvas>

See Also

Brush Overview, Brush


SplineColorKeyFrame Object

Animates from the Color value of the previous key frame to its own Value using splined interpolation.

XAML | <SplineColorKeyFrame .../>
Scripting | To create an object using scripting, see CreateFromXAML.

Properties

KeySpline, KeyTime, Name, Value

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

A key frame defines a segment of the ColorAnimationUsingKeyFrames to which it belongs. Each key frame has a target Value and a KeyTime. The KeyTime specifies the time at which the key frame's Value should be reached. A key frame animates from the target value of the previous key frame to its own target value. It starts when the previous key frame ends and ends when its own key time is reached.

Spline key frames like SplineColorKeyFrame creates a variable transition between values which is determined by the KeySpline property. Splined interpolation can be used to achieve more realistic "real world" timing effects such as acceleration and deceleration.

Examples

The following example uses the ColorAnimationUsingKeyFrames class to animate the Background property of a Canvas. This animation uses three key frames in the following manner:

  1. During the first two seconds, LinearColorKeyFrame gradually changes the color from green to red. Linear key frames like LinearColorKeyFrame create a smooth linear transition between values.
  2. During the end of the next half second, DiscreteColorKeyFrame quickly changes the color from red to yellow. Discrete key frames like DiscreteColorKeyFrame create sudden changes between values, that is, the color change in this part of the animation occurs quickly and is not subtle.
  3. During the final two seconds, SplineColorKeyFrame changes the color again�this time from yellow back to green. Spline key frames like SplineColorKeyFrame create a variable transition between values according to the values of the KeySpline property. In this example, the change in color begins slowly and speeds up exponentially toward the end of the time segment.
XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Width="200" Height="200"
  Background="White"
  x:Name="Page">
  <Canvas.Triggers>
    <EventTrigger RoutedEvent="Canvas.Loaded">
      <BeginStoryboard>
        <Storyboard x:Name="ColorStoryboard">
          <ColorAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="Page" Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)">

            <!-- Go from green to red in the first 2 seconds. LinearColorKeyFrame creates
            a smooth, linear animation between values. -->
            <LinearColorKeyFrame Value="Red" KeyTime="00:00:02" />

            <!-- In the next half second, go to yellow. DiscreteColorKeyFrame creates a
            sudden jump between values. -->
            <DiscreteColorKeyFrame Value="Yellow" KeyTime="00:00:2.5" />

            <!-- In the final 2 seconds of the animation, go from yellow back to green. SplineColorKeyFrame
            creates a variable transition between values depending on the KeySpline property. In this example,
            the animation starts off slow but toward the end of the time segment, it speeds up exponentially.-->
            <SplineColorKeyFrame Value="Green" KeyTime="00:00:4.5" KeySpline="0.6,0.0 0.9,0.00" />

          </ColorAnimationUsingKeyFrames>
        </Storyboard>
      </BeginStoryboard>
    </EventTrigger>
  </Canvas.Triggers>
</Canvas>

See Also

Animation Overview, ColorAnimationUsingKeyFrames


SplineDoubleKeyFrame Object

Animates from the Double value of the previous key frame to its own Value using splined interpolation.

XAML | <SplineDoubleKeyFrame .../>
Scripting | To create an object using scripting, see CreateFromXAML.

Properties

KeySpline, KeyTime, Name, Value

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

A key frame defines a segment of the DoubleAnimationUsingKeyFrames to which it belongs. Each key frame has a target Value and a KeyTime. The KeyTime specifies the time at which the key frame's Value should be reached. A key frame animates from the target value of the previous key frame to its own target value. It starts when the previous key frame ends and ends when its own key time is reached.

Spline key frames like SplineDoubleKeyFrame creates a variable transition between values which is determined by the KeySpline property. Splined interpolation can be used to achieve more realistic "real world" timing effects such as acceleration and deceleration.

Examples

The following example moves a rectangle across a screen. The example uses the DoubleAnimationUsingKeyFrames class to animate the X property of a TranslateTransform applied to a Rectangle. This animation, which repeats indefinitely, uses three key frames in the following manner:

  1. During the first three seconds, uses an instance of the LinearDoubleKeyFrame class to move the rectangle along a path at a steady rate from its starting position to the 500 position. Linear key frames like LinearDoubleKeyFrame create a smooth linear transition between values.
  2. At the end of the fourth second, uses an instance of the DiscreteDoubleKeyFrame class to suddenly move the rectangle to the next position. Discrete key frames like DiscreteDoubleKeyFrame create sudden jumps between values. In this example, the rectangle is at the starting position and then suddenly appears at the 500 position.
  3. In the final two seconds, uses an instance of the SplineDoubleKeyFrame class to move the rectangle back to its starting position. Spline key frames like SplineDoubleKeyFrame create a variable transition between values according to the value of the KeySpline property. In this example, the rectangle begins by moving slowly and then speeds up exponentially toward the end of the time segment.
XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Width="400" Height="300">
  <Rectangle Fill="Blue"
    Width="50" Height="50">
    <Rectangle.RenderTransform>
      <TranslateTransform
        x:Name="MyAnimatedTranslateTransform"
        X="0" Y="0" />
    </Rectangle.RenderTransform>
    <Rectangle.Triggers>
      <EventTrigger RoutedEvent="Rectangle.Loaded">
        <BeginStoryboard>
          <Storyboard>

            <!-- Animate the TranslateTransform's X property
                 from 0 to 350, then 50,
                 then 200 over 10 seconds. -->
            <DoubleAnimationUsingKeyFrames
              Storyboard.TargetName="MyAnimatedTranslateTransform"
              Storyboard.TargetProperty="X"
              Duration="0:0:10">

                <!-- Using a LinearDoubleKeyFrame, the rectangle moves
                     steadily from its starting position to 500 over
                     the first 3 seconds.  -->
                <LinearDoubleKeyFrame Value="500" KeyTime="0:0:3" />

                <!-- Using a DiscreteDoubleKeyFrame, the rectangle suddenly
                     appears at 400 after the fourth second of the animation. -->
                <DiscreteDoubleKeyFrame Value="400" KeyTime="0:0:4" />

                <!-- Using a SplineDoubleKeyFrame, the rectangle moves
                     back to its starting point. The
                     animation starts out slowly at first and then speeds up.
                     This KeyFrame ends after the 6th
                     second. -->
                <SplineDoubleKeyFrame KeySpline="0.6,0.0 0.9,0.00" Value="0" KeyTime="0:0:6" />

            </DoubleAnimationUsingKeyFrames>
          </Storyboard>
        </BeginStoryboard>
      </EventTrigger>
    </Rectangle.Triggers>
  </Rectangle>
</Canvas>

See Also

Animation Overview, DoubleAnimationUsingKeyFrames


SplinePointKeyFrame Object

Animates from the Point value of the previous key frame to its own Value using splined interpolation.

XAML | <SplinePointKeyFrame .../>
Scripting | To create an object using scripting, see CreateFromXAML.

Properties

KeySpline, KeyTime, Name, Value

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

A key frame defines a segment of the PointAnimationUsingKeyFrames to which it belongs. Each key frame has a target Value and a KeyTime. The KeyTime specifies the time at which the key frame's Value should be reached. A key frame animates from the target value of the previous key frame to its own target value. It starts when the previous key frame ends and ends when its own key time is reached.

Spline key frames like SplinePointKeyFrame creates a variable transition between values which is determined by the KeySpline property. Splined interpolation can be used to achieve more realistic "real world" timing effects such as acceleration and deceleration.

Examples

The following example moves an ellipse along a triangular path. The example uses the PointAnimationUsingKeyFrames class to animate the Center property of an EllipseGeometry. This animation uses three key frames in the following manner:

  1. During the first half second, uses an instance of the LinearPointKeyFrame class to move the ellipse along a path at a steady rate from its starting position. Linear key frames like LinearPointKeyFrame create a smooth linear interpolation between values.
  2. During the end of the next half second, uses an instance of the DiscretePointKeyFrame class to suddenly move the ellipse along the path to the next position. Discrete key frames like DiscretePointKeyFrame create sudden jumps between values.
  3. During the final two seconds, uses an instance of the SplinePointKeyFrame class to move the ellipse back to its starting position. Spline key frames like SplinePointKeyFrame create a variable transition between values according to the values of the KeySpline property. In this example, the animation begins slowly and speeds up exponentially toward the end of the time segment.
XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Width="400" Height="300">
  <Path Fill="Blue">
    <Path.Data>

      <!-- Describes an ellipse. -->
      <EllipseGeometry x:Name="MyAnimatedEllipseGeometry"
       Center="200,100" RadiusX="15" RadiusY="15" />
    </Path.Data>

    <Path.Triggers>
      <EventTrigger RoutedEvent="Path.Loaded">
        <BeginStoryboard>
          <Storyboard>

            <!-- Animating the Center property uses 3 KeyFrames, which animate
                 the ellipse allong a triangular path. -->
            <PointAnimationUsingKeyFrames
              Storyboard.TargetProperty="Center"
              Storyboard.TargetName="MyAnimatedEllipseGeometry"
              Duration="0:0:5" RepeatBehavior="Forever">

              <!-- Over the first half second, Using a LinearPointKeyFrame, the ellipse
                   moves steadily from its starting position along the first line of the
                   trianglar path.  -->
              <LinearPointKeyFrame
                KeyTime="0:0:0.5"
                Value="100,300" />

              <!-- Using a DiscretePointKeyFrame, the ellipse suddenly changes position
                   after the first second of the animation. -->
              <DiscretePointKeyFrame
                KeyTime="0:0:1"
                Value="400,300" />

              <!-- Using a SplinePointKeyFrame, the ellipse moves back to its starting
                   position. It moves slowly at first and then speeds up. This key frame
                   takes 2 seconds to complete. -->
              <SplinePointKeyFrame
                KeySpline="0.6,0.0 0.9,0.00"
                KeyTime="0:0:3"
                Value="200,100" />
            </PointAnimationUsingKeyFrames>
          </Storyboard>
        </BeginStoryboard>
      </EventTrigger>
    </Path.Triggers>
  </Path>
</Canvas>

See Also

Animation Overview, PointAnimationUsingKeyFrames


Storyboard Object

Controls and provides object and property targeting information for its child animations.

XAML
<Storyboard ...>
  oneOrMoreChildTimelines
</Storyboard>
Scripting
To create an object using scripting, see CreateFromXAML.

Properties

AutoReverse, BeginTime, Children, Duration, FillBehavior, Name, RepeatBehavior, SpeedRatio, Storyboard.TargetName, Storyboard.TargetProperty

Methods

Begin, Equals, FindName, GetHost, GetParent, GetValue, Pause, Resume, Seek, SetValue, Stop

Events

Completed

Remarks

In addition to starting a storyboard automatically when an object loads, you can use the interactive methods of the Storyboard object to start, pause, resume, and stop an animation. For more information, see the Interactive Animations Overview.

Examples

The following example shows how to use a Storyboard and an EventTrigger to make a rectangle that fades in and out of view after it is loaded.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Rectangle
    x:Name="MyAnimatedRectangle"
    Width="100"
    Height="100"
    Fill="Blue">
    <Rectangle.Triggers>

      <!-- Animates the rectangle's opacity. -->
      <EventTrigger RoutedEvent="Rectangle.Loaded">
        <BeginStoryboard>
          <Storyboard>
            <DoubleAnimation
              Storyboard.TargetName="MyAnimatedRectangle"
              Storyboard.TargetProperty="Opacity"
              From="1.0" To="0.0" Duration="0:0:5" AutoReverse="True" RepeatBehavior="Forever" />
          </Storyboard>
        </BeginStoryboard>
      </EventTrigger>
    </Rectangle.Triggers>
  </Rectangle>
</Canvas>

See Also

Animation Overview, Interactive Animations Overview


Stretch Enumeration

Describes how content is resized to fill its allocated space.

XAML | <object property="EnumerationValue" .../>
Scripting | value = "EnumerationValue"

Enumeration Values

Value | Description
Fill | The content is resized to fill the destination dimensions. The aspect ratio is not preserved.
None | The content preserves its original size.
Uniform | The content is resized to fit in the destination dimensions while it preserves its native aspect ratio.
UniformToFill | The content is resized to fill the destination dimensions while it preserves its native aspect ratio. If the aspect ratio of the destination rectangle differs from the source, the source content is clipped to fit in the destination dimensions.

Remarks

The following illustration shows the different Stretch values.

Different Brush Stretch settings

Applies To

Stretch (Image), Stretch (ImageBrush), Stretch (MediaElement), Stretch (Shape), Stretch (VideoBrush)

See Also

Image, MediaElement


Stroke Object

Represents a collection of points that correspond to a stylus-down, move, and stylus-up sequence.

Syntax

XAML
<Stroke .../>
Scripting
To create an object using scripting, see CreateFromXAML.

Properties

DrawingAttributes, Name, StylusPoints

Methods

Equals, FindName, GetBounds, GetHost, GetValue, HitTest, SetValue

Remarks

The Stroke object is not related to the Stroke property which is a member of the Shape class.

Examples

JavaScript
var agCtrl;
var inkPresenter; // Corresponds to InkPresenter element in xaml
var newStroke = null; // The Stroke variable we'll use here in mouse handlers
// DrawingAttributes variables
var daWidth = 2;
var daHeight = 2;
var daColor = "Black";
var daOutlineColor = "Black";

function root_Loaded(sender, args)
{
    // Get the html object which contains the Silverlight plug-in
    agCtrl = sender.GetHost();
    inkPresenter = sender.findname("inkPresenterElement");
}

// Capture mouse movement when the left button is pressed and create the stroke
function InkPresenterMouseDown(sender,args)
{
   inkPresenter.CaptureMouse();

   newStroke = agCtrl.content.createFromXaml('<Stroke/>');

   var da = agCtrl.content.CreateFromXaml('<DrawingAttributes/>');
   newStroke.DrawingAttributes = da;

   // Set the drawing attributes properties
   newStroke.DrawingAttributes.Width = daWidth;
   newStroke.DrawingAttributes.Height = daHeight;
   newStroke.DrawingAttributes.Color = daColor;
   newStroke.DrawingAttributes.OutlineColor = daOutlineColor;

   newStroke.StylusPoints.AddStylusPoints(args.GetStylusPoints(inkPresenter));
   inkPresenter.Strokes.Add(newStroke);
}

// Add the new points to the Stroke we're working with
function InkPresenterMouseMove(sender,args)
{
   if (newStroke != null)
   {
      newStroke.StylusPoints.AddStylusPoints(args.GetStylusPoints(inkPresenter));
   }
}

// Release the mouse
function InkPresenterMouseUp(sender,args)
{
   newStroke = null;
   inkPresenter.ReleaseMouseCapture();
}

See Also

Stroke Collection, InkPresenter


StrokeCollection Object

Represents zero or more Stroke objects that are grouped together.

Syntax

XAML
<StrokeCollection ...>
  oneOrMoreStrokes
</StrokeCollection>
Scripting
To create an object using scripting, see CreateFromXAML.

Properties

Count, Name

Methods

Add, Clear, Equals, FindName, GetBounds, GetHost, GetItem, GetValue, HitTest, Insert, Remove, RemoveAt, SetValue

Remarks

StrokeCollection is used by the Strokes property object to store Stroke information.

Collection methods such as Add or GetItem will expect or return objects that are of type Stroke. In addition to Collection methods, this collection also defines the methods GetBounds and HitTest.

The XAML syntax for properties that use a StrokeCollection is potentially an example of an implicit collection syntax, where you can omit an actual StrokeCollection object element. However, prepopulating an InkPresenter with strokes is not a common technique; usually you start with a blank Strokes collection and capture strokes as user input with runtime JavaScript. For more information about XAML implicit collection syntax, see XAML Syntax Overview.

Examples

JavaScript
// Inking variables
var agCtrl;
var inkPresenter; // Corresponds to InkPresenter element in XAML
var newStroke = null; // The Stroke variable we'll use here in mouse handlers

function root_Loaded(sender, args)
{
  // Get the html object which contains the Silverlight plug-in.
  agCtrl = sender.GetHost();

  // hold on to the InkPresenter plug-in interface
  inkPresenter = sender.findname("inkPresenterElement");
}

// Capture mouse and create the stroke
function InkPresenterMouseDown(sender,args)
{
  inkPresenter.CaptureMouse();

  // Erase mode?
  if (args.GetStylusInfo().IsInverted)
  {
    var sc = agCtrl.content.createFromXaml("<StrokeCollection/>");
    sc = inkPresenter.Strokes.HitTest(args.GetStylusPoints(inkPresenter));

    for (var i = 0; i < sc.Count; i++)
    {
      inkPresenter.Strokes.Remove(sc.GetItem(i));
    }
  }
  else // Ink mode
  {
    newStroke = agCtrl.content.createFromXaml('<Stroke/>');

    var da = agCtrl.content.createFromXaml('<DrawingAttributes/>');
    newStroke.DrawingAttributes = da;
    var spc = agCtrl.content.createFromXaml('<StylusPointCollection/>');
    newStroke.StylusPoints = spc;

    newStroke.DrawingAttributes.Width = 5;
    newStroke.DrawingAttributes.Height = 5;
    newStroke.DrawingAttributes.Color = "Green";
    newStroke.DrawingAttributes.OutlineColor = "Black";

    newStroke.StylusPoints.AddStylusPoints(args.GetStylusPoints(inkPresenter));
    inkPresenter.Strokes.Add(newStroke);
  }
}

// Add the new points to the Stroke we're working with or
// delete strokes if stylus is inverted. Thus, implementing back of pen erase.
function InkPresenterMouseMove(sender,args)
{
  // Erase mode?
  if (args.GetStylusInfo().IsInverted)
  {
    // Use HitTest to get all the strokes that were intersected
    var hitStrokes = inkPresenter.Strokes.HitTest(args.GetStylusPoints(inkPresenter));

    // Remove the strokes that were intersected above
    for (var i = 0; i < hitStrokes.Count; i++)
    {
      inkPresenter.Strokes.Remove(hitStrokes.GetItem(i));
    }
  }
  else
  {
    if (newStroke != null)
    {
      newStroke.StylusPoints.AddStylusPoints(args.GetStylusPoints(inkPresenter));
    }
  }
}

// Release the mouse
function InkPresenterMouseUp(sender,args)
{
  newStroke = null;
  inkPresenter.ReleaseMouseCapture();
}

function ClearInkMouseDown(sender,args)
{
  inkPresenter.Strokes.Clear();
}

See Also

Stroke, InkPresenter


StylusInfo Object

Represents information about the state of the stylus.

Syntax

XAML
Cannot be used in XAML.
Scripting
To create an object using scripting, see CreateFromXAML.

Properties

IsInverted, Name, DeviceType

Methods

Equals, FindName, GetHost, GetValue, SetValue

Examples

The following example uses the PressureFactor property to determine the size of a stroke. The PressureFactor is obtained from the first StylusPoint of each stroke, then the stroke Width and Height is calculated by multiplying the PressureFactor by 20.

JavaScript
var agCtrl;
var inkPresenter; // Corresponds to InkPresenter element in xaml
var newStroke = null; // The Stroke variable we'll use here in mouse handlers
var daWidth;
var daHeight;

function root_Loaded(sender, args)
{
    // Get the html object which contains the Silverlight plug-in
    agCtrl = sender.GetHost();
    inkPresenter = sender.findname("inkPresenterElement");
}

// Capture mouse movement when the left button is pressed then create the stroke.
function InkPresenterMouseDown(sender,args)
{
   inkPresenter.CaptureMouse();
   newStroke = agCtrl.content.createFromXaml('<Stroke/>');

   // Get the DeviceType
   if(args.GetStylusInfo().deviceType == "Stylus")
   {
     var sps = args.GetStylusPoints(inkPresenter);
     SetStylusStrokeSize(sps);
   }
   // If the device type is not a stylus then use the default stroke height and width.
   else
   {
     daWidth = 3;
     daHeight = 3;
   }

   // Set the drawing attributes properties
   newStroke.DrawingAttributes.Width = daWidth;
   newStroke.DrawingAttributes.Height = daHeight;
   newStroke.DrawingAttributes.Color = "Blue";
   newStroke.DrawingAttributes.OutlineColor = "Orange";

   newStroke.StylusPoints.AddStylusPoints(args.GetStylusPoints(inkPresenter));
   inkPresenter.Strokes.Add(newStroke);
}

// Add the new points to the Stroke we're working with
function InkPresenterMouseMove(sender,args)
{
   if (newStroke != null)
   {
      newStroke.StylusPoints.AddStylusPoints(args.GetStylusPoints(inkPresenter));
   }
}

// Release the mouse
function InkPresenterMouseUp(sender,args)
{
   newStroke = null;
}

// Set the size of the stroke based on the initial pressureFactor of the stroke.
function SetStylusStrokeSize(sps)
{
    var p;
    // Set variable p to the first StylusPoint in the Stroke
    p = sps.getItem(0).pressureFactor;
    daWidth = p * 20.0;
    daHeight = p * 20.0;
}

See Also

Ink Support In Microsoft Silverlight


StylusPoint Object

Represents a single point collected while the user is inking with the stylus or mouse.

Syntax

XAML
<StylusPoint .../>
Scripting
To create an object using scripting, see CreateFromXAML.

Properties

Name, PressureFactor, X, Y

Methods

Equals, FindName, GetHost, GetValue, SetValue

Examples

In the following example the x and y coordinates and pressure data of each StylusPoint are sent to a text TextBlock as they are added to a stroke.

JavaScript
// Add the new points to the Stroke we're working with and display the StylusPoint coordinates.
function InkPresenterMouseMove(sender,args)
{
   if (newStroke != null)
   {
      newStroke.StylusPoints.AddStylusPoints(args.GetStylusPoints(inkPresenter));
      xCoord.Text = "" + args.GetStylusPoints(inkPresenter).GetItem(0).X;
      yCoord.Text = "" + args.GetStylusPoints(inkPresenter).GetItem(0).Y;
      pressureData.Text = "" + args.GetStylusPoints(inkPresenter).GetItem(0).PressureFactor;
   }
}

See Also


StylusPointCollection Object

Represents a set of related StylusPoint objects.

Syntax

XAML
<StylusPointCollection ...>
  oneOrMoreStylusPoints
</StylusPointCollection>
Scripting
To create an object using scripting, see CreateFromXAML.

Properties

Count, Name

Methods

Add, AddStylusPoints, Clear, Equals, FindName, GetHost, GetItem, GetValue, Insert, Remove, RemoveAt, SetValue

Remarks

This collection is used primarily by the Stroke class to keep track of the StylusPoint objects that define the appearance of the Stroke object.

A StylusPointCollection can belong to more than one Stroke object.

Collection methods such as Add or GetItem will expect or return objects that are of type StylusPoint. In addition to Collection methods, this collection also defines the method AddStylusPoints.

The XAML syntax for properties that use a StylusPoint is potentially an example of an implicit collection syntax, where you can omit an actual StylusPointCollection object element. However, prepopulating an InkPresenter with strokes is not a common technique; usually you start with a blank Strokes collection and capture strokes as user input with runtime JavaScript. For more information about XAML implicit collection syntax, see XAML Syntax Overview.

Examples

JavaScript
// Inking variables
var agCtrl;
var inkPresenter; // Corresponds to InkPresenter element in XAML
var newStroke = null; // The Stroke variable we'll use here in mouse handlers

function root_Loaded(sender, args)
{
  // Get the html object which contains the Silverlight plug-in.
  agCtrl = sender.GetHost();

  // hold on to the InkPresenter plug-in interface
  inkPresenter = sender.findname("inkPresenterElement");
}

// Capture mouse and create the stroke
function InkPresenterMouseDown(sender,args)
{
  inkPresenter.CaptureMouse();

  // Erase mode?
  if (args.GetStylusInfo().IsInverted)
  {
    var sc = agCtrl.content.createFromXaml("<StrokeCollection/>");
    sc = inkPresenter.Strokes.HitTest(args.GetStylusPoints(inkPresenter));

    for (var i = 0; i < sc.Count; i++)
    {
      inkPresenter.Strokes.Remove(sc.GetItem(i));
    }
  }
  else // Ink mode
  {
    newStroke = agCtrl.content.createFromXaml('<Stroke/>');

    var da = agCtrl.content.createFromXaml('<DrawingAttributes/>');
    newStroke.DrawingAttributes = da;
    var spc = agCtrl.content.createFromXaml('<StylusPointCollection/>');
    newStroke.StylusPoints = spc;

    newStroke.DrawingAttributes.Width = 5;
    newStroke.DrawingAttributes.Height = 5;
    newStroke.DrawingAttributes.Color = "Green";
    newStroke.DrawingAttributes.OutlineColor = "Black";

    newStroke.StylusPoints.AddStylusPoints(args.GetStylusPoints(inkPresenter));
    inkPresenter.Strokes.Add(newStroke);
  }
}

// Add the new points to the Stroke we're working with or
// delete strokes if stylus is inverted. Thus, implementing back of pen erase.
function InkPresenterMouseMove(sender,args)
{
  // Erase mode?
  if (args.GetStylusInfo().IsInverted)
  {
    // Use HitTest to get all the strokes that were intersected
    var hitStrokes = inkPresenter.Strokes.HitTest(args.GetStylusPoints(inkPresenter));

    // Remove the strokes that were intersected above
    for (var i = 0; i < hitStrokes.Count; i++)
    {
      inkPresenter.Strokes.Remove(hitStrokes.GetItem(i));
    }
  }
  else
  {
    if (newStroke != null)
    {
      newStroke.StylusPoints.AddStylusPoints(args.GetStylusPoints(inkPresenter));
    }
  }
}

// Release the mouse
function InkPresenterMouseUp(sender,args)
{
  newStroke = null;
  inkPresenter.ReleaseMouseCapture();
}

function ClearInkMouseDown(sender,args)
{
  inkPresenter.Strokes.Clear();
}

See Also

Ink Support In Microsoft Silverlight


TextBlock Object

Represents a lightweight object for displaying single-line and multi-line multi-formatted text.

XAML | <TextBlock .../>
Scripting | To create an object using scripting, see CreateFromXAML.

Properties

ActualHeight, ActualWidth, Canvas.Left, Canvas.Top, Canvas.ZIndex, Clip, Cursor, FontFamily, FontSize, FontStretch, FontStyle, FontWeight, Foreground, Height, Inlines, Name, Opacity, OpacityMask, RenderTransform, RenderTransformOrigin, Resources, Text, TextDecorations, TextWrapping, Tag, Triggers, Visibility, Width

Methods

AddEventListener, CaptureMouse, Equals, FindName, GetHost, GetParent, GetValue, ReleaseMouseCapture, RemoveEventListener, SetFontSource, SetValue

Events

Loaded, MouseEnter, MouseLeave, MouseLeftButtonDown, MouseLeftButtonUp, MouseMove

Remarks

The TextBlock object is the primary element for displaying text in Silverlight applications.

The default value of the FontSize property of a rendered TextBlock is 14.666 pixels, which is exactly 11 points.

The default value of theFontFamily property of a rendered TextBlock is "Lucida Sans Unicode, Lucida Grande". Application-served fonts are not required to enable the default font.

When setting text in a TextBlock, it is not necessary in XAML to explicitly specify the Text property; you can use the intuitive markup syntax of placing text within the TextBlock container as its content, or inner text:

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007">
  <TextBlock>Hello, world!</TextBlock>
</Canvas>

Note Any leading or trailing whitespace is not preserved when setting the Text property.

The Run and LineBreak objects can also be used to render text. The Run object is a text element that represents a discrete section of formatted or unformatted text. The LineBreak object represents an explicit new line in a TextBlock. For more information on using a TextBlock and formatting text, see Text and Fonts Overview.

Examples

>The following XAML example shows how to define a TextBlock element and set its Text property to a character string:

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007">
  <TextBlock Text="Hello, world!" />
</Canvas>

The following image displays the result of the previous XAML content example:

TextBlock rendering with default font properties

See Also

Text and Fonts Overview, Run, LineBreak


Timeline Object (Abstract)

Defines a segment of time.

XAML | Cannot be used in XAML, see Remarks.
Scripting | Must use derived objects.

Properties

AutoReverse, BeginTime, Duration, FillBehavior, Name, RepeatBehavior, SpeedRatio, Storyboard.TargetName, Storyboard.TargetProperty

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

For XAML syntaxes that take a Timeline, you need to specify a nonabstract derived type of Timeline as an object element. A Timeline obtained in script will always be an instance of one of these derived types. For details, see the XAML syntax on the reference pages for Storyboard, ColorAnimation, ColorAnimationUsingKeyFrames, DoubleAnimation, DoubleAnimationUsingKeyFrames, PointAnimation, and PointAnimationUsingKeyFrames.

For more information, see the following Timeline objects: Storyboard, ColorAnimation, ColorAnimationUsingKeyFrames, DoubleAnimation, DoubleAnimationUsingKeyFrames, PointAnimation, PointAnimationUsingKeyFrames.

See Also

Animation Overview


TimelineCollection Object

Represents a collection of Timeline objects.

XAML | Cannot be used in XAML
Scripting | Cannot explicitly create, reference to existing only.

Properties

Count, Name

Methods

Add, Clear, Equals, FindName, GetHost, GetItem, GetValue, Insert, Remove, RemoveAt, SetValue

Remarks

TimelineCollection defines no methods or properties beyond the basic Collection methods and properties. Methods such as Add or GetItem will expect or return objects that are of type Timeline.

The XAML syntax for properties that use a TimelineCollection is an example of an implicit collection syntax, where can omit an actual TimelineCollection object element. Instead, you generally include one or more animation types (Timeline elements) as child elements of a Storyboard. In this case the explicit syntax is not permitted; neither a <Storyboard.Children> property element nor a <TimelineCollection> object element are accepted by the parser. For more information about XAML implicit collection syntax, see XAML Syntax Overview. (Explicitly including a TimelineCollection object element is permissible XAML syntax, and might be useful if you intend to name the collection in XAML and manipulate its contents through script later.)

See Also

Animation Overview, Collection


TimelineMarker Object

Represents metadata associated with a specific point in a media file.

XAML | <TimelineMarker .../>
Scripting | To create an object using scripting, see CreateFromXAML.

Properties

Name, Text, Time, Type

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

A timeline marker is metadata associated with a particular point in a media file. These markers are usually created ahead of time and stored in the media file itself. They are typically used to name different scenes in a video or provide scripting cues. By handling the MediaElement object's MarkerReached event or by accessing the MediaElement object's Markers property, you can use timeline markers to trigger actions or enable users to seek to selected positions in the media file.

TimelineMarker objects are used to represent all types of windows media technology timeline markers: markers and script commands (both metadata and separate stream). The following table lists how the Text and Type properties map to its source marker or script command.

TimelineMarker property | Windows Media marker | Windows Media script command
Text | "Name" field | "Param" field
Type | Always set to Name | "Type" field

The XAML syntax for TimelineMarker is mainly only relevant for a CreateFromXaml scenario. Populating the initial .Markers collection of a MediaElement with one or more TimelineMarker in XAML using one or more is permitted by the parser. However, this has no effect because the .Markers collection is specific to a media source rather than to a MediaElement. At the time the markup is specified, the media specified by Source is not yet loaded, and the true .Markers collection is only available once the media (and its internal markers) are loaded at runtime. Whenever a Source is loaded, any pre-existing .Markers collection in the XAML is discarded and replaced by the media's timeline markers. After the media is loaded, you can manipulate the .Markers collection in script, and use CreateFromXaml to add a new marker.

Examples

The following example creates a MediaElement object and responds to its MarkerReached event. Each time a timeline marker is reached, the example displays the timeline marker's Time, Type, and Text values.

XAML
<Canvas
   xmlns="http://schemas.microsoft.com/client/2007"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 Width="300" Height="300">

  <MediaElement x:Name="media"
    Canvas.Top="50"
    MediaOpened="onMediaOpened"
    MarkerReached="onMarkerReached" Source="thebutterflyandthebear.wmv"
    Width="300" Height="200" />

  <Canvas Canvas.Left="10" Canvas.Top="5">

    <TextBlock
      FontSize="12" Foreground="DarkGray">Time:</TextBlock>

    <TextBlock x:Name="timeTextBlock"
      Canvas.Left="40"
      FontSize="12" />

    <TextBlock Canvas.Top="12"
      FontSize="12" Foreground="DarkGray">Type:</TextBlock>

    <TextBlock x:Name="typeTextBlock"
      Canvas.Left="40" Canvas.Top="12"
      FontSize="12" />

    <TextBlock
      Canvas.Top="24"
      FontSize="12" Foreground="DarkGray">Value:</TextBlock>

    <TextBlock x:Name="valueTextBlock"
      Canvas.Left="40" Canvas.Top="24"
      FontSize="12" />

  </Canvas>

  <!-- Stops media playback.-->
  <Canvas MouseLeftButtonDown="media_stop"
    Canvas.Left="10" Canvas.Top="265">
    <Rectangle Stroke="Black"
       Height="30" Width="55" RadiusX="5" RadiusY="5">
      <Rectangle.Fill>
        <RadialGradientBrush GradientOrigin="0.75,0.25">
          <GradientStop Color="Orange" Offset="0.0" />
          <GradientStop Color="Red" Offset="1.0" />
        </RadialGradientBrush>
      </Rectangle.Fill>
    </Rectangle>
    <TextBlock Canvas.Left="5" Canvas.Top="5">stop</TextBlock>
  </Canvas>

  <!-- Pauses media playback. -->
  <Canvas MouseLeftButtonDown="media_pause"
     Canvas.Left="70" Canvas.Top="265">
    <Rectangle Stroke="Black"
       Height="30" Width="55" RadiusX="5" RadiusY="5">
      <Rectangle.Fill>
        <RadialGradientBrush GradientOrigin="0.75,0.25">
          <GradientStop Color="Yellow" Offset="0.0" />
          <GradientStop Color="Orange" Offset="1.0" />
        </RadialGradientBrush>
      </Rectangle.Fill>
    </Rectangle>
    <TextBlock Canvas.Left="5" Canvas.Top="5">pause</TextBlock>
  </Canvas>

  <!-- Begins media playback. -->
  <Canvas MouseLeftButtonDown="media_begin"
    Canvas.Left="130" Canvas.Top="265">
    <Rectangle Stroke="Black" RadiusX="5" RadiusY="5"
       Height="30" Width="55">
      <Rectangle.Fill>
        <RadialGradientBrush GradientOrigin="0.75,0.25">
          <GradientStop Color="LimeGreen" Offset="0.0" />
          <GradientStop Color="Green" Offset="1.0" />
        </RadialGradientBrush>
      </Rectangle.Fill>
    </Rectangle>
    <TextBlock Canvas.Left="5" Canvas.Top="5">play</TextBlock>
  </Canvas>

</Canvas>
JavaScript
function media_stop(sender, args) {
    sender.findName("media").stop();
}

function media_pause(sender, args) {
    sender.findName("media").pause();
    alert(sender.findName("media").name);
}

function media_begin(sender, args) {
    sender.findName("media").play();

}

function onMarkerReached(sender, markerEventArgs)
{

  sender.findName("timeTextBlock").Text =
      markerEventArgs.marker.time.seconds.toString();

  sender.findName("typeTextBlock").Text =
       markerEventArgs.marker.type;

  sender.findName("valueTextBlock").Text =
       markerEventArgs.marker.text;

}

For more information, see the Media Overview.

See Also

Media Overview, MediaElement


TimelineMarkerCollection Object

Represents a collection of TimelineMarker objects.

XAML | Cannot be used in XAML
Scripting | See Remarks.

Properties

Count, Name

Methods

Add, Clear, Equals, FindName, GetHost, GetItem, GetValue, Insert, Remove, RemoveAt, SetValue

Remarks

You cannot set the TimelineMarkerCollection in initial XAML, or with the XAML used for CreateFromXAML. Instead, you either embed the timeline markers in the media itself, or add them with script after the media is opened, as described inMedia Overview.

Changing the collection with script does not affect the embedded markers that exist in the media file, it only adjusts the current MediaElement representation of the collection of timeline markers.

See Also

MediaElement, TimelineMarker, Media Overview


TimelineMarkerEventArgs Object

Contains arguments for the MediaElement.MarkerReached event.

XAML | You cannot use this object in XAML.
Scripting | Obtained as arguments for MarkerReached event handlers.

Properties

Marker, Name

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

The MarkerReached event is raised when a MediaElement encounters a TimelineMarker during media playback.

See Also

MarkerReached, Media Overview


TimeSpan Object

Represents a time interval.

XAML
<object property="[days.]hours:minutes:seconds[.fractionalSeconds]" .../>
- or -
<object property="[days.]hours:minutes" .../>
- or -
<object property="days" .../>
Scripting
See Remarks.

Properties

Name, Seconds

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

Creating a Duration, KeyTime, RepeatBehavior, or TimeSpan in XAML or in script is only possible through a type conversion syntax when setting a property such as BeginTime that takes one of these types, with the value specified as a string. The string format for specifying a time in each of these types is identical. Duration can also take the literals "Automatic" and "Forever". RepeatBehavior can take the literal "Forever" and also an iterations syntax "#x".

The main scenario for working with a TimeSpan as an object in script is to get or set its Seconds property in order to query or change an existing animation value.

See Also

Animation Overview


Transform Object (Abstract)

Defines functionality that enables transformations in a 2-D plane. Transformations include rotation (RotateTransform), scale (ScaleTransform), skew (SkewTransform), and translation (TranslateTransform).

XAML | Cannot be used in XAML, see Remarks.
Scripting | Must use derived objects.

Properties

Name

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

For XAML syntaxes that take a Transform, you need to specify a nonabstract derived type of Transform as an object element. For details, see the XAML syntax on the reference pages for MatrixTransform, RotateTransform, ScaleTransform, SkewTransform, TransformGroup, and TranslateTransform.

Use the MatrixTransform class to create custom transformations that are not provided by the RotateTransform, ScaleTransform, SkewTransform, and TranslateTransform classes.

A 2-D x-y plane uses a 3x3 matrix for transformations. You can multiply affine transformation matrices to form linear transformations, such as rotation and skew (shear) that are followed by translation.

An affine transformation matrix has its final column equal to (0, 0, 1); therefore, you only have to specify the members in the first two columns.

You cannot extract the matrix-specific information from the non-matrix transformations. However you can adjust the non-matrix transformations with their specific properties, or replace a transformation with a matrix transformation at runtime.

For more information, see the following Transform objects: RotateTransform, ScaleTransform, SkewTransform, TranslateTransform, MatrixTransform, TransformGroup

See Also

Transform Overview


TransformCollection Object

Represents a collection of Transform objects that can be individually accessed by index.

XAML
<TransformCollection ...>
  oneOrMoreTransforms
</TransformCollection>
Scripting
To create an object using scripting, see CreateFromXAML.

Properties

Count, Name

Methods

Add, Clear, Equals, FindName, GetHost, GetItem, GetValue, Insert, Remove, RemoveAt, SetValue

Remarks

TransformCollection is used by TransformGroup to store Transform child elements.

Transforms in a TransformCollection are applied in the order that they appear in the collection, so the index order of each transform in a TransformCollection is meaningful.

TransformCollection defines no methods or properties beyond the basic Collection methods and properties. Methods such as Add or GetItem will expect or return objects that are of type Transform. Transform itself is an abstract type, so this means that the items in the collection will be one of the following:

  • MatrixTransform
  • ScaleTransform
  • SkewTransform
  • TranslateTransform
  • TransformGroup (nesting TransformGroups is possible)

The XAML syntax for properties that use a TransformCollection is an example of an implicit collection syntax, where you can omit an actual TransformCollection object element, as well as the <TransformGroup.Children> property element. Instead, you generally include one or more Transform derived elements as child elements of a TransformGroup. For more information about XAML implicit collection syntax, see XAML Syntax Overview. (Explicitly including a TransformCollection object element is permissible XAML syntax and might be useful if you intend to name the collection in XAML and manipulate its contents through script later.)

See Also

Transform Overview, RotateTransform, ScaleTransform, SkewTransform, TranslateTransform, MatrixTransform, TransformGroup


TransformGroup Object

Silverlight SDK

TransformGroup

Represents a composite Transform composed of other Transform objects.

XAML
<TransformGroup>
  oneOrMoreTransforms
</TransformGroup>
Scripting
To create an object using scripting, see CreateFromXAML.

Properties

Children, Name

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

Use a TransformGroup when you want to apply multiple Transform objects to a single property.

In a composite transformation, the order of individual transformations is important. For example, if you first rotate, then scale, then translate, you get a different result than if you first translate, then rotate, then scale. One reason order is significant is that transformations such as rotation and scaling are done with respect to the origin of the coordinate system. Scaling an object that is centered at the origin produces a different result than scaling an object that has been moved away from the origin. Similarly, rotating an object that is centered at the origin produces a different result than rotating an object that has been moved away from the origin.

In XAML usages, TransformGroup uses Children as its content property and supports implicit collection usage. Therefore, to declare transforms that will be in a TransformGroup in XAML, you declare one or more transforms as object elements, placing them in order as the child elements of the TransformGroup. Nesting TransformGroups is permitted.

Examples

The following example shows the markup for using a TransformGroup to fill the RenderTransform property.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Width="200" Height="200">
  <TextBlock FontSize="28"
    Canvas.Left="100" Canvas.Top="100"
    Width="50" Height="50"
    Text="Hello">
    <TextBlock.RenderTransform>
      <TransformGroup>
        <RotateTransform Angle="45" />
        <SkewTransform CenterX="0" CenterY="0" AngleX="60"/>
      </TransformGroup>
    </TextBlock.RenderTransform>
  </TextBlock>
</Canvas>

See Also

Transform Overview, RotateTransform, ScaleTransform, SkewTransform, TranslateTransform, MatrixTransform, TransformCollection, Transform


TranslateTransform Object

Translates (moves) an object in the 2-D x-y coordinate system.

XAML | <TranslateTransform .../>
Scripting | To create an object using scripting, see CreateFromXAML.

Properties

Name, X, Y

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

The local 0,0 for an object can be offset on a Canvas using Canvas.Left and Canvas.Top, but this does not count as a transform; the object retains its own local 0,0 in this case for transform purposes. For details on this concept, see Object Layout in Silverlight.

Multiple transforms can be applied with a TransformGroup. Custom transforms can be created with a MatrixTransform.

TranslateTransform defines an axis-aligned translation along the x- and y- axes. The following illustration shows the transformation matrix for a translation by offset (dx, dy).

Transforms can alter the display of text in your application to create a decorative effect. The following illustration shows text translated, or moved, along the x- and y-axis.

TextBlock using a TranslateTransform

Examples

The following JavaScript example uses a TranslateTransform to offset text. In this example, a slightly offset copy of text below the primary text creates a shadow effect.

XAML
<!-- Offset the text using a TranslateTransform. -->
<TextBlock
  FontFamily="Verdana"
  FontSize="32"
  FontWeight="Bold"
  Foreground="Black"
  Text="Translated Text">
  <TextBlock.RenderTransform>
    <TranslateTransform X="2" Y="2" />
  </TextBlock.RenderTransform>
</TextBlock>

<TextBlock
  FontFamily="Verdana"
  FontSize="32"
  FontWeight="Bold"
  Foreground="Coral"
  Text="Translated Text"/>

See Also

Transform Overview, Transform


TriggerActionCollection Object

Represents a collection of trigger actions that can be individually accessed by index.

XAML
<TriggerActionCollection ...>
  oneOrMoreBeginStoryboards
</TriggerActionCollection>
Scripting
To create an object using scripting, see CreateFromXAML.

Properties

Count, Name

Methods

Add, Clear, Equals, FindName, GetHost, GetItem, GetValue, Insert, Remove, RemoveAt, SetValue

Remarks

Despite the name of this collection, the items contained in the collection are not "TriggerAction" objects. Instead, they are BeginStoryboard objects.

TriggerActionCollection defines no methods or properties beyond the basic Collection methods and properties. Methods such as Add or GetItem will expect or return objects that are of type BeginStoryboard.

The XAML syntax for properties that use a TriggerActionCollection is an example of an implicit collection syntax, where you can omit an actual TriggerActionCollection object element, as well as the <EventTrigger.Actions> property element. Instead, you generally include one or more BeginStoryboard elements as child elements of an EventTrigger. For more information about XAML implicit collection syntax, see XAML Syntax Overview. (Explicitly including a TriggerActionCollection object element is permissible XAML syntax, and might be useful if you intend to name the collection in XAML and manipulate its contents through script later.)

See Also

BeginStoryboard, Interactive Animations Overview


TriggerCollection Object

Represents a collection of EventTrigger objects.

XAML
<TriggerCollection ...>
  oneOrMoreEventTriggers
</TriggerCollection>
Scripting
To create an object using scripting, see CreateFromXAML.

Properties

Count, Name

Methods

Add, Clear, Equals, FindName, GetHost, GetItem, GetValue, Insert, Remove, RemoveAt, SetValue

Remarks

TriggerCollection defines no methods or properties beyond the basic Collection methods and properties. Methods such as Add or GetItem will expect or return objects that are of type EventTrigger.

The XAML syntax for properties that use a TriggerCollection is an example of an implicit collection syntax, where you can omit an actual TriggerCollection object element. Instead, you generally include one or more EventTrigger elements as child elements of an <object.Triggers> property element tag. For more information about XAML implicit collection syntax, see XAML Syntax Overview. (Explicitly including a TriggerCollection object element is permissible XAML syntax, and might be useful if you intend to name the collection in XAML and manipulate its contents through script later.)

See Also

EventTrigger


UIElement Object (Abstract)

UIElement is the base class for rendered objects. This class is abstract.

XAML | Cannot be used in XAML.
Scripting | Must use derived objects.

Properties

Canvas.Left, Canvas.Top, Canvas.ZIndex, Clip, Cursor, Height, IsHitTestVisible, Name, Opacity, OpacityMask, RenderTransform, RenderTransformOrigin, Resources, Tag, Triggers, Visibility, Width

Methods

AddEventListener, CaptureMouse, Equals, FindName, GetHost, GetParent, GetValue, ReleaseMouseCapture, RemoveEventListener, SetValue

Events

GotFocus, KeyDown, KeyUp, Loaded, LostFocus, MouseEnter, MouseLeave, MouseLeftButtonDown, MouseLeftButtonUp, MouseMove

Remarks

For more information, see the following UIElement objects: Canvas, Ellipse, Glyphs, Image, InkPresenter, Line, MediaElement, Path, Polygon, Polyline, Rectangle, Shape, TextBlock.

UIElement is abstract, and is not returned as that object type by any APIs in Silverlight 1.0. Instead, you always obtain an instance of the more specific derived practical class. You also cannot create a true <UIElement> object element in XAML. For this reason, UIElement is not listed in the "Applies To" lists for various UIElement APIs, even though it is the defining class.

See Also

Silverlight Object Model


VideoBrush Object

Paints an area with video content.

XAML | <VideoBrush .../>
Scripting | To create an object using scripting, see the CreateFromXAML method.

Properties

AlignmentX, AlignmentY, Name, Opacity, RelativeTransform, SourceName, Stretch, Transform

Methods

Equals, FindName, GetHost, GetValue, SetValue

Remarks

A detailed walkthrough of how to use a VideoBrush is documented in the Silverlight VideoBrush Overview.

A VideoBrush is a type of Brush object similar to a LinearGradientBrush or an ImageBrush. However, instead of painting an area with a solid color, a gradient, or an image, it paints an area with video content. This video content is provided by a MediaElement. Just like the other brush types, you can use a VideoBrush to paint the Fill of a shape such as a Rectangle or the geometry contents of a Path, the Background of a Canvas, or the Foreground of a TextBlock or Run.

To use a VideoBrush, you create a MediaElement, apply the VideoBrush to the object that you want to paint, and set the VideoBrush object's SourceName property to the Name of the MediaElement that you created.

Examples

The following example uses a VideoBrush to paint the Foreground of a TextBlock.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <MediaElement
      x:Name="butterflyMediaElement"
      Source="sampleMedia/Butterfly.wmv" IsMuted="True"
      Opacity="0.0" IsHitTestVisible="False" />

    <TextBlock Canvas.Left="5" Canvas.Top="30"
      FontFamily="Verdana" FontSize="120"
      FontWeight="Bold" TextWrapping="Wrap"
      Text="Video">

        <!-- Paint the text with video. -->
        <TextBlock.Foreground>
          <VideoBrush SourceName="butterflyMediaElement" Stretch="UniformToFill" />
        </TextBlock.Foreground>
    </TextBlock>

</Canvas>

For more information, see the VideoBrush Overview.

See Also

VideoBrush Overview, Brush Overview, Silverlight Objects


VisualCollection Object

Represents a collection of UIElement objects.

XAML | Cannot be used in XAML
Scripting | See Remarks.

Properties

Count, Name

Methods

Add, Clear, Equals, FindName, GetHost, GetItem, GetValue, Insert, Remove, RemoveAt, SetValue

Remarks

This is the collection that underlies Canvas.Children. However, neither Canvas.Children nor VisualCollection can be used in XAML syntax. A VisualCollection is implicitly created by XAML parsing and are available if you examine the runtime object tree through scripting, but explicit uses in XAML are disallowed.

The general scripting usage is to make all scripting calls that adjust the VisualCollection inline with getting the Canvas.Children property, for instance myCanvas.Children.Add(content). However, you can also retain a variable for a VisualCollection if you wish; this will retain a reference that will remain synchronized with the actual collection and can be used to add to, remove from or otherwise examine the collection of child elements (it is not a one-time copy).

See Also

Canvas


Silverlight Methods

This section contains a list of the methods exposed by the Silverlight Object Model.

Methods

Abort

Add

AddEventListener

AddStylusPoints

Begin

CaptureMouse

Clear

CreateFromXAML

CreateFromXAMLDownloader

CreateObject

FindName (Silverlight Plug-in)

FindName (UIElement)

GetBounds (Stroke)

GetBounds (StrokeCollection)

GetHost

GetItem

GetItemByName

GetParent

GetPosition

GetResponseText

GetStylusInfo

GetStylusPoints

GetValue

HitTest (Stroke)

HitTest (StrokeCollection)

Insert

IsVersionSupported

Open

Pause (MediaElement)

Pause (Storyboard)

Play

ReleaseMouseCapture

Remove

RemoveAt

RemoveEventListener

Resume

Seek

Send

SetFontSource

SetSource

SetValue

Stop (MediaElement)

Stop (Storyboard)

See Also

Silverlight Reference, Silverlight Conceptual Topics


Abort Method

Cancels the downloader request and resets properties to their initial state.

XAML | You cannot use methods in XAML.
Scripting | downloaderObject.Abort()

Remarks

The Abort method cancels the downloader request that has been executed by using the Send method of the Downloader object. In addition, the Abort method resets the following Downloader properties to their initial state:

Property name | Initial state
DownloadProgress | 0
Status | 0
StatusText | Empty string

Examples

The following JavaScript example shows how to invoke the Abort method:

JavaScript
// Cancel download on mouse click.
function onLeftMouseButtonUp(sender, eventArgs)
{
    // Cancel Downloader activity and restore state.
    downloader.abort();
}

Applies To

Downloader

See Also

Open, Send, Using the Downloader Object


Add Method

Adds an object to the end of the collection.

XAML | You cannot use methods in XAML.
Scripting | retval = object.Add(value)

Parameters

value

object

The object to add to the collection.

Return Value

integer

Returns the zero-based index of the inserted object in the collection if successful; otherwise, returns null.

Examples

You can add XAML content to objects that support child objects, such as the Canvas object. The following JavaScript example shows to create a TextBlock and add it to the root Canvas object by using the Add method on the object's collection of children. Note that the Opacity property is 0, so the fragment will not be initially visible. Using the Opacity property to control an object's visibility avoids having to modify the Silverlight object hierarchy.

JavaScript
var textBlock;

function onLoaded(sender, eventArgs)
{
    // Retrieve the id of the plug-in.
    var plugin = sender.getHost();

    // Define and create a XAML fragment.
    var xamlFragment = '<TextBlock Canvas.Top="200" Opacity=".5" Text="Click for more info" />';
    textBlock = plugin.content.createFromXaml(xamlFragment);

    // Add the TextBlock to the root Canvas object.
    sender.children.add(textBlock);
}

// Toggle the Opacity property for the TextBlock.
function onToggle()
{
    if (textBlock.opacity)
    {
        textBlock.opacity = 0;
    }
    else
    {
        textBlock.opacity = 1;
    }
}

Applies To

ColorKeyFrameCollection, DoubleKeyFrameCollection, GradientStopCollection, Inlines, PathFigureCollection, PathSegmentCollection, PointKeyFrameCollection, StrokeCollection, StylusPointCollection, TriggerActionCollection, TriggerCollection, VisualCollection

See Also

Insert, Referencing and Modifying Silverlight Objects


AddEventListener Method

Registers an event listener on the event target object.

XAML | You cannot use methods in XAML.
Scripting | [token = ]object.AddEventListener(eventName, functionReference)

Parameters

eventName | string The name of the event, such as "KeyDown". This is a true string, and the value must be quoted. An exception is thrown if eventName is invalid (not a known event name).
functionReference | object A reference to the event handler function. Specifying the name of an existing function (without quotes) will create a delegate that fills this object reference. -or- The name of an existing function, with quotes. See Remarks.

Return Value

integer

A token that is returned from the function, which you can optionally retain as a variable. If you intend to call RemoveEventListener to remove the handler, you will need this token.

Remarks

The AddEventListener method registers an event listener on a UIElement-derived object, such as a Canvas or Image. The event handler function that is defined as the event listener receives a notification when the specified eventType occurs.

The alternative syntax that specifies the event handler as a quoted string was originally for Safari browsers, which did not have the ability in the browser object model to retain handler references. You can still use the quoted string syntax as an option; the quoted string syntax effectively parallels the mechanism that is used to add the handlers that are declared as XAML attributes. When you use the quoted string syntax, you are not obligated to use the token in calls to RemoveEventListener. Instead, you can also specify the second parameter of RemoveEventListener as a quoted string of the handler name. Instead of the retained token, you can specify the second parameter of RemoveEventListener as a quoted string of the handler name. To explicitly remove handlers that were added through XAML, you can either specify the handler name as a string, or use a token value of 0 (handlers from XAML always have that token value).

Note The Silverlight implementation of AddEventListener is different from the HTML Document Object Model (DOM) version of the same name. The DOM version provides an additional third parameter that enables event capture.

Another important difference from the HTML DOM is that the the Silverlight implementation of AddEventListener will register multiple identical event listeners if provided. The event listener is called as many times as it was added. If there are multiples, a RemoveEventListener call removes only one of the instances, not all of them.

The AddEventListener method returns a token. Often you do not need this token, so you can call this method without storing the return value. However, if you plan to remove the event handler at some later point in your code, by calling RemoveEventListener, and you have added multiple listeners to the same event using scripting, you should retain this token.

Use the RemoveEventListener method to remove a functionReference that has been added using the AddEventListener method.

The token is just an integer value to track the order in which handlers were added for each object-event combination. Therefore, if you are certain that your code has added only one handler, you can pass 0 as the token value rather than storing it as a token.

Examples

The following JavaScript example shows how to define a Silverlight keyboard event by using the AddEventListener method:

JavaScript
function onLoaded(sender, eventArgs)
{
    // Set the root Canvas object to a KeyDown event handler function.
    var token = sender.addEventListener("keyDown", onKeyDown);
}

function onKeyDown(sender, keyEventArgs)
{
    // Determine whether the keystroke combination CTRL+V was detected.
    if ((keyEventArgs.key == 51) && (keyEventArgs.ctrl == true))
    {
        // Retrieve a reference to the plug-in.
        var slPlugin = sender.getHost();

        // Display the current version of the plug-in.
        alert("Silverlight version: " + slPlugin.isVersionSupported("1.0"));
    }
}

The following Javascript example shows how to remove a Silverlight event handler function for the KeyDown event. The token variable in the previous example is used here to fill the second parameter of the RemoveEventListener method.

JavaScript
function onCleanUp()
{
    // Remove the KeyDown event handler function from the root Canvas object.
    sender.removeEventListener("keyDown", token);
}

Applies To

Canvas, Ellipse, Glyphs, Image, InkPresenter, Line, MediaElement, Path, Polygon, Polyline, Rectangle, TextBlock

See Also

RemoveEventListener


AddStylusPoints Method

Adds a collection of StylusPoint objects to the collection.

XAML | You cannot use methods in XAML.
Scripting | retval = object.AddStylusPoints(stylusPoints)

Parameters

stylusPoints

StylusPointCollection

The collection of StylusPoint objects to add to the collection.

Return Value

integer

The 0 based integer value which is the index of the last element in the StylusPointCollection, or 1 if the collection is empty.

Remarks

A StylusPointCollection can belong to more than one Stroke object.

Applies To

StrokeCollection

See Also

Ink Support In Microsoft Silverlight


Begin Method (Storyboard)

Initiates the set of animations associated with this Storyboard.

XAML | You cannot use methods in XAML.
Scripting | object.Begin()

Remarks

This method is generally used to initiate storyboards that are not associated with a trigger, or at least that are intended to be used again after an initial triggered run. See Interactive Animations Overview.

If your Storyboard has an animation type that does not match the targeted property type, this will be indicated as a method failure of the call to Begin. This can be differentiated from a nonresolving Storyboard.TargetName because a nonresolving name will raise a SetValue error on the Storyboard.TargetName property.

Applies To

Storyboard

See Also

Seek, Stop, Animation Overview, Interactive Animations Overview


CaptureMouse Method

Enables mouse capture for the object.

XAML | You cannot use methods in XAML.
Scripting | retval = object.CaptureMouse()

Return Value

Boolean

Returns true if the object has enabled mouse capture; otherwise, returns false.

Remarks

When an object has captured the mouse, it receives mouse input whether or not the cursor is within its borders. The mouse is typically only captured during drag operations. To disable mouse capture for an object, use the ReleaseMouseCapture method. For more information on capturing the mouse, see Implementing Drag and Drop.

The mouse can be captured when all of the following conditions are true:

  • The mouse is over the Silverlight plug-in content area.
  • No other Silverlight object has captured the mouse.
  • No other non-Silverlight object has captured the mouse.
  • The left mouse button must be in a depressed state.

Only a UIElement type can capture the mouse (see the Applies To section in this topic for a list). Notable cases of other objects that have a visual display but cannot capture the mouse are Run (only the parent TextBlock can capture) and geometries (only the parent Path can capture).

Examples

To understand how mouse capture works, consider the following XAML example in which two Rectangle objects share the same MouseMove event handler function:

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Height="180" Width="300"
  Background="PowderBlue">

  <Rectangle
    x:Name="Green"
    MouseMove="onMouseMove"
    MouseLeftButtonDown="onLeftButtonDown"
    MouseLeftButtonUp="onLeftButtonUp"
    Width="100" Height="100"
    Fill="Green" />

  <!-- The MouseMove event handler function is shared with the first rectangle -->
  <Rectangle
    x:Name="Red"
    MouseMove="onMouseMove"
    Canvas.Left="120"
    Width="100" Height="100"
    Fill="Maroon" />

  <TextBlock
    x:Name="statusTextBlock"
    FontSize="18"
    Canvas.Top="120" />

</Canvas>

The corresponding event handler functions for the previous XAML content example are defined in the following JavaScript example. Notice that the green Rectangle object captures all Silverlight application mouse input from the time the left mouse button is depressed until the left mouse button is released.

JavaScript
// Display the current mouse position for the Rectangle object.
function onMouseMove(sender, mouseEventArgs)
{
    var msg = "x:y = " + mouseEventArgs.getPosition(null).x + ", " + mouseEventArgs.getPosition(null).y;
    sender.findName("statusTextBlock").Text = sender.Name + ": " + msg;
}

// Enable mouse capture when the mouse is depressed over the green Rectangle object.
function onLeftButtonDown(greenRect, mouseEventArgs)
{
    greenRect.captureMouse();
}

// Disable mouse capture when the mouse is released over the green Rectangle object.
function onLeftButtonUp(greenRect, mouseEventArgs)
{
    greenRect.releaseMouseCapture();
}

When the Silverlight is displayed and the mouse moves over the rectangles, each rectangle displays its mouse position by using the shared onMouseMove event handler function. For example, when the mouse is over the red rectangle, the status displays "Red: x:y = 171, 55".

Each rectangle receives mouse input

When the mouse is depressed over the green rectangle and held down, moving the mouse over any part of the Silverlight application results in the green rectangle receiving all mouse input events. For example, when the green rectangle enables mouse capture and the mouse moves over the red rectangle, "Green: x:y = 140, 76". This is because all events are being redirected to the green rectangle even though the mouse is outside the green rectangle's bounding area.

Applies To

Canvas, Ellipse, Glyphs, Image, InkPresenter, Line, MediaElement, Path, Polygon, Polyline, Rectangle, TextBlock

See Also

Silverlight Events, Silverlight Mouse Support, MouseLeftButtonDown, MouseLeftButtonUp, MouseMove, ReleaseMouseCapture


Clear Method

Removes all objects from the collection.

XAML | You cannot use methods in XAML.
Scripting | retval = object.Clear()

Return Value

Boolean

true if all the objects were removed from the collection; otherwise, false.

Examples

You can remove all objects in a collection by using the Clear method, which is equivalent to using the RemoveAt method for each item in the collection. The following JavaScript example shows to removes all items from a collection using the Clear method.

JavaScript
// Remove all child objects from the parent collection.
myCanvas.children.clear();

The Remove method allows you to remove a specific child object from the parent's collection by referencing the object's x:Name attribute value.

The following JavaScript example shows to remove a TextBlock from its parent Canvas object by using the Remove method on the object's collection of children.

JavaScript
function removeCaption(rootCanvas)
{
    // Retrieve the TextBlock object.
    var captionTextBlock = rootCanvas.findName("myCaption");

    if (captionTextBlock != null)
    {
        rootCanvas.children.remove(captionTextBlock);
    }
}

Applies To

ColorKeyFrameCollection, DoubleKeyFrameCollection, GradientStopCollection, Inlines, PathFigureCollection, PathSegmentCollection, PointKeyFrameCollection, StrokeCollection, StylusPointCollection, TriggerActionCollection, TriggerCollection, VisualCollection

See Also

Referencing and Modifying Silverlight Objects


CreateFromXaml Method

Creates XAML content dynamically.

XAML | You cannot use methods in XAML.
Scripting | retval = silverlightObject.content.CreateFromXaml(xamlContent[, createNameScope])

Parameters

xamlContent | string The XAML content to add to the existing Silverlight object hierarchy.
createNameScope | Boolean Determines whether to create x:Name references in XAML content that do not conflict with other named elements. The createNameScope parameter is optional, and its value defaults to false if not specified.

Return Value

object

An object reference if the XAML content was successfully created; otherwise, returns null.

Remarks

This method is available on the content sub-object of a Silverlight plug-in instance.

The CreateFromXaml method creates objects from XAML content dynamically, which you can then add to the existing Silverlight object hierarchy. You can create a single Silverlight object, such as a TextBlock, or an entire tree of Silverlight objects. For more information, see Using the CreateFromXaml Method.

The string you specify for xamlContent must specify well formed XML (notably, it must have a single root element). CreateFromXaml will fail and raise an error if the provided XML string is not well formed.

Note XAML content created by using the CreateFromXaml method is not rendered until it is added to an object using the Add method.

Note In order to guard your Silverlight application against security attacks, it is strongly recommended that you do not pass in untrusted XAML to the createFromXAML method. For example, untrusted XAML could contain a mock-up interface that mirrors a legitimate site, leading to a spoofing type security threat. Additionally, XAML contains references to script event handlers. Adding untrusted XAML to the live tree could result in unintended execution of script. Always validate that XAML passed in to createFrom XAML is from a source that your Silverlight application considers trusted.

Examples

The following JavaScript example shows to add a TextBlock to an existing Canvas object:

JavaScript
// MouseLeftButtonUp event handler for the root Canvas object.
function onMouseLeftButtonUp(sender, eventArgs)
{
    // Retrieve a reference to the plug-in.
    var plugin = sender.getHost();

    // Define a XAML fragment and create it.
    var xamlFragment = '<TextBlock Canvas.Top="200" Text="Click for more info..." />';
    textBlock = plugin.content.createFromXaml(xamlFragment);

    // Add the XAML fragment as a child of the root Canvas object.
    sender.children.add(textBlock);
}

If you want to use the x:Name attribute value as part of your XAML fragment, you will need to provide the XML namespace reference as part of the XAML content. For example, in order for the previous XAML fragment example to use the x:Name attribute value, it would need to be rewritten as:

JavaScript
    // Define a XAML fragment and create it.
    var xamlFragment = '<TextBlock xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" ';
       xamlFragment += 'x:Name="myCanvas" Canvas.Top="200" Text="Click for more info" />';

    textBlock = plugin.content.createFromXaml(xamlFragment);

If you use an x:Name attribute value that is already identifies an object in the Silverlight object hierarchy and createNameScope is false, an error is generated when you invoke the Add method for the XAML fragment. Set createNameScope to true, if you want to create multiple instances of elements without naming conflicts.

Applies To

Silverlight Plug-in

See Also

Using the CreateFromXaml Method, Silverlight XAML Syntax


CreateFromXamlDownloader Method

Creates XAML content dynamically using downloader content.

XAML | You cannot use methods in XAML.
Scripting | retval = silverlightObject.content.CreateFromXamlDownloader(downloader, part)

Parameters

downloader | Downloader The object containing the downloaded content.
part | string The name of the specific part of the downloaded content package. When the downloaded content package is a Zip file, part refers to the contents of a filename within downloader. If the downloaded content does not represent packaged content, set part to an empty string.

Return Value

object

An object reference if the XAML content was successfully created; otherwise, returns null.

Remarks

This method is available on the content sub-object of a Silverlight plug-in instance.

The CreateFromXamlDownloader method creates objects from XAML content dynamically by using the downloaded content in the Downloader object. If successful, the CreateFromXamlDownloader method returns an object reference, which you can then add to the existing Silverlight object hierarchy. You can create a single Silverlight object, such as a TextBlock, or an entire tree of Silverlight objects.

Note The CreateFromXamlDownloader method is more efficient that using CreateFromXaml with downloaded content, since it avoids have to copy downloaded content from the GetResponseText method return value to a temporary buffer and then back again for use by the XAML parser.

XAML content created by using the CreateFromXamlDownloader method is not rendered until it is added to an object using the Add method. The following diagram illustrates the relationship between the Silverlight object hierarachy and the downloaded XAML content before and after the content is added to the object hierarchy:

Examples

The following JavaScript example shows to add XAML content to an existing Canvas object using the CreateFromXamlDownloader method. Since the downloaded content does not represent packaged content, the part parameter for CreateFromXamlDownloader must be set to an empty string:

JavaScript
// Event handler for the Completed event.
function onCompleted(sender, eventArgs)
{
    // Retrieve a reference to the plug-in.
    var slPlugin = sender.getHost();

    // Retrieve the XAML fragment and create an object reference.
    // In this case, since the downloaded content represents a single file, OK_button.xaml,
    // the part parameter is set to an empty string.
    var xamlFragment = slPlugin.content.createFromXamlDownloader(sender, "");

    // Add the XAML object as a child of the root Canvas object.
    var root = sender.findName("rootCanvas");
    root.children.add(xamlFragment);
}

You can also use the CreateFromXamlDownloader method to retrieve a specific part within the downloaded content package. When the downloaded content package is a Zip file, the CreateFromXamlDownloader method retrieves the contents of a filename within the Zip file.

The following JavaScript example shows how to use the CreateFromXamlDownloader method, using the part parameter to reference as specified part within the downloaded content:

JavaScript
// Event handler for the Completed event.
function onCompleted(sender, eventArgs)
{
    // Retrieve a reference to the plug-in.
    var slPlugin = sender.getHost();

    // Retrieve the specified XAML file from the packaged downloader content,
    // and create an object reference.
    var xamlFragment = slPlugin.content.createFromXamlDownloader(sender, "OK_button.xaml");

    // Add the XAML object as a child of the root Canvas object.
    var root = sender.findName("rootCanvas");
    root.children.add(xamlFragment);
}

Applies To

Silverlight Plug-in

See Also

Using a Downloader Object, Silverlight XAML Syntax


CreateObject Method

Creates a specified object and returns a reference to it.

XAML | You cannot use methods in XAML.
Scripting | retval = silverlightObject.CreateObject(objectType)

Parameters

objectType

string

The type of object to create.

Return Value

object

An object reference if the object was successfully created; otherwise, null.

Remarks

The Downloader object is the only object that can by specified by name as the objectType parameter for the CreateObject method. If you specify an invalid objectType parameter, the CreateObject method throws an exception.

Examples

The following JavaScript example shows how to invoke the CreateObject method and create a Downloader:

JavaScript
// Event handler for initializing and executing a download request.
function onMouseLeftButtonUp(sender, eventArgs)
{
    // Retrieve a reference to the plug-in.
    var slPlugin = sender.getHost();

    // Create a Downloader object.
    var downloader = slPlugin.createObject("downloader");

    // Add DownloadProgressChanged and Completed events.
    downloader.addEventListener("downloadProgressChanged", onDownloadProgressChanged);
    downloader.addEventListener("completed", onCompleted);

    // Initialize the Downloader request.
    // NOTE: downloader APIs disallow file:\\ scheme
    // you must run this sample over localhost: or off a server or the following call will fail

    downloader.open("GET", "promo.png");

    // Execute the Downloader request.
    downloader.send();
}

Applies To

Silverlight Plug-in

See Also

Downloader, CreateFromXaml


Equals Method

Checks for equality of an object to the current object.

XAML | You cannot use methods in XAML
Scripting | retval = object.Equals(objectToCompare)

Parameters

objectToCompare

object

The object to compare to the calling object.

Return Value

Boolean

true if the objects are the same object; otherwise, false.

Remarks

Equality is determined by reference equality. This applies even if you compare two instances such as Point that each have identical string initialization for their internal values.

Some of the object types listed in Applies To are abstract types, therefore this method cannot be truly called on that type in JavaScript because there is no way to obtain instances of abstract types in JavaScript programming.

Applies To

Accessibility, ArcSegment, BeginStoryboard, BezierSegment, Boolean, Brush, Canvas, Color, ColorAnimation, ColorAnimationUsingKeyFrames, ColorKeyFrame, ColorKeyFrameCollection, DependencyObject, DiscreteColorKeyFrame, DiscreteDoubleKeyFrame, DiscretePointKeyFrame, DoubleAnimation, DoubleAnimationUsingKeyFrames, DoubleKeyFrame, DoubleKeyFrameCollection, Downloader, DrawingAttributes, Duration, Ellipse, EllipseGeometry, EventTrigger, Geometry, GeometryCollection, GeometryGroup, Glyphs, GradientStop, GradientStopCollection, Image, ImageBrush, InkPresenter, Inlines, KeySpline, KeyTime, Line, LinearColorKeyFrame, LinearDoubleKeyFrame, LinearGradientBrush, LinearPointKeyFrame, LineBreak, LineGeometry, LineSegment, Matrix, MatrixTransform, MediaAttribute, MediaAttributeCollection, MediaElement, Path, PathFigure, PathFigureCollection, PathGeometry, PathSegment, PathSegmentCollection, Point, PointAnimation, PointAnimationUsingKeyFrames, PointKeyFrame, PointKeyFrameCollection, PolyBezierSegment, Polygon, Polyline, PolyLineSegment, PolyQuadraticBezierSegment, QuadraticBezierSegment, RadialGradientBrush, Rect, Rectangle, RectangleGeometry, RepeatBehavior, ResourceDictionary, RotateTransform, Run, RuntimeErrorEventArgs, ScaleTransform, SkewTransform, SolidColorBrush, SplineColorKeyFrame, SplineDoubleKeyFrame, SplinePointKeyFrame, Storyboard, Stretch, Stroke, StrokeCollection, StylusInfo, StylusPoint, StylusPointCollection, TextBlock, Timeline, TimelineCollection, TimelineMarker, TimelineMarkerCollection, TimelineMarkerEventArgs, TimeSpan, TransformCollection, TransformGroup, TranslateTransform, TriggerActionCollection, TriggerCollection, VisualCollection, VideoBrush

See Also

DependencyObject, Silverlight Object Models


FindName Method

Silverlight SDK

FindName Method (Silverlight Plug-in)

Gets any object in the Silverlight object hierarchy by referencing the object's x:Name or Name attribute value.

XAML | You cannot use methods in XAML.
Scripting | retval = silverlightObject.content.FindName(objectName)

Parameters

objectName

string

The name of the object to get.

Return Value

object

A reference to the specified object if the object was successfully found; otherwise, returns null.

Remarks

This method is available on the content sub-object of a Silverlight plug-in instance.

You can find any object in the Silverlight object hierarchy by using the FindName method of the Silverlight plug-in and referencing the object's x:Name or Name attribute value. This object you are searching for can be any named object in the Silverlight object hierarchy. If the FindName method is successful, a reference to the object is returned; otherwise, null is returned.

For more information on accessing Silverlight controls, see Referencing and Modifying Silverlight Objects.

Examples

The following JavaScript example shows how use the FindName method:

JavaScript
function onLoaded(sender, eventArgs)
{
    // Retrieve a reference to the plug-in.
    var slPlugin = sender.getHost();

    // Retrieve a reference to the specified object.
    var object = slPlugin.content.findName("myTextBlock");

    // If a valid object reference, display an alert dialog box.
    if (object != null)
    {
        alert(object.toString() + " found");
    }
}

Applies To

Silverlight Plug-in

See Also

Using a Silverlight Plug-in, Referencing and Modifying Silverlight Objects


FindName Method

Silverlight SDK

FindName Method (DependencyObject)

Gets any object in the Silverlight object hierarchy by referencing the object's x:Name attribute value.

XAML | You cannot use methods in XAML.
Scripting | retval = object.FindName(name)

Parameters

name

string

The name of the object to get.

Return Value

object

A reference to the specified object if the object was successfully found; otherwise, returns null.

Remarks

You can find any object in the Silverlight object hierarchy by using the FindName method and referencing the object's x:Name or Name attribute value. This means that the object you are searching for does not have to be a direct descendant of the object that invokes the findName method. If the method is successful, a reference to the object is returned; otherwise, null is returned.

Some of the object types listed in Applies To are abstract types, therefore this method cannot be truly called on that type in JavaScript because there is no way to obtain instances of abstract types in JavaScript programming.

Examples

The following JavaScript example shows how a leaf node of a Silverlight object hierarchy can access a root node.

JavaScript
// Loaded event handler for the root Canvas object.
function onLoaded(sender, eventArgs)
{
    // Retrieve the object corresponding to the x:Name attribute value.
    var canvas = sender.findName("rootCanvas");

    // Determine whether the object was found.
    if (canvas != null)
    {
        alert(canvas.toString());
    }
    else
    {
        alert("Object not found");
    }
}

You can set or get a property directly on the returned value of the FindName method. The following JavaScript example shows how to combine the FindName and SetValue operations as a combined operation:

JavaScript
    // Set the property on the retrieved object.
    sender.findName("statusTextBlock").text = "Press OK to continue.";

Applies To

Accessibility, ArcSegment, BeginStoryboard, BezierSegment, Boolean, Brush, Canvas, Color, ColorAnimation, ColorAnimationUsingKeyFrames, ColorKeyFrame, ColorKeyFrameCollection, DependencyObject, DiscreteColorKeyFrame, DiscreteDoubleKeyFrame, DiscretePointKeyFrame, DoubleAnimation, DoubleAnimationUsingKeyFrames, DoubleKeyFrame, DoubleKeyFrameCollection, Downloader, DrawingAttributes, Duration, Ellipse, EllipseGeometry, EventTrigger, Geometry, GeometryCollection, GeometryGroup, Glyphs, GradientStop, GradientStopCollection, Image, ImageBrush, InkPresenter, Inlines, KeySpline, KeyTime, Line, LinearColorKeyFrame, LinearDoubleKeyFrame, LinearGradientBrush, LinearPointKeyFrame, LineBreak, LineGeometry, LineSegment, Matrix, MatrixTransform, MediaAttribute, MediaAttributeCollection, MediaElement, Path, PathFigure, PathFigureCollection, PathGeometry, PathSegment, PathSegmentCollection, Point, PointAnimation, PointAnimationUsingKeyFrames, PointKeyFrame, PointKeyFrameCollection, PolyBezierSegment, Polygon, Polyline, PolyLineSegment, PolyQuadraticBezierSegment, QuadraticBezierSegment, RadialGradientBrush, Rect, Rectangle, RectangleGeometry, RepeatBehavior, ResourceDictionary, RotateTransform, Run, RuntimeErrorEventArgs, ScaleTransform, SkewTransform, SolidColorBrush, SplineColorKeyFrame, SplineDoubleKeyFrame, SplinePointKeyFrame, Storyboard, Stretch, Stroke, StrokeCollection, StylusInfo, StylusPoint, StylusPointCollection, TextBlock, Timeline, TimelineCollection, TimelineMarker, TimelineMarkerCollection, TimelineMarkerEventArgs, TimeSpan, TransformCollection, TransformGroup, TranslateTransform, TriggerActionCollection, TriggerCollection, VisualCollection, VideoBrush

See Also

Referencing and Modifying Objects, Name


GetBounds Method (Stroke)

Returns a Rect that is the bounding box of the Stroke.

XAML | You cannot use methods in XAML.
Scripting | retval = object.GetBounds()

Return Value

Rect

The bounding box of the Stroke.

Examples

JavaScript
  var newRect = currentStroke.GetBounds();

Applies To

Stroke

See Also

Ink Support In Microsoft Silverlight


GetBounds Method (StrokeCollection)

Returns a Rect which is the bounding box of the strokes in the collection.

XAML | You cannot use methods in XAML.
Scripting | retval = object.GetBounds()

Return Value

Rect

The bounding box of the strokes in the StrokeCollection.

Examples

JavaScript
  var newRect = inkPresenter.Strokes.GetBounds();

For the strokes shown in the example making up "Ink!", the Rect returned by calling GetBounds() would be the red box.

Applies To

StrokeCollection

See Also


GetHost Method

Gets a reference to the Silverlight plug-in that contains the current element.

XAML | You cannot use methods in XAML.
Scripting | retval = object.GetHost()

Return Value

object

A reference to the Silverlight plug-in instance that contains the specified object.

Remarks

The GetHost method can be used by any object in the Silverlight object model (any DependencyObject) to retrieve the Silverlight plug-in instance that contains the object. This method is especially useful for retrieving the Silverlight plug-in in an event handling function, in which the sender parameter is generally a DependencyObject.

Some of the object types listed in Applies To are abstract types, therefore this method cannot be truly called on that type in JavaScript because there is no way to obtain instances of abstract types in JavaScript programming.

Examples

The following JavaScript example shows how to retrieve a Silverlight plug-in object in a KeyUp event handler function:

JavaScript
function onKeyUp(sender, keyEventArgs)
{
    // Determine whether the keystroke combination CTRL+V was detected.
    if ((keyEventArgs.key == 51) && (keyEventArgs.ctrl == true))
    {
        // Retrieve a reference to the plug-in.
        var plugin = sender.getHost();

        // Determine whether the 1.0 version of Silverlight is available.
        alert("Silverlight 1.0: " + plugin.isVersionSupported("1.0"));
    }
}

In cases where you need access to a plug-in's HTML Document Object Model (DOM) values, such as width and height, you can retrieve a reference to the HTML DOM representation of the Silverlight plug-in by using its ID value in the DOM for the HTML page. The following JavaScript example shows how to retrieve a reference to the Silverlight plug-in instance by using the document.getElementById method:

JavaScript
var plugin_1 = document.getElementById("SLPlugin_1");

Applies To

Accessibility, ArcSegment, BeginStoryboard, BezierSegment, Boolean, Brush, Canvas, Color, ColorAnimation, ColorAnimationUsingKeyFrames, ColorKeyFrame, ColorKeyFrameCollection, DependencyObject, DiscreteColorKeyFrame, DiscreteDoubleKeyFrame, DiscretePointKeyFrame, DoubleAnimation, DoubleAnimationUsingKeyFrames, DoubleKeyFrame, DoubleKeyFrameCollection, Downloader, DrawingAttributes, Duration, Ellipse, EllipseGeometry, EventTrigger, Geometry, GeometryCollection, GeometryGroup, Glyphs, GradientStop, GradientStopCollection, Image, ImageBrush, InkPresenter, Inlines, KeySpline, KeyTime, Line, LinearColorKeyFrame, LinearDoubleKeyFrame, LinearGradientBrush, LinearPointKeyFrame, LineBreak, LineGeometry, LineSegment, Matrix, MatrixTransform, MediaAttribute, MediaAttributeCollection, MediaElement, Path, PathFigure, PathFigureCollection, PathGeometry, PathSegment, PathSegmentCollection, Point, PointAnimation, PointAnimationUsingKeyFrames, PointKeyFrame, PointKeyFrameCollection, PolyBezierSegment, Polygon, Polyline, PolyLineSegment, PolyQuadraticBezierSegment, QuadraticBezierSegment, RadialGradientBrush, Rect, Rectangle, RectangleGeometry, RepeatBehavior, ResourceDictionary, RotateTransform, Run, RuntimeErrorEventArgs, ScaleTransform, SkewTransform, SolidColorBrush, SplineColorKeyFrame, SplineDoubleKeyFrame, SplinePointKeyFrame, Storyboard, Stretch, Stroke, StrokeCollection, StylusInfo, StylusPoint, StylusPointCollection, TextBlock, Timeline, TimelineCollection, TimelineMarker, TimelineMarkerCollection, TimelineMarkerEventArgs, TimeSpan, TransformCollection, TransformGroup, TranslateTransform, TriggerActionCollection, TriggerCollection, VisualCollection, VideoBrush

See Also

Using a Silverlight Plug-in


GetItem Method

Retrieves the object from the collection at the specified index.

XAML | You cannot use methods in XAML.
Scripting | retval = object.GetItem(index)

Parameters

index

integer

The index at which the object should be retrieved.

Return Value

object

Returns a reference to the object if successful; otherwise, returns null.

Examples

You can retrieve a specific child of a parent object by referencing the index of the collection of the parent object. The following JavaScript example shows how to retrieve a child of a parent Canvas object by using the GetItem method:

JavaScript
function getObject(parent, index)
{
    // Determine if the index is valid.
    if (index < parent.children.count)
    {
        // Retrieve the child object at the specified index in the collection.
        var object = parent.children.getItem(index);
    }

    return object;
}

Enumerating Child Objects

You can enumerate the child of a parent object by accessing the children collection of the parent object. The following JavaScript example shows how to enumerate the children of a parent Canvas object by using the GetItem method:

JavaScript
function getChildren(parent, index)
{
    // Enumerate the children of the Canvas object.
    for (i = 0; i < parent.children.count; i++)
    {
        var child = parent.children.getItem(i);

        // Display the index and type of the child object.
        alert(i + ": " + child.toString());
    }
}

Applies To

ColorKeyFrameCollection, DoubleKeyFrameCollection, GradientStopCollection, Inlines, PathFigureCollection, PathSegmentCollection, PointKeyFrameCollection, StrokeCollection, StylusPointCollection, TriggerActionCollection, TriggerCollection, VisualCollection

See Also

Insert, Referencing and Modifying Silverlight Objects


GetItemByName Method

Gets the MediaAttribute for the collection with the Name equal to the specified string.

XAML | You cannot use methods in XAML.
Scripting | retval = object.GetItemByName(name)

Parameters

name

string

The name of the MediaAttribute to get from the collection.

Return Value

MediaAttribute

The MediaAttribute with the Name property equal to the specified string if found; otherwise, null.

Examples

The following JavaScript example shows how to retrieve a MediaAttribute by name from the Attributes property of a MediaElement that has a Source property set to an ASX playlist file. The Name and Value properties of the MediaAttribute is then displayed.

JavaScript
    // Get the MediaElement name MediaPlayer.
    player = sender.findName("MediaPlayer");

    // Variable to hold the MediaAttribute.
    var attribute;

    // Get the MediaAttribute named Title
    try
    {
        attribute = player.Attributes.getItemByName("Title");
    }
    catch(errorObj)
    {
        alert(errorObj.message);
    }

    // Display the Value of the MediaAttribute
    if(attribute != null)
    {
      alert("The title of the track is: " + attribute.value);
    }

Applies To

MediaAttributeCollection

See Also

MediaElement, Attributes, Referencing and Modifying Silverlight Objects


GetParent Method

Gets the parent object of the calling object.

XAML | You cannot use methods in XAML.
Scripting | retval = object.GetParent()

Return Value

object

A reference to the specified parent object if successful; otherwise, returns null.

Remarks

The only objects that can contain UIElement children are Canvas or InkPresenter. Path can have child elements, but these are geometries rather than UIElements.

Applies To

Canvas, Ellipse, Glyphs, Image, InkPresenter, Line, MediaElement, Path, Polygon, Polyline, Rectangle, TextBlock

See Also

FindName, GetHost


GetPosition Method

Gets the x- and y-coordinates of the mouse pointer position.

XAML | You cannot use methods in XAML.
Scripting | retval = eventargs.GetPosition(element)

Parameters

element UIElement

Any UIElement-derived object that is contained by the Silverlight plug-in. The returned mouse pointer position is relative to element. To specify the object relative to the plug-in, set the element parameter to null.

Return Value

Point

A point that represents the current x- and y-coordinates of the mouse pointer position relative to element.

Remarks

The element parameter can also be set to any UIElement-derived object that is contained by the Silverlight plug-in. The returned mouse pointer position is relative to element. Depending on the location of element relative to the object, the coordinate values of the mouse position may be negative values.

Examples

The following JavaScript example shows how to retrieve the current mouse pointer position for the object that received the MouseMove event. In this case, the element parameter is set to null, which means the returned Point value represents the mouse pointer position of the object relative to the upper-left corner of the plug-in area.

JavaScript
function onMouseMove(sender, mouseEventArgs)
{
    // Return a Point object representing the x- and y-coordinates of the current mouse position.
    var pt = mouseEventArgs.getPosition(null);

    // Display the current mouse position.
    sender.findName("Status").text = pt.x + " : " + pt.y;
}

The following screenshot illustrates how the green Rectangle object uses the red Rectangle object as the value of element, in order to return mouse position values that are relative to the coordinate space of element. This means that clicking near the upper-left corner of the green Rectangle generates mouse position values that are negative with respect to the red Rectangle.

The following JavaScript example shows how to retrieve the current mouse pointer position for the object relative to element.

JavaScript
function onMouseLeftButtonUp(sender, mouseEventArgs)
{
    // Return a Point object representing the x- and y-coordinates of the current mouse position
    // relative to the reference object.
    var pt = mouseEventArgs.getPosition(sender.findName("referenceObject"));

    // Display the current mouse position.
    sender.findName("Status").text = pt.x + " : " + pt.y;
}

Applies To

MouseEventArgs

See Also

Silverlight Mouse Support, MouseEnter, MouseLeftButtonDown, MouseLeftButtonUp, MouseMove


GetResponseText Method

Retrieves a specified part of packaged downloaded data.

HTML | You cannot use this method in HTML.
Scripting | retval = downloaderObject.GetResponseText(part)

Parameters

part

string

The name of the specific part of the downloaded content package.

Return Value

object

The downloaded data. As in HTML, the return value can be examined and is passed as a string in a packet, but ultimately is interpreted by whatever property you set with this value.

Remarks

You generally only call this method from within the event handler for a Downloader Completed event. Outside of this context, there is no guarantee that a GetResponseText return value is valid.

When a Downloader object request is completed, the GetResponseText method returns a representation of the downloaded content as a string value. The return value from GetResponseText can represent XAML content, JavaScript content, or a media asset, such as an image.

If you are not requesting parts of a package, and the Downloader request only returns a single asset, you typically would get the ResponseText property rather than GetResponseText. Calling GetResponseText with part value of "" gives the same value as ResponseText.

Note If you are downloading media assets for use by the Source property of Image and MediaElement objects, you should consider using the SetSource (Image) or SetSource (MediaElement) methods rather than setting an object with GetResponseText or ResponseText and then setting the Source properties. This is a more efficient way to transfer large-sized media assets. ImageBrush also has an equivalent SetSource.

Silverlight provides the ability to download content as a package, which is a collection of independent files containing XAML content, media assets, and other application content. Once the package is successfully downloaded, you can use methods, such as GetResponseText, SetSource, and CreateFromXamlDownloader, to selectively retrieve a specific named part of the package. In this case, a part reference is the filename reference of the individual content within the package, such as "rotation01_green.png".

Retrieving a part from a download package

The part parameter of the GetResponseText method identifies the specific part to retrieve within the downloaded content.

Examples

The following JavaScript example shows how to use the GetResponseText method to retrieve a specified part from the downloaded content:

JavaScript
function onDownloadCompleted(sender, eventArgs)
{
    // Retrieve the XAML content from the downloaded package file.
    var jacketBrowserXaml = sender.getResponseText("jacketBrowser.xaml");

    // Create the objects from the XAML content.
    var jacketBrowser = plugin.content.createFromXaml(jacketBrowserXaml);

    // Add downloaded XAML content to the root Canvas of the plug-in.
    sender.findName("root").children.insert(0, jacketBrowser);

    // Retrieve a reference to the Image object representing the jacket.
    var jacketImageSlice = sender.findName("jacketSlice");

    // Set the Source property of the Image object to the specific jacket image
    // within the downloaded Zip package file.
    jacketImageSlice.setSource(sender, "rotation01_green.png");
}

Applies To

Downloader

See Also

Completed, SetSource (MediaElement), Status, StatusText, Using a Downloader Object


GetStylusInfo Method

Returns a StylusInfo object which gives information about the state of the Stylus.

XAML | You cannot use methods in XAML.
Scripting | retval = eventargs.GetStylusInfo()

Return Value

StylusInfo

Information about the state of the stylus.

Remarks

For a mouse, the following is returned:
Type = Mouse
IsInverted = False

Examples

The following example demonstrates how to display the type of device that was used to create the current StylusPoint.

JavaScript
// Capture mouse movement when the left button is pressed and create the stroke
function InkPresenterMouseDown(sender,args)
{
  // Display the Type of input device in a TextBlock
  device.Text = args.GetStylusInfo().deviceType;

  inkPresenter.CaptureMouse();
  newStroke = agCtrl.content.createFromXaml('<Stroke/>');

  newStroke.StylusPoints.AddStylusPoints(args.GetStylusPoints(inkPresenter));
  inkPresenter.Strokes.Add(newStroke);
}

Applies To

MouseEventArgs

See Also


GetStylusPoints Method

Returns a clone of the stylus points collected since the last mouse event.

XAML | You cannot use methods in XAML.
Scripting | retval = eventargs.GetStylusPoints(inkPresenter)

Parameters

inkPresenter

InkPresenter

The coordinates of the StylusPoints that are returned are relative to the InkPresenter that is passed into the method.

Return Value

StylusPointCollection

A collection of the stylus points collected since the last mouse event.

Remarks

If the active device is a mouse, the returned StylusPointCollection will contain a single point corresponding to the mouse event.

Examples

In this example the x and y coordinates of each StylusPoint are sent to a TextBlock as they are added to a stroke.

JavaScript
// Add the new points to the Stroke we're working with and display the StylusPoint coordinates.
function InkPresenterMouseMove(sender,args)
{
   if (newStroke != null)
   {
      newStroke.StylusPoints.AddStylusPoints(args.GetStylusPoints(inkPresenter));
      xCoord.Text = "" + args.GetStylusPoints(inkPresenter).GetItem(0).X;
      yCoord.Text = "" + args.GetStylusPoints(inkPresenter).GetItem(0).Y;
      pressureData.Text = "" + args.GetStylusPoints(inkPresenter).GetItem(0).PressureFactor;
   }
}

Applies To

MouseEventArgs

See Also

Ink Support In Microsoft Silverlight


GetValue Method

Gets the value of the specified property.

XAML | You cannot use methods in XAML.
Scripting | retval = object.GetValue(propertyName)

Parameters

propertyName

string

Name of the property to get the value for.

Return Value

object

The value of the specified property.

Remarks

You can use the GetValue method to get the value of any Silverlight property. However, you generally do not need this method to get property values, because all Silverlight properties support a more direct property syntax.

You can also use GetValue to get the value of Silverlight attached properties such as Canvas.Left. In this case, the attached property name is the owner class name for the attached property, a dot, and the attached property name: value = object.GetValue("ownerType.propertyName"). Attached properties also support a more direct property syntax, in the form value = object["ownerType.propertyName"].

Examples

The following JavaScript example shows to get a property value by using both the GetValue method and the typical property notation:

JavaScript
function onMouseLeftButtonUp(sender, index)
{
    // Get the property value using the GetValue method.
    var opacity = sender.getValue("opacity");

    // Get the property value using the equivalent "." notation.
    var opacity = sender.opacity;

    alert("Opacity = " + opacity);
}

Applies To

Accessibility, ArcSegment, BeginStoryboard, BezierSegment, Boolean, Brush, Canvas, Color, ColorAnimation, ColorAnimationUsingKeyFrames, ColorKeyFrame, ColorKeyFrameCollection, DependencyObject, DiscreteColorKeyFrame, DiscreteDoubleKeyFrame, DiscretePointKeyFrame, DoubleAnimation, DoubleAnimationUsingKeyFrames, DoubleKeyFrame, DoubleKeyFrameCollection, Downloader, DrawingAttributes, Duration, Ellipse, EllipseGeometry, EventTrigger, Geometry, GeometryCollection, GeometryGroup, Glyphs, GradientStop, GradientStopCollection, Image, ImageBrush, InkPresenter, Inlines, KeySpline, KeyTime, Line, LinearColorKeyFrame, LinearDoubleKeyFrame, LinearGradientBrush, LinearPointKeyFrame, LineBreak, LineGeometry, LineSegment, Matrix, MatrixTransform, MediaAttribute, MediaAttributeCollection, MediaElement, Path, PathFigure, PathFigureCollection, PathGeometry, PathSegment, PathSegmentCollection, Point, PointAnimation, PointAnimationUsingKeyFrames, PointKeyFrame, PointKeyFrameCollection, PolyBezierSegment, Polygon, Polyline, PolyLineSegment, PolyQuadraticBezierSegment, QuadraticBezierSegment, RadialGradientBrush, Rect, Rectangle, RectangleGeometry, RepeatBehavior, ResourceDictionary, RotateTransform, Run, RuntimeErrorEventArgs, ScaleTransform, SkewTransform, SolidColorBrush, SplineColorKeyFrame, SplineDoubleKeyFrame, SplinePointKeyFrame, Storyboard, Stretch, Stroke, StrokeCollection, StylusInfo, StylusPoint, StylusPointCollection, TextBlock, Timeline, TimelineCollection, TimelineMarker, TimelineMarkerCollection, TimelineMarkerEventArgs, TimeSpan, TransformCollection, TransformGroup, TranslateTransform, TriggerActionCollection, TriggerCollection, VisualCollection, VideoBrush

See Also

Referencing and Modifying Objects, SetValue


HitTest Method (Stroke)

Returns true if the StylusPointCollection passed intersects the Stroke object; otherwise, false.

XAML | You cannot use methods in XAML.
Scripting | retval = object.HitTest(stylusPoints)

Parameters

stylusPoints

StylusPointCollection

The collection of stylus points used to check for intersection with the Stroke object.

Return Value

Boolean

true if the StylusPointCollection passed intersects the Stroke object; otherwise, false

Examples

JavaScript
// Add the new points to the Stroke we're working with or
// change the color of intersected strokes if the stylus is inverted.
function InkPresenterMouseMove(sender,args)
{
  if (args.GetStylusInfo().IsInverted)
  {
    // Change the color of intersected strokes
    // to red to indicate they are selected
    for (var i = 0; i < inkPresenter.Strokes.Count; i++)
    {
      var hitStroke = inkPresenter.Strokes.GetItem(i);

      if (hitStroke.HitTest(args.GetStylusPoints(inkPresenter)))
      {
        hitStroke.DrawingAttributes.SetValue("Color", "Red");
      }
    }
  }
  else if (newStroke != null)
  {
    // Add points to the stroke we're currently creating
    newStroke.StylusPoints.AddStylusPoints(args.GetStylusPoints(inkPresenter));
  }
}

Applies To

Stroke

See Also


HitTest Method (StrokeCollection)

Returns a collection of strokes that are intersected by the points in the StylusPointCollection passed.

XAML | You cannot use methods in XAML.
Scripting | retval = object.HitTest(stylusPoints)

Parameters

stylusPoints

StylusPointCollection

The collection of stylus points used to check for intersection with the StrokeCollection.

Return Value

StrokeCollection

A collection of strokes that are intersected by the points in the StylusPointCollection passed.

Remarks

For a StrokeCollection_sc, containing strokes S0 - S2, and a StylusPointCollection_spc, containing points P0 - P3, calling:

sc.HitTest(spc)
returns a StrokeCollection containing S1 and S2.

Examples

JavaScript

// Add the new points to the Stroke we're working with
// or delete strokes if we are in erase mode.

function inkPresenterMouseMove(sender, args)
{
    var stylusPoints = args.getStylusPoints(sender);

    // Check if we are in Erase mode.
    if (lastErasePoint != null)
    {
        // Connect the point from previous mouse event
        // to the current collection of stylus points.
        stylusPoints.insert(0, lastErasePoint);
        var hitStrokes = sender.strokes.hitTest(stylusPoints);

        // Remove the strokes that were intersected.
        for (var i = 0; i < hitStrokes.Count; i++)
        {
          sender.strokes.remove(hitStrokes.getItem(i));
        }

        // Update the cached last erase point.
        lastErasePoint = stylusPoints.getItem(stylusPoints.count-1);
    }

    // Check if we are in Ink mode.
    if (newStroke != null)
    {
        newStroke.stylusPoints.addStylusPoints(stylusPoints);
    }
}

Applies To

StrokeCollection

See Also

Ink Support In Microsoft Silverlight


Insert Method

Inserts an object into the collection at the specified index.

XAML | You cannot use methods in XAML.
Scripting | object.Insert(index, value)

Parameters

index | integer The index at which the object should be inserted.
value | object The object to insert into the collection.

Remarks

When you use the Insert method, you add the object to a specified index in the parent object's collection. Existing objects are shifted to make room for the new inserted object.

Examples

The following JavaScript example shows an object inserted into the beginning of a collection that contains three existing Rectangle objects.

JavaScript
// Insert an overlapping Rectangle object.
function InsertItem(rootCanvas)
{
    var plugin = rootCanvas.getHost();

    var xamlFragment = '<Rectangle Fill="Black" Canvas.Top="0" Canvas.Left="0" Height="100" Width="100" />';
    var rectangle_4 = plugin.content.createFromXaml(xamlFragment);
    rootCanvas.children.insert(0, rectangle_4);
}

The following illustration shows the display result of the previous JavaScript example. Notice that the rendering of the inserted object. Since the inserted object is the first object in the collection, it is overlaid by all of its siblings:

Z-order of an inserted object into the collection

Applies To

ColorKeyFrameCollection, DoubleKeyFrameCollection, GradientStopCollection, Inlines, PathFigureCollection, PathSegmentCollection, PointKeyFrameCollection, StrokeCollection, StylusPointCollection, TriggerActionCollection, TriggerCollection, VisualCollection

See Also

Add, Referencing and Modifying Silverlight Objects


IsVersionSupported Method

Determines whether the existing Silverlight plug-in is a matching version or is a compatible version with a specified version string.

XAML | You cannot use methods in XAML.
Scripting | retval = silverlightObject.IsVersionSupported(versionString)

Parameters

versionString

string

A string that represents the version to check against the Silverlight plug-in.

Return Value

Boolean

true if the existing Silverlight plug-in is a matching version or is a compatible version with a specified version string; otherwise, false.

Remarks

The format of the version string contains four integer values that are separated by dots, for example, "1.0.50232.0". The sequence of integers represent the following version values:

  • major - the major number
  • minor - the minor number
  • build - the build number
  • revision - the revision number

This method primarily supports the JavaScript helper method IsInstalled, which is defined in Silverlight.js. Once you have an instantiated Silverlight plug-in that is displaying content, checking the installed version is of lesser importance. The main reason you typically need to know the installed Silverlight plug-in version is to change the information that is displayed to the user prior to instantiating a control with content in your HTML, and/or to anticipate whether your HTML page users will see Silverlight update or install UI based on the installed plug-in version versus what you are passing as "version" in the CreateObject method call. For more information, see Using CreateSilverlight.js and Silverlight.js.

Applies To

Silverlight Plug-in

See Also

Using a Silverlight Plug-in, Referencing and Modifying Silverlight Objects


Open Method

Initializes the download request.

XAML | You cannot use methods in XAML.
Scripting | downloaderObject.Open(verb, uri)

Parameters

verb | string The type of download action. The only supported action is "GET".
uri | string The Uniform Resource Identifier (URI) of the content to perform the download action.

Remarks

The Open method initializes the Downloader object by specifying the action to perform and the content to perform the action on. However, the download is not committed until you subsequently call Send.

The uri you specify for Open must reference content on the same site of origin as the hosting HTML page. Cross-domain downloads are not permitted. Also, backslashes (\) in Downloader URIs are not permitted; always use forward slashes (/). Generally, a best practice is to use relative URIs, which are calculated based on the position of the hosting HTML page. For details, see Using a Downloader Object.

Examples

The following JavaScript example shows how to call the Open method:

JavaScript
// Event handler for initializing and executing a download request.
function onMouseLeftButtonUp(sender, eventArgs)
{
    // Retrieve a reference to the plug-in.
    var slPlugin = sender.getHost();

    // Create a Downloader object.
    var downloader = slPlugin.createObject("downloader");

    // Add DownloadProgressChanged and Completed events.
    downloader.addEventListener("downloadProgressChanged", onDownloadProgressChanged);
    downloader.addEventListener("completed", onCompleted);

    // Initialize the Downloader request.
    // NOTE: downloader APIs disallow file:\\ scheme
    // you must run this sample over localhost: or off a server or the following call will fail

    downloader.open("GET", "promo.png");

    // Execute the Downloader request.
    downloader.send();
}

Applies To

Downloader

See Also

Abort, Send, Using a Downloader Object


Pause Method (MediaElement)

Pauses media at the current position.

XAML | You cannot use methods in XAML.
Scripting | object.Pause()

Remarks

This method pauses the media if the media is currently running. The Play method can be used to resume.

CanPause returns false for any case where the MediaElement has loaded live streaming media. Calling Pause on a MediaElement that has opened and is playing streaming content does not throw an error. Instead the method call is ignored.

Applies To

MediaElement

See Also

Play, Stop, CanPause, Media Overview


Pause Method (Storyboard)

Pauses the set of animations associated with this Storyboard.

XAML | You cannot use methods in XAML.
Scripting | object.Pause()

Applies To

Storyboard

See Also

Animation Overview


Play Method (MediaElement)

Plays media from the current position.

XAML | You cannot use methods in XAML.
Scripting | object.Play()

Remarks

This method will begin the media if it is not currently active or resume media if it is paused. This method has no effect if the media is currently running.

Applies To

MediaElement

See Also

Pause, Stop


ReleaseMouseCapture Method

Disables mouse capture for the object.

XAML | You cannot use methods in XAML.
Scripting | object.ReleaseMouseCapture()

Remarks

The ReleaseMouseCapture method disables mouse capture for a plug-in that has captured the mouse by using the CaptureMouse method. When a plug-in instance has captured the mouse, it receives mouse input whether or not the cursor is within its borders. The mouse is typically only captured during drag operations. For more information on capturing the mouse, see Implementing Drag and Drop.

Examples

The following JavaScript example shows the mouse being captured and released using event handler functions for the MouseLeftButtonDown and MouseLeftButtonUp events.

JavaScript
// Display the current mouse position for the Rectangle object.
function onMouseMove(sender, mouseEventArgs)
{
    var msg = "x:y = " + mouseEventArgs.getPosition(null).x + ", " + mouseEventArgs.getPosition(null).y;
    sender.findName("statusTextBlock").Text = sender.Name + ": " + msg;
}

// Enable mouse capture when the mouse is depressed over the green Rectangle object.
function onLeftButtonDown(greenRect, mouseEventArgs)
{
    greenRect.captureMouse();
}

// Disable mouse capture when the mouse is released over the green Rectangle object.
function onLeftButtonUp(greenRect, mouseEventArgs)
{
    greenRect.releaseMouseCapture();
}

Applies To

Canvas, Ellipse, Glyphs, Image, InkPresenter, Line, MediaElement, Path, Polygon, Polyline, Rectangle, TextBlock

See Also

CaptureMouse, Silverlight Mouse Support, MouseLeftButtonDown, MouseLeftButtonUp, MouseMove


Remove Method

Removes the specified object from the collection.

XAML | You cannot use methods in XAML.
Scripting | retval = object.Remove(value)

Parameters

value

object

The object to remove from the collection.

Return Value

Boolean

true if value was removed from the collection; otherwise, false.

Remarks

The Remove method removes a child object from the parent collection by referencing the object's x:Name attribute value. As soon as objects are removed from the Silverlight object hierarchy, they are no longer rendered. When you remove an object using the Remove or RemoveAt methods, you are disconnecting the object from the Silverlight object hierarchy. The disconnected object is now a XAML fragment that can be connected back to the object hierarchy using the Add method. The following two diagrams illustrate the process of disconnecting objects from the Silverlight object hierarchy:

Removing objects from the Silverlight object hierarchy

Removing an object from the Silverlight object hierachy

Disconnected XAML fragment and Silverlight object hierarchy

Disconnected XAML fragment and Silverlight object hierarchy

Examples

The following JavaScript example shows to remove a TextBlock from its parent Canvas object by using the Remove method on the object's collection of children.

JavaScript
function removeCaption(rootCanvas)
{
    // Retrieve the TextBlock object.
    var captionTextBlock = rootCanvas.findName("myCaption");

    if (captionTextBlock != null)
    {
        rootCanvas.children.remove(captionTextBlock);
    }
}

The RemoveAt method removes a child object at a specified index value in the parent's collection. This means the child object does not require an x:Name attribute value. The following JavaScript example removes the first object from a parent Canvas object by using the RemoveAt method:

JavaScript
// Remove the first child object from the parent collection.
myCanvas.children.removeAt(0);

You can remove all objects in a collection by using the Clear method, which is equivalent to using the RemoveAt method for each item in the collection. The following JavaScript example shows to removes all items from a collection using the Clear method.

JavaScript
// Remove all child objects from the parent collection.
myCanvas.children.clear();

Applies To

ColorKeyFrameCollection, DoubleKeyFrameCollection, GradientStopCollection, Inlines, PathFigureCollection, PathSegmentCollection, PointKeyFrameCollection, StrokeCollection, StylusPointCollection, TriggerActionCollection, TriggerCollection, VisualCollection

See Also

Clear, RemoveAt, Referencing and Modifying Silverlight Objects


RemoveAt Method

Removes the object at the specified index.

XAML | You cannot use methods in XAML.
Scripting | retval = object.RemoveAt(index)

Parameters

index

object

The zero-based index of the object to remove.

Return Value

object

A reference to the removed item from the collection if successful; otherwise, returns null.

Remarks

The RemoveAt method removes a child object at a specified index value in the parent's collection. This means the child object does not require an x:Name attribute value. As soon as objects are removed from the Silverlight object hierarchy, they are no longer rendered.

Examples

The following JavaScript example shows to remove the first object from a parent Canvas object by using the RemoveAt method:

JavaScript
// Remove the first child object from the parent collection.
myCanvas.children.removeAt(0);

The Remove method removes a child object from the parent's collection by referencing the object's x:Name / Name attribute value. The following JavaScript example shows to remove a TextBlock from its parent Canvas object by using the Remove method on the object's collection of children.

JavaScript
function removeCaption(rootCanvas)
{
    // Retrieve the TextBlock object.
    var captionTextBlock = rootCanvas.findName("myCaption");

    if (captionTextBlock != null)
    {
        rootCanvas.children.remove(captionTextBlock);
    }
}

You can remove all objects in a collection by using the Clear method, which is equivalent to using the RemoveAt method for each item in the collection. The following JavaScript example removes all items from a collection using the Clear method.

JavaScript
// Remove all child objects from the parent collection.
myCanvas.children.clear();

Applies To

ColorKeyFrameCollection, DoubleKeyFrameCollection, GradientStopCollection, Inlines, PathFigureCollection, PathSegmentCollection, PointKeyFrameCollection, StrokeCollection, StylusPointCollection, TriggerActionCollection, TriggerCollection, VisualCollection

See Also

Clear, Remove, Referencing and Modifying Silverlight Objects


RemoveEventListener Method

Unregisters an event listener on the event target object.

XAML
You cannot use methods in XAML.
Scripting
object.RemoveEventListener(eventName, token)
-or-
object.RemoveEventListener(eventName,functionName)

Parameters

eventName | string The type of event, such as "KeyDown". This is a true string, and the value must be quoted. An exception is thrown if eventName is invalid (not a known event name).
token | integer A token that is returned from an AddEventListener call. If you have no token, and the handler was added in XAML, you can pass 0.
functionName | string The name of the event handler function. This syntax only works in two cases: either the handler was added in XAML, or the original AddEventListener call that added the handler used a quoted string rather than a delegate reference.

Remarks

The AddEventListener method returns a token. Often you do not need this token, so you can call this method without storing the return value. However, if you plan to remove the event handler at some later point in your code, and you have added multiple listeners to the same event using scripting, you should retain this token.

The alternative AddEventListener syntax that specifies the event handler as a quoted string was originally for Safari browsers, which did not have the ability in the browser object model to retain handler references. You can still use the quoted string syntax as an option; the quoted string syntax effectively parallels the mechanism that is used to add the handlers that are declared as XAML attributes. When you use the quoted string syntax, you are not obligated to use the token in calls to RemoveEventListener. Instead of the retained token, you can specify the second parameter of RemoveEventListener as a quoted string of the handler name. To explicitly remove handlers that were added through XAML, you can either specify the handler name as a string, or use a token value of 0 (handlers from XAML always have that token value).

Use the RemoveEventListener method to remove a handler that has been added using the AddEventListener method.

Note The Silverlight implementation of RemoveEventListener is different from the HTML Document Object Model (DOM) version method of the same name. The DOM version provides an additional third parameter that enables event capture.

Another important difference from the HTML DOM is that the the Silverlight implementation of AddEventListener will register multiple identical event listeners if provided. The event listener is called as many times as it was added. If there are multiples, a RemoveEventListener call removes only one of the instances, not all of them.

Examples

The following JavaScript example shows how to remove events from a TextBlock object, using tokens that were obtained from earlier AddEventListener calls:

JavaScript
function removeEvents()
{
    textBlock.removeEventListener("MouseEnter", entertoken1);
    textBlock.removeEventListener("MouseLeave", leavetoken1);
}

Applies To

Canvas, Ellipse, Glyphs, Image, InkPresenter, Line, MediaElement, Path, Polygon, Polyline, Rectangle, TextBlock

See Also

AddEventListener


Resume Method (Storyboard)

Resumes the set of animations associated with this Storyboard.

XAML | You cannot use methods in XAML.
Scripting | object.Resume()

Applies To

Storyboard

See Also

Animation Overview


Seek Method

Seeks this Storyboard to a new position when the next clock tick occurs.

XAML | You cannot use methods in XAML.
Scripting | object.Seek(offset)

Parameters

offset

TimeSpan

A positive or negative time value that describes the amount by which the timeline should move forward or backward from the beginning of the animation. The TimeSpan is specified as a string in the following format (in this syntax, the [] characters denote optional components of the string, but the quotes, colons and periods are all part of the syntax):

"[days.]hours:minutes:seconds[.fractionalSeconds]"
- or -
"days"

Remarks

Defining a TimeSpan is only possible through a type conversion syntax when setting a property or calling a method that takes TimeSpan as a type, with the value specified as a string in a delimited format, as documented in the Parameters section or on the TimeSpan page.

Examples

The following example shows how to use the Seek method. When you click on the rectangle created by the XAML below, the animation jumps to 3 seconds from the beginning of the animation.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Rectangle
    x:Name="MyAnimatedRectangle"
    Width="50"
    Height="100"
    Fill="Blue"
    MouseLeftButtonDown="SeekStoryboard"
    >
    <Rectangle.Triggers>
      <!-- Increases the width of the rectangle. -->
      <EventTrigger RoutedEvent="Rectangle.Loaded">
        <BeginStoryboard>
          <Storyboard x:Name="RectWidthStoryboard">
            <DoubleAnimation
              Storyboard.TargetName="MyAnimatedRectangle"
              Storyboard.TargetProperty="Width"
              From="50" To="550" Duration="0:0:5" />
          </Storyboard>
        </BeginStoryboard>
      </EventTrigger>
    </Rectangle.Triggers>
  </Rectangle>
</Canvas>
JavaScript
function SeekStoryboard(sender, eventArgs)
{

  // Get a reference to the Storyboard.
  var myStoryboard = sender.findName("RectWidthStoryboard");

  // Seek to 3 seconds after the animation begins.
  myStoryboard.Seek("0:0:3");

}

Applies To

Storyboard

See Also

Animation Overview, Interactive Animations Overview


Send Method

Executes a download request.

XAML | You cannot use methods in XAML.
Scripting | downloaderObject.Send()

Remarks

The Send method executes the request to download data using the Downloader object functionality. The Send method executes asynchronously. If you need to know the precise moment that the requested content is available, you should attach a handler for the Completed event prior to calling Send.

A cross-domain download attempt, or an attempt to download through the FILE scheme, will fail even before raising the Completed or DownloadFailed events, and the symptom of the failure is that the Send method call will fail.

Examples

The following JavaScript example shows how to invoke the Send method:

JavaScript
// Event handler for initializing and executing a download request.
function onMouseLeftButtonUp(sender, eventArgs)
{
    // Retrieve a reference to the plug-in.
    var slPlugin = sender.getHost();

    // Create a Downloader object.
    var downloader = slPlugin.createObject("downloader");

    // Add DownloadProgressChanged and Completed events.
    downloader.addEventListener("downloadProgressChanged", onDownloadProgressChanged);
    downloader.addEventListener("completed", onCompleted);

    // Initialize the Downloader request.
    // NOTE: downloader APIs disallow file:\\ scheme
    // you must run this sample over localhost: or off a server or the following call will fail

    downloader.open("GET", "promo.png");

    // Execute the Downloader request.
    downloader.send();
}

Applies To

Downloader

See Also

Abort, Open, Using a Downloader Object


SetFontSource Method

Adds font files in the downloaded content to the object's collection of type faces.

XAML | You cannot use methods in XAML.
Scripting | object.SetFontSource(downloader)

Parameters

downloader

Downloader

The object containing the downloaded content. Set downloader to null to restore the default font for the object.

Remarks

The SetFontSource method can be used as a way of adding downloaded font content to the existing collection of type faces for a TextBlock object. The downloader parameter identifies the Downloader object representing the downloaded content. The downloaded content can either be an individual font file or packaged content, such as a Zip file, that contains one or more font files. This particular downloader API does not have a part parameter, because fonts are extracted from all parts in a downloaded package automatically.

Downloader only supports downloading fonts that come from the same domain as does the HTML page that contains the Silverlight plug-in; for details, see Using a Downloader Object. Also, backslashes (\) in ImageSource URIs are not permitted; always use forward slashes (/).

Note Font files used with the SetFontSource method must be OpenType or TrueType fonts.

Note As with most types of software, font files are licensed, rather than sold, and licenses that govern the use of fonts vary from vendor to vendor. As a developer it is your responsibility to ensure that you have the required license rights for any font you embed within a document or application, or otherwise redistribute.

Examples

The following JavaScript example shows how to use the Downloader object to download an individual font file.

JavaScript
// Event handler for initializing and executing a font file download request.
function onMouseLeftButtonUp(sender, eventArgs)
{
    // Retrieve a reference to the plug-in.
    var plugin = sender.getHost();

    // Create a Downloader object.
    var downloader = plugin.createObject("downloader");

    // Add Completed event.
    downloader.addEventListener("Completed", onCompleted);

    // Initialize the Downloader request.
    downloader.open("GET", "SHOWG.TTF");

    // Execute the Downloader request.
    // NOTE: downloader APIs disallow file:\\ scheme
    // you must run this sample over localhost: or off a server or the following call will fail
    downloader.send();
}

When the font file has been downloaded, it needs to be added to the TextBlock's collection of type faces, which is the purpose of SetFontSource. Once it has been added to the collection, it can then be selected using the FontFamily property. The following JavaScript example shows how to use the SetFontSource method to add the the font file to the type face collection, and then set the FontFamily property to display the TextBlock with the downloaded font:

JavaScript
// Event handler for the Completed event.
function onCompleted(sender, eventArgs)
{
    // Retrieve the TextBlock object.
    var myTextBlock = sender.findName("myTextBlock");

    // Add the font files in the downloaded object to the TextBlock's type face collection.
    myTextBlock.setFontSource(sender);

    // Set the FontFamily property to the friendly name of the font.
    myTextBlock.fontFamily = "Showcard Gothic";

    myTextBlock.text = "Showcard Gothic";
}

You can also download font files contained in a packaged format, such as a Zip file. The Zip file can contain other content files, such as image files, and those files are effectively ignored for purposes of what gets added to the font collection.

The following JavaScript example shows how to use the Downloader object to download a Zip file containing an image file and multiple font files.

JavaScript
// Initialize the Downloader request. Zip file contains: Coco.png, Britanic.ttf, Erasbd.ttf, Showg.ttf
downloader.open("GET", "myMediaAssets.zip");

When the Zip file has been downloaded, the font files it contains must be added to the TextBlock's collection of type faces. Once the font files have been added to the collection, they can then be selected using the FontFamily property. The following JavaScript example shows how to use the SetSource and SetFontSource methods to use the downloaded content.

JavaScript
// Event handler for the Completed event.
function onCompleted(sender, eventArgs)
{
    // Retrieve the Image object.
    var myImage = sender.findName("myImage");

    // Set the Source property of the Image object to the specific image
    // within the downloaded Zip package file.
    myImage.setSource(sender, "Coco.png");

    // Retrieve the TextBlock object.
    var myTextBlock = sender.findName("myTextBlock");

    // Add the font files in the downloaded package object to the TextBlock's type face collection.
    myTextBlock.setFontSource(sender);

    // Set the FontFamily property to the friendly name of the font.
    myTextBlock.fontFamily = "Showcard Gothic";
}

The following JavaScript example shows how to define a Silverlight keyboard event by using the AddEventListener method:

JavaScript
function onLoaded(sender, eventArgs)
{
    // Set the root Canvas object to a KeyDown event handler function.
    var token = sender.addEventListener("keyDown", onKeyDown);
}

function onKeyDown(sender, keyEventArgs)
{
    // Determine whether the keystroke combination CTRL+V was detected.
    if ((keyEventArgs.key == 51) && (keyEventArgs.ctrl == true))
    {
        // Retrieve a reference to the plug-in.
        var slPlugin = sender.getHost();

        // Display the current version of the plug-in.
        alert("Silverlight version: " + slPlugin.isVersionSupported("1.0"));
    }
}

To return to the default font used to display the TextBlock, set the downloader parameter of the SetFontSource method to null.

The following JavaScript example shows how to use the SetFontSource method with a null parameter value.

JavaScript
// Retrieve the TextBlock object.
var myTextBlock = sender.findName("myTextBlock");

// Remove the custom font setting.
myTextBlock.setFontSource(null);

Applies To

TextBlock

See Also

Downloader, Using a Downloader Object


SetSource Method (Image)

Sets the source value of an object with downloaded content.

XAML | You cannot use methods in XAML.
Scripting | object.SetSource(downloader, part)

Parameters

downloader | Downloader The object containing the downloaded content.
part | string The name of the specific part of the downloaded content package. When the downloaded content package is a Zip file, part refers to the contents of a filename within downloader. If the downloaded content does not represent packaged content, set part to an empty string.

Remarks

The SetSource method sets the downloaded image content to the Source property of the Image. Equivalent SetSource methods exist on ImageBrush (for ImageSource) and MediaElement (for Source). The first parameter, downloader, identifies the Downloader object representing the downloaded content. The second parameter, part, identifies the specific part to retrieve within the downloaded content. If the downloaded content does not represent packaged content, such as a Zip file, part must be set to an empty string.

Examples

The following JavaScript example shows how to use the SetSource method to set the Source property of an Image object to the downloaded content:

JavaScript
// Event handler for the Completed event.
function onCompleted(sender, eventArgs)
{
    // Retrieve the Image object.
    var myImage = sender.findName("myImage");

    // Set the Source property to the contents of the downloaded object,
    // In this case, since the downloaded content represents a single image file, promo.png,
    // the part parameter is set to an empty string.
    myImage.setSource(sender, "");
}

Silverlight provides the ability to download content as a package, which is a collection of independent files containing XAML content, media assets, and other application data. The Zip file format is supported as a download package. The following diagram illustrates a collection of application content contained within a Zip download package:

Download package contains a collection of application files

Once the package is successfully downloaded, you can use methods, such as GetResponseText, SetSource, and CreateFromXamlDownloader, to selectively retrieve a specific named part of the package. In this case, a part reference is the filename reference of the individual content within the package, such as "rotation01_green.png".

Retrieving a part from a download package

You can use the SetSource method to retrieve a specific part within the downloaded content package. When the downloaded content package is a Zip file, the SetSource method allows you to retrieve the contents of a filename within the Zip file. The following JavaScript example shows how to use the SetSource method to set the Source property of an Image object to a specified part within the downloaded content:

JavaScript
function onDownloadCompleted(sender, eventArgs)
{
    // Retrieve the XAML content from the downloaded package file.
    var jacketBrowserXaml = sender.getResponseText("jacketBrowser.xaml");

    // Create the objects from the XAML content.
    var jacketBrowser = plugin.content.createFromXaml(jacketBrowserXaml);

    // Add downloaded XAML content to the root Canvas of the plug-in.
    sender.findName("root").children.insert(0, jacketBrowser);

    // Retrieve a reference to the Image object representing the jacket.
    var jacketImageSlice = sender.findName("jacketSlice");

    // Set the Source property of the Image object to the specific jacket image
    // within the downloaded Zip package file.
    jacketImageSlice.setSource(sender, "rotation01_green.png");
}

Applies To

Image

See Also

Downloader, SetSource Method (ImageBrush), SetSource Method (MediaElement), Using a Downloader Object


SetSource Method (ImageBrush)

Sets the source value of an object with downloaded content.

XAML | You cannot use methods in XAML.
Scripting | object.SetSource(downloader, part)

Parameters

downloader | Downloader The object containing the downloaded content.
part | string The name of the specific part of the downloaded content package. When the downloaded content package is a Zip file, part refers to the contents of a filename within downloader. If the downloaded content does not represent packaged content, set part to an empty string.

Remarks

The SetSource method sets the downloaded image content to the ImageSource property of the ImageBrush. Equivalent SetSource methods exist on Image (for Source) and MediaElement (for Source). The first parameter, downloader, identifies the Downloader object representing the downloaded content. The second parameter, part, identifies the specific part to retrieve within the downloaded content. If the downloaded content does not represent packaged content, such as a Zip file, part must be set to an empty string.

Examples

The following JavaScript example shows how to use the SetSource method to set the Source property of an Image object to the downloaded content:

JavaScript
// Event handler for the Completed event.
function onCompletedImageBrush(sender, eventArgs)
{
    // Retrieve the ImageBrush object.
    var myImageBrush = sender.findName("myImageBrush");

    // Set the ImageSource property to the contents of the downloaded object,
    // named gear_large.png as a zip part in the download
    myImageBrush.setSource(sender, "gear_large.png");
}

Applies To

ImageBrush

See Also

Downloader, SetSource Method (Image), SetSource Method (MediaElement), Using a Downloader Object


SetSource Method (MediaElement)

Sets the source value of an object with downloaded content.

XAML | You cannot use methods in XAML.
Scripting | object.SetSource(downloader, part)

Parameters

downloader | Downloader The object containing the downloaded content.
part | string The name of the specific part of the downloaded content package. When the downloaded content package is a Zip file, part refers to the contents of a filename within downloader. If the downloaded content does not represent packaged content, set part to an empty string.

Remarks

The SetSource method sets the downloaded media content to the Source property of the MediaElement. Equivalent SetSource methods exist on ImageBrush (for ImageSource) and Image (for Source).

SetSource differs notably from just setting Source in that cross-domain URIs for Source are permitted, whereas cross-domain URIs for the Downloader object you create to support SetSource are not permitted. Therefore, if you are sourcing media element content using cross-domain and/or referencing media using a specific moniker such as mms:, you should not use SetSource and should instead set Source directly.

The first parameter, downloader, identifies the Downloader object representing the downloaded content. The second parameter, part, identifies the specific part to retrieve within the downloaded content. If the downloaded content does not represent packaged content, such as a Zip file, part must be set to an empty string.

Note In Silverlight 1.0, if an initial download attempt through SetSource fails (the underlying Downloader raises the DownloadFailed event), then subsequent attempts to call SetSource will also result in a failed download, even if the URI is expected to result in a successful download on subsequent attempts. In order to avoid this issue, you should provide a DownloadFailed handler on the underlying downloader. If DownloadFailed is detected, then you should null out the existing MediaElement, create a new one (using CreateFromXaml) and re-add it to the object tree at the same position. This will provide a MediaElement that will avoid the no-reset issue with its SetSource API.

Examples

The following JavaScript example shows how to use the SetSource method to set the Source property of an Image object to the downloaded content:

JavaScript
// Event handler for the Completed event.
function onCompletedVideo(sender, eventArgs)
{
    // Retrieve the MediaElement object.
    var myMediaElement = sender.findName("myMediaElement");

    // Set the Source property to the contents of the downloaded object,
    // named xbox.wmv as a zip part in the download
    myMediaElement.setSource(sender, "xbox.wmv");
}

Applies To

MediaElement

See Also

Downloader, SetSource Method (Image), SetSource Method (ImageBrush), Using a Downloader Object


SetValue Method

Sets the specified property or event to the specified value.

XAML | You cannot use methods in XAML.
Scripting | object.SetValue(propertyName, value)

Parameters

propertyName | string The name of the dependency property to set.
value | object The value to set the property to.

Remarks

You can use the SetValue method to set the value of any Silverlight property. However, you generally do not need this method to set property values, because all Silverlight properties support a more direct property syntax.

You can also use SetValue to set the value of Silverlight attached properties such as Canvas.Left. In this case, the attached property name is the owner class name for the attached property, a dot, and the attached property name: object.SetValue("ownerType.propertyName",value). Attached properties also support a more direct property syntax, in the form object["ownerType.propertyName"] = value.

Examples

The following JavaScript example shows to set a property value by using both the SetValue method and typical property notation:

JavaScript
function onMouseEnter(sender, index)
{
    // Set the property value using the SetValue method.
    sender.setValue("opacity", 0.5);

    // Set the property value using the equivalent "." notation.
    sender.opacity = 0.5;
}

Applies To

Accessibility, ArcSegment, BeginStoryboard, BezierSegment, Boolean, Brush, Canvas, Color, ColorAnimation, ColorAnimationUsingKeyFrames, ColorKeyFrame, ColorKeyFrameCollection, DependencyObject, DiscreteColorKeyFrame, DiscreteDoubleKeyFrame, DiscretePointKeyFrame, DoubleAnimation, DoubleAnimationUsingKeyFrames, DoubleKeyFrame, DoubleKeyFrameCollection, Downloader, DrawingAttributes, Duration, Ellipse, EllipseGeometry, EventTrigger, Geometry, GeometryCollection, GeometryGroup, Glyphs, GradientStop, GradientStopCollection, Image, ImageBrush, InkPresenter, Inlines, KeySpline, KeyTime, Line, LinearColorKeyFrame, LinearDoubleKeyFrame, LinearGradientBrush, LinearPointKeyFrame, LineBreak, LineGeometry, LineSegment, Matrix, MatrixTransform, MediaAttribute, MediaAttributeCollection, MediaElement, Path, PathFigure, PathFigureCollection, PathGeometry, PathSegment, PathSegmentCollection, Point, PointAnimation, PointAnimationUsingKeyFrames, PointKeyFrame, PointKeyFrameCollection, PolyBezierSegment, Polygon, Polyline, PolyLineSegment, PolyQuadraticBezierSegment, QuadraticBezierSegment, RadialGradientBrush, Rect, Rectangle, RectangleGeometry, RepeatBehavior, ResourceDictionary, RotateTransform, Run, RuntimeErrorEventArgs, ScaleTransform, SkewTransform, SolidColorBrush, SplineColorKeyFrame, SplineDoubleKeyFrame, SplinePointKeyFrame, Storyboard, Stretch, Stroke, StrokeCollection, StylusInfo, StylusPoint, StylusPointCollection, TextBlock, Timeline, TimelineCollection, TimelineMarker, TimelineMarkerCollection, TimelineMarkerEventArgs, TimeSpan, TransformCollection, TransformGroup, TranslateTransform, TriggerActionCollection, TriggerCollection, VisualCollection, VideoBrush

See Also

Referencing and Modifying Objects, GetValue


Stop Method (MediaElement)

Stops and resets media to be played from the beginning.

XAML | You cannot use methods in XAML.
Scripting | object.Stop()

Parameters

None

Return Value

None

Remarks

This method will stop media playback if the media is either playing or pause. This method has no effect if the media is already stopped.

Applies To

MediaElement

See Also

Play, Pause


Stop Method (Storyboard)

Halts the set of animations associated with this Storyboard.

XAML | You cannot use methods in XAML.
Scripting | object.Stop()

Applies To

Storyboard

See Also

Animation Overview


Silverlight Properties

This section contains a list of the properties exposed by the Silverlight Object Model.

Properties

Accessibility

ActionDescription

Actions

ActualHeight (Silverlight Plug-in)

ActualHeight (TextBlock)

ActualWidth (Silverlight Plug-in)

ActualWidth (TextBlock)

AlignmentX (ImageBrush)

AlignmentX (VideoBrush)

AlignmentY (ImageBrush)

AlignmentY (VideoBrush)

Angle

AngleX

AngleY

Attributes

AudioStreamCount

AudioStreamIndex

AutoPlay

AutoReverse

Background (Canvas)

Background (Silverlight Plug-in)

Balance

BeginTime

BufferingProgress

BufferingTime

By (ColorAnimation)

By (DoubleAnimation)

By (PointAnimation)

CanPause

CanSeek

Canvas.Left

Canvas.Top

Canvas.ZIndex

Center (EllipseGeometry)

Center (RadialGradientBrush)

CenterX (RotateTransform)

CenterX (ScaleTransform)

CenterX (SkewTransform)

CenterY (RotateTransform)

CenterY (ScaleTransform)

CenterY (SkewTransform)

CharPosition (ParserErrorEventArgs)

CharPosition (RuntimeErrorEventArgs)

Children (Canvas)

Children (GeometryGroup)

Children (Storyboard)

Children (TransformGroup)

Clip

Color (DrawingAttributes)

Color (GradientStop)

Color (SolidColorBrush)

ColorInterpolationMode (LinearGradientBrush)

ColorInterpolationMode (RadialGradientBrush)

Count

Ctrl (KeyboardEventArgs)

Ctrl (MouseEventArgs)

CurrentState

Cursor

Data

Description

DeviceType

DownloadProgress (Downloader)

DownloadProgress (MediaElement)

DownloadProgress (Image)

DownloadProgress (ImageBrush)

DrawingAttributes

Duration

EnableFramerateCounter

EnableHtmlAccess

EnableRedrawRegions

EndPoint (LinearGradientBrush)

EndPoint (LineGeometry)

ErrorCode

ErrorMessage

ErrorType

Figures

Fill (Glyphs)

Fill (Shape)

FillBehavior

FillRule (Geometry)

FillRule (Polygon)

FillRule (Polyline)

FontFamily

FontRenderingEmSize

FontSize

FontStretch

FontStyle

FontUri

FontWeight

Foreground

From (ColorAnimation)

From (DoubleAnimation)

From (PointAnimation)

FullScreen

GradientOrigin

GradientStops (LinearGradientBrush)

GradientStops (RadialGradientBrush)

Height (DrawingAttributes)

Height (Rect)

Height (UIElement)

ImageSource

Indices

InitParams

Inlines

IsClosed

IsHitTestVisible

IsInverted

IsLargeArc

IsLoaded

IsMuted

Key

KeyFrames (ColorAnimationUsingKeyFrames)

KeyFrames DoubleAnimationUsingKeyFrames)

KeyFrames PointAnimationUsingKeyFrames)

KeySpline (SplineColorKeyFrame)

KeySpline (SplineDoubleKeyFrame)

KeySpline (SplinePointKeyFrame)

KeyTime (ColorKeyFrame)

KeyTime (DoubleKeyFrame)

KeyTime (PointKeyFrame)

LineNumber (ParserErrorEventArgs)

LineNumber (RuntimeErrorEventArgs)

M11

M12

N21

M22

MappingMode (LinearGradientBrush)

MappingMode (RadialGradientBrush)

Marker

Markers

MaxFrameRate

MethodName

Name

NaturalDuration

NaturalVideoHeight

NaturalVideoWidth

Offset

OffsetX.htm

Offsety.htm

Opacity (Brush)

Opacity (UIElement)

OpacityMask

OriginX

OriginY

OutlineColor

PlatformKeyCode

Point (ArcSegment)

Point (LineSegment)

Point1 (BezierSegment)

Point1 (QuadraticBezierSegment)

Point2 (BezierSegment)

Point2 (QuadraticBezierSegment)

Point3

Points (PolyBezierSegment)

Points (Polygon)

Points (Polyline)

Points (PolyLineSegment)

Points (PolyQuadraticBezierSegment)

Position

PressureFactor

RadiusX (EllipseGeometry)

RadiusX (RadialGradientBrush)

RadiusX (Rectangle)

RadiusX (RectangleGeometry)

RadiusY (EllipseGeometry)

RadiusY (RadialGradientBrush)

RadiusY (Rectangle)

RadiusY (RectangleGeometry)

Rect

RelativeTransform

RenderTransform

RenderTransformOrigin

RepeatBehavior

Resources

Root

RotationAngle

RoutedEvent

ScaleX

ScaleY

Seconds (Duration)

Seconds (KeyTime)

Seconds (RepeatBehavior)

Seconds (TimeSpan)

Segments

Shift (KeyboardEventArgs)

Shift (MouseEventArgs)

Size

Source (Image)

Source (MediaElement)

Source (Silverlight Plug-in)

SourceName

SpeedRatio

SpreadMethod (LinearGradientBrush)

SpreadMethod (RadialGradientBrush)

StartPoint (LinearGradientBrush)

StartPoint (LineGeometry)

StartPoint (PathFigure)

Status

StatusText

Storyboard

Stretch (Image)

Stretch (ImageBrush)

Stretch (MediaElement)

Stretch (Shape)

Stretch (VideoBrush)

Stroke

StrokeDashArray

StrokeDashCap

StrokeDashOffset

StrokeEndLineCap

StrokeLineJoin

StrokeMiterLimit

Strokes

StrokeStartLineCap

StrokeThickness

StyleSimulations

StylusPoints

SweepDirection

Tag

TargetName

TargetProperty

Text (TextElement)

Text (TimelineMarker)

TextDecorations

TextWrapping

Time

Title

To (ColorAnimation)

To (DoubleAnimation)

To (PointAnimation)

Transform (Brush)

Transform (Geometry)

Transform (MatrixTransform)

Triggers

Type (TimelineMarker)

UnicodeString

Uri

Value (ColorKeyFrame)

Value (DoubleKeyFrame)

Value (MediaAttribute)

Value (PointKeyFrame)

Visibility

Volume

Width (DrawingAttributes)

Width (Rect)

Width (UIElement)

Windowless

X (Point)

X (Rect)

X (StylusPoint)

X (TranslateTransfrom)

X1

X2

XamlFile

XmlAttribute

XmlElement

Y (Point)

Y (Rect)

Y (StylusPoint)

Y (TranslateTransform)

Y1

Y2

See Also

Silverlight Reference, Silverlight Conceptual Topics


Accessibility Property

Gets an object that contains properties that report accessibility information to the Silverlight plug-in host.

Scripting (Instantiation) | Cannot be set during instantiation.
Scripting (Runtime) | value = silverlightObject.content.Accessibility

Property Value

Accessibility

An object (Accessibility) that holds several accessibility-related strings as well as an event.

This property is read-only (the object itself is not settable). The default value is an instance of the object with its properties at default values.

Remarks

This property is available on the content sub-object of a Silverlight plug-in instance.

This property is set to the initial default during initialization, but values of the Accessibility object cannot be set through the initial creation parameters. For more information, see Using CreateSilverlight.js and Silverlight.js and Accessibility.

Applies To

Silverlight Control

See Also

Accessibility, Title, Accessibility (Overview)


ActionDescription Property

Gets or sets a string that describes the primary method of manipulation for the Silverlight plug-in instance and/or its content from the user's viewpoint.

XAML
Cannot be used in XAML.
Scripting
value = object.ActionDescription
object.ActionDescription = value

Property Value

string

A string that provides a description for the Silverlight plug-in instance and its content.

This property is read-write. The default is an empty string.

Remarks

The ActionDescription property should be a verb or a short verb phrase that hints at possible interaction in the UI. For example, if the Silverlight content area serves the purpose of playing a video trailer, and then hooks up a Canvas-level mouse click event that navigates to a new HTML page, you might report the ActionDescription as "After the video plays, click here for more."

Applies To

Accessibility

See Also


Actions Property

Gets the collection of actions to apply when the event occurs.

XAML
<EventTrigger>
  oneOrMoreBeginStoryboards
</EventTrigger>
Scripting
value = object.Actions
object.Actions = value

Property Value

TriggerActionCollection

A collection of actions to apply when the event occurs

This property is read/write. The default value is an empty collection.

Remarks

You do not typically specify Actions as an explicit property element in XAML, because it is the default collection property of an EventTrigger. You will set the Actions value in XAML by placing one or more BeginStoryboard elements as the child elements of an EventTrigger object element.

Once the collections of actions exists, you can manipulate the collection of actions using the value of the Actions property in scripting. The value will be a TriggerActionCollection, and you can add, remove, clear or query the BeginStoryboard children in that collection.

Applies To

EventTrigger

See Also


ActualHeight Property (Silverlight Plug-in)

Gets the height of the rendering area of the Silverlight plug-in.

Scripting (Instantiation) | Not directly set during instantiation, but influenced by instantiation height value
Scripting (Runtime) | value = silverlightObject.content.ActualHeight

Property Value

integer

The height of the rendering area of the Silverlight plug-in in pixels.

This property is read-only. The default value is the height of the Silverlight plug-in, as specified by the OBJECT/EMBED tag that instantiated it. For more information on how this property is set during initialization, see Using CreateSilverlight.js and Silverlight.js.

Remarks

This property is available on the content sub-object of a Silverlight plug-in instance.

Important In the early stages of the object lifetime of a Silverlight plug-in instance, ActualHeight and ActualWidth do not contain a usable value. The OnLoad event does not yet guarantee a correct value for ActualHeight or ActualWidth. In general, you should check these values in the handler for the OnResize event, which occurs just thereafter.

A Silverlight plug-in can display in either embedded mode or full-screen mode:

  • embedded mode: plug-in displays within the Web browser.
  • full-screen mode: plug-in displays on top of all other applications.

When the Silverlight plug-in is in embedded mode, the value of ActualHeight depends on whether the height of the Silverlight plug-in is a fixed-width or percentage value. The height of the Silverlight plug-in is defined in the OBJECT tag of the containing Web page. If the height of the Silverlight plug-in is a fixed-width value, such as "300", ActualHeight is set to the plug-in height. If the height of the Silverlight plug-in is a percentage value, such as "100%", ActualHeight is set to the most appropriate height for displaying the plug-in in a browser. In this case, resizing the browser window height causes the ActualHeight value to change.

When the application is in full-screen mode, the value of ActualHeight is set to the current vertical resolution of the display.

The OnResize event occurs whenever the ActualHeight and ActualWidth properties change, and the Silverlight plug-in is in embedded mode. When the Silverlight plug-in is in full-screen mode, the OnResize event does not occur.

Examples

The following JavaScript example shows how to use the ActualWidth and ActualHeight properties. In the case where height is defined as a percentage value, the ActualHeight value represents a height value in pixels:

JavaScript
function onResizeStatus(sender, eventArgs)
{
    // Concatenate the size values as a formatted message string.
    var msgString  = " actualWidth: " + slPlugin.content.actualWidth;
        msgString += " actualHeight: " + slPlugin.content.actualHeight;

    // Display an alert dialog box with a formatted message string.
    var textBlock = sender.findName("Status");
    textBlock.text = msgString;
}

Applies To

Silverlight Plug-in

See Also

ActualWidth, OnResize, Using CreateSilverlight.js and Silverlight.js, Resizing a Silverlight Plug-in, Silverlight Full-screen Support


ActualHeight Property (TextBlock)

Gets the rendered height of the TextBlock.

XAML | Cannot be used in XAML.
Scripting | value = object.ActualHeight

Property Value

Double

The rendered height of the TextBlock.

This property is read-only.

Remarks

ActualHeight and ActualWidth specify the rendered height and width of the TextBlock. These properties can be different than the Height and Width properties of the TextBlock. Setting the TextWrapping property affects the ActualHeight and ActualWidth values of the TextBlock. The following diagram shows how the TextWrapping property affects ActualHeight; in both cases the Height was specified as 20.

How TextWrapping affects ActualHeight

Applies To

TextBlock

See Also

Text and Fonts Overview, ActualWidth


ActualWidth Property (Silverlight Plug-in)

Gets the width of the rendering area of the Silverlight plug-in.

Scripting (Instantiation) | Not directly set during instantiation, but influenced by instantiation width value.
Scripting | value = silverlightObject.content.ActualWidth

Property Value

integer

The width of the rendering area of the Silverlight plug-in in pixels.

This property is read-only. The default value is the height of the Silverlight plug-in, as specified by the OBJECT/EMBED tag that instantiated it. If height was specified by percentage during initialization this is a calculated pixel value. For more information on how this property is set during plug-in initialization, see Using CreateSilverlight.js and Silverlight.js.

Remarks

This property is available on the content sub-object of a Silverlight plug-in instance.

Important In the early stages of the object lifetime of a Silverlight plug-in instance, ActualHeight and ActualWidth do not contain a usable value. The OnLoad event does not yet guarantee a correct value for ActualHeight or ActualWidth. In general, you should check these values in the handler for the OnResize event, which occurs just thereafter.

A Silverlight plug-in can display in either embedded mode or full-screen mode:

  • embedded mode: plug-in displays within the Web browser.
  • full-screen mode: plug-in displays on top of all other applications.

When the Silverlight plug-in is in embedded mode, the value of ActualWidth depends on whether the width of the Silverlight plug-in is specified as a fixed-width or percentage value. The width of the Silverlight plug-in is defined in the OBJECT tag of the containing Web page. If the width of the Silverlight plug-in is a fixed-width value, such as "400", ActualWidth is set to the plug-in width. If the width of the Silverlight plug-in is a percentage value, such as "100%", ActualWidth is set to the most appropriate width for displaying the plug-in in the browser. In this case, resizing the browser window width causes the ActualWidth value to change.

When the application is in full-screen mode, the value of ActualWidth is set to the current horizontal resolution of the display.

The OnResize event occurs whenever the ActualHeight and ActualWidth properties change, and the Silverlight plug-in is in embedded mode. When the Silverlight plug-in is in full-screen mode, the OnResize event does not occur.

Examples

The following JavaScript example shows how to use the ActualWidth and ActualHeight properties. In the case where width is defined as a percentage value, the ActualWidth value represents a width value in pixels:

JavaScript
function onResizeStatus(sender, eventArgs)
{
    // Concatenate the size values as a formatted message string.
    var msgString  = " actualWidth: " + slPlugin.content.actualWidth;
        msgString += " actualHeight: " + slPlugin.content.actualHeight;

    // Display an alert dialog box with a formatted message string.
    var textBlock = sender.findName("Status");
    textBlock.text = msgString;
}

Applies To

Silverlight Plug-in

See Also

ActualHeight, OnResize, Using CreateSilverlight.js and Silverlight.js, Resizing a Silverlight Plug-in, Silverlight Full-screen Support


ActualWidth Property (TextBlock)

Gets the rendered width of the TextBlock.

XAML | Cannot be used in XAML.
Scripting | value = object.ActualWidth

Property Value

Double

The rendered width of the TextBlock.

This property is read-only.

Remarks

ActualHeight and ActualWidth reflect the rendered height and width of the TextBlock. These properties can be different than the Height and Width properties of the TextBlock. Setting the TextWrapping property affects the ActualHeight and ActualWidth values of the TextBlock. The following diagram shows how the TextWrapping property affects ActualWidth.

How TextWrapping affects ActualWidth

Applies To

TextBlock

See Also

Text and Fonts Overview, ActualHeight


AlignmentX Property (ImageBrush)

Gets or sets the horizontal alignment of images in the ImageBrush.

XAML
<object AlignmentX="AlignmentX" .../>
Scripting
value = object.AlignmentX
object.AlignmentX = value

Property Value

AlignmentX

A value that specifies the horizontal position of the image when applied to the brush.

This property is read/write. The default value is Center.

Applies To

ImageBrush

See Also

Silverlight Brushes Overview


AlignmentX Property (VideoBrush)

Gets or sets the horizontal alignment of the video from the VideoBrush.

XAML
<object AlignmentX="AlignmentX" .../>
Scripting
value = object.AlignmentX
object.AlignmentX = value

Property Value

AlignmentX

A value that specifies the horizontal position of the video when applied to the brush.

This property is read/write. The default value is Center.

Applies To

VideoBrush

See Also

Silverlight Brushes Overview, Silverlight VideoBrush Overview


AlignmentY Property (ImageBrush)

Gets or sets the vertical alignment of images in the ImageBrush.

XAML
<object AlignmentY="AlignmentY" .../>
Scripting
value = object.AlignmentY
object.AlignmentY = value

Property Value

AlignmentY

A value that specifies the vertical position of the image.

This property is read/write. The default value is Center.

Applies To

ImageBrush

See Also

Silverlight Brushes Overview


AlignmentY Property (VideoBrush)

Gets or sets the vertical alignment of the video from the VideoBrush.

XAML
<object AlignmentY="AlignmentY" .../>
Scripting
value = object.AlignmentY
object.AlignmentY = value

Property Value

AlignmentY

A value that specifies the vertical position of the video.

This property is read/write. The default value is Center.

Applies To

VideoBrush

See Also

Silverlight Brushes Overview, Silverlight VideoBrush Overview


Angle Property

Gets or sets the angle, in degrees, of rotation for this transform.

XAML
<object Angle="Double" .../>
Scripting
value = object.Angle
object.Angle = value

Property Value

Double

The angle, in degrees, of rotation.

This property is read/write. The default value is 0.

Remarks

The local 0,0 for an object can be offset on a Canvas using Canvas.Left and Canvas.Top, but this does not count as a transform; the object retains its own local 0,0 in this case for transform purposes. For details on this concept, see Object Layout in Silverlight.

When you use a RotateTransform, using the default values of 0 for CenterX and CenterY, the transform rotates the coordinate system for a particular object around its local 0,0. Therefore, depending on the position of the object and other applied transforms, it might not rotate in place (around its center). For example, if an object is already transformed 200 units from 0 along the x-axis, a rotation of 30 degrees can swing the object 30 degrees along a circle that has a radius of 200, which is drawn around its local 0,0. To rotate an object in place, set the CenterX and CenterY of the RotateTransform to the center of the object to rotate.

Positive values are interpreted as clockwise rotation. Negative values are interpreted as counterclockwise rotation.

Applies To

RotateTransform

See Also

Silverlight Transforms Overview, Object Layout in Silverlight


AngleX Property

Gets or sets the x-axis skew angle, which is measured in degrees counterclockwise from the y-axis.

XAML
<object AngleX="Double" .../>
Scripting
value = object.AngleX
object.AngleX = value

Property Value

Double

The skew angle, which is measured in degrees counterclockwise from the y-axis.

This property is read/write. The default value is 0.

Remarks

To skew an object in place, set the CenterX and CenterY properties to the object's center point.

The local origin (0,0) for an object can be offset on a Canvas using Canvas.Left and Canvas.Top, but this does not count as a transform; the object retains its own local origin in this case for transformation purposes. For details on this concept, see Object Layout in Silverlight.

Positive values are interpreted as counterclockwise skew. Negative values are interpreted as clockwise skew. For values less than -360 or greater than 360, the values will wrap around and be treated as if the mathematical operation (mod 360) was applied.

The following illustration shows three examples of a SkewTransform applied to a Rectangle.

Applies To

SkewTransform

See Also

Silverlight Transforms Overview


AngleY Property

Silverlight SDK

AngleY Propert

Gets or sets the y-axis skew angle, which is measured in degrees counterclockwise from the x-axis.

XAML
<object AngleY="Double" .../>
Scripting
value = object.AngleY
object.AngleY = value

Property Value

Double

The skew angle, which is measured in degrees counterclockwise from the x-axis.

This property is read/write. The default value is 0.

Remarks

To skew an object in place, set the CenterX and CenterY properties to the object's center point.

The local origin (0,0) for an object can be offset on a Canvas using Canvas.Left and Canvas.Top, but this does not count as a transform; the object retains its own local origin in this case for transformation purposes. For details on this concept, see Object Layout in Silverlight.

Positive values are interpreted as counterclockwise skew. Negative values are interpreted as clockwise skew. For values less than -360 or greater than 360, the values will wrap around and be treated as if the mathematical operation (mod 360) was applied.

The following illustration shows three examples of a SkewTransform applied to a Rectangle.

Applies To

SkewTransform

See Also

Silverlight Transforms Overview


Attributes Property

Gets the collection of MediaAttribute objects that corresponds to the current entry in the ASX file that Source is set to.

XAML | Cannot be used in XAML.
Scripting | value = object.Attributes

Property Value

MediaAttributeCollection

The collection of MediaAttribute objects.

This property is read-only.

Examples

The following JavaScript example shows how to retrieve the Attributes property of a MediaElement that has a Source property set to an ASX playlist file. The retrieved MediaAttributeCollection is iterated through and the Name and Value properties of each MediaAttribute is displayed.

JavaScript
    // Get the MediaElement name MediaPlayer.
    player = sender.findName("MediaPlayer");

    // The display message.
    var msg;
    msg =  "MediaElement Source: " + player.source + "\n\n";
    msg += "Attributes: \n";

    // Variable to hold the MediaAttribute.
    var attribute;

    // Iterate through the collection of MediaAttributes.
    var loop = 0;
    while(loop < player.Attributes.count)
    {
        // Get the current Attribute.
        attribute = player.Attributes.getItem(loop);

        msg += "Name: "  + attribute.Name + "\n";
        msg += "Value: " + attribute.Value + " \n\n";
        loop++;
    }

    // Display the MediaAttribute information.
    alert(msg);
}

Applies To

MediaElement

See Also

Media Overview


AudioStreamCount Property

Gets the number of audio streams available in the current media file.

XAML | You cannot set this property in XAML.
Scripting | value = object.AudioStreamCount

Property Value

integer

The number of audio streams that exist in the source media file.

This property is read-only. The default value is 0.

Remarks

The

AudioStreamCount

property value is only valid after the MediaOpened event has been raised.

AudioStreamIndex and AudioStreamCount both specifically refer to a collection of only audio streams. This collection is composed locally at runtime. If you were to examine the actual media, the audio streams might be interleaved with nonaudio stream types, but these other streams will not be part of the collection.

Applies To

MediaElement

See Also

MediaOpened, Source (MediaElement), AudioStreamIndex Media Overview, Supported Media Formats and Protocols


AudioStreamIndex Property

Gets or sets the index of the audio stream that plays along with the video component. The collection of audio streams is composed at runtime, and represents all audio streams available within the media file.

XAML
<object AudioStreamIndex="integer" .../>
Scripting
value = object.AudioStreamIndex
object.AudioStreamIndex = value

Property Value

integer

The index within the media file of the audio component that plays along with the video component. The index can be unspecified, in which case the value is null.

This property is read/write. The default value is null; see Remarks.

Remarks

If no audio stream index is specifically set, the value of this property is null. A null value means that the media file uses the default audio stream.

If you have previously set AudioStreamIndex to an index value, you can set the value back to null. The behavior is that the initial default audio stream value is cached, and that audio stream will resume.

AudioStreamIndex and AudioStreamCount both specifically refer to a collection of only audio streams. This collection is composed locally at runtime. If you were to examine the actual media, the audio streams might be interleaved with nonaudio stream types, but these other streams will not be part of the collection.

This property can be set in XAML in order to indicate a preference. The value only becomes relevant after MediaOpened is raised.

Applies To

MediaElement

See Also

MediaOpened, Source (MediaElement), Media Overview, Supported Media Formats and Protocols


AutoPlay Property

Gets or sets a value that indicates whether media will begin playback automatically when the Source property is set.

XAML
<object AutoPlay="Boolean" .../>
Scripting
value = object.AutoPlay
object.AutoPlay = value

Property Value

Boolean

true if playback is automatic; otherwise, false.

This property is read/write. The default value is true.

Remarks

In script, set this property to false before setting the Source property to pause the media at load time. Call the Play method to start media playback. When opened, the media will be in Stopped state.

Applies To

MediaElement

See Also

MediaOpened, Source (MediaElement), Media Overview, Supported Media Formats and Protocols


AutoReverse Property

Gets or sets a value that indicates whether the timeline plays in reverse after it completes a forward iteration.

XAML
<object AutoReverse="Boolean" .../>
Scripting
value = object.AutoReverse
object.AutoReverse = value

Property Value

Boolean

true if the timeline plays in reverse at the end of each iteration; otherwise, false.

This property is read/write. The default value is false.

Remarks

If the AutoReverse property is set to true, the timeline plays for twice the length of time specified by its Duration property.

Applies To

ColorAnimation, ColorAnimationUsingKeyFrames, DoubleAnimation, DoubleAnimationUsingKeyFrames, PointAnimation, PointAnimationUsingKeyFrames, Storyboard

See Also

Animation Overview


Background Property (Canvas)

Gets or sets the Brush that describes the background of the object.

XAML
<object Background="Brush" .../>
-or-
<object>
  <object.Background>
    <Brush" .../>
  </object.Background>
</object>
Scripting
value = object.Background
object.Background = value

Property Value

Brush

The brush that is used to fill the background of the object. If either the object's Height or Width property values are equal to 0, the Background property value is ignored.

This property is read/write. The default value is null.

Remarks

The Background property of the Silverlight plug-in determines the background color of the client area underneath your Silverlight content, whereas this Background property determines the background color of a Canvas.

The Background property specifies a Brush for the object. A Brush can represent a solid color, a linear or radial gradient, or an image.

Some brush types (SolidColorBrush) support a XAML attribute syntax, whereas other brush types (ImageBrush, LinearGradientBrush, RadialGradientBrush) only support an object element syntax. This is why two versions of XAML syntax are shown for this property.

When animating a Background, you must use indirect targeting. For instance, if you are animating the color of a SolidColorBrush that is the Background of a Canvas, the syntax would be <ColorAnimation ... Storyboard.TargetProperty="(Canvas.Background).(SolidColorBrush.Color)" />.

InkPresenter is a derived class of Canvas and inherits its Background property. The Background for an InkPresenter is applied behind any strokes that are presented on the surface.

Examples

The following XAML example shows how to define a LinearGradientBrush object that is used as the Background property value for the Canvas object:

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Width="200" Height="80"
  >

  <!-- Define a LinearGradientBrush for the Canvas Background property. -->
  <Canvas.Background>
    <LinearGradientBrush>
      <GradientStop Color="Yellow" Offset="0.0" />
      <GradientStop Color="Orange" Offset="0.5" />
      <GradientStop Color="Red" Offset="1.0" />
    </LinearGradientBrush>
  </Canvas.Background>
</Canvas>

The XAML content of the previous example is displayed using a LinearGradientBrush object.

Canvas object rendered with a LinearGradientBrush

Applies To

Canvas, InkPresenter

See Also

Brush, Canvas, Background (Silverlight Plug-in)


Background Property (Silverlight Plug-in)

Gets or sets the background color of the rectangular region that display XAML content.

Scripting (Instantiation)
Silverlight.CreateObject(,,,{background:'colorValue'})

-or-

Silverlight.CreateObjectEx({properties:{background:'colorValue'}})
Scripting (Runtime)
value = silverlightObject.settings.Background
silverlightObject.settings.Background = value

Property Value

Color

Specifies the background color value as a string, which can either be a named color value, or an 8-bit or 16-bit color value, with or without alpha transparency.

Type of Color Value | Example | Description
Color Name | "Teal" | A named color value. For a listing of color names, see the Remarks section in Color.
8 Bit RGB | "#RGB" | An 8-bit RGB value.
8 Bit RGB + Alpha | "#ARGB" | An 8-bit RGB value with alpha transparency.
16 Bit RGB | "#RRGGBB" | A 16-bit RGB value. For a listing of hexadecimal equivalents for color names, see the Remarks section in Color.
16 Bit RGB + Alpha | "#AARRGGBB" | A 16-bit RGB value with alpha transparency. For a listing of hexadecimal equivalents for color names, see the Remarks section in Color.

This property is read/write. The default value is null, which is equivalent to the named color "White". For more information on how this property is set during plug-in initialization, see Using CreateSilverlight.js and Silverlight.js.

Remarks

This property is available on the settings sub-object of a Silverlight plug-in instance.

If the Windowless property is set to true, or on Macintosh (where the window-less mode is always active regardless of the Windowless setting) the Background property value can specify an alpha value for the color. The color value is then blended with the HTML page.

Important Setting an alpha channel value for full or partial transparency has possible performance consequences, particularly on certain client environments. See Performance Tips.

Consider the following JavaScript examples in which the two Silverlight plug-ins are defined in CreateSilverlight.js--the first one with the isWindowless initialization parameter set to false; the second, with isWindowless set to true:

JavaScript
isWindowless:'false',       // Display as windowed.
background:'#80008080',     // Background color of plug-in (alpha + RGB).

JavaScript
isWindowless:'true',       // Display as window-less.
background:'#80008080',    // Background color of plug-in (alpha + RGB).

Notice the displayed output of the preceding plug-in initializations. The background of the first Silverlight plug-in area is opaque. The background of the second Silverlight plug-in are is blended with the background image of the HTML page.

Windowless property set on two Silverlight plug-ins

Applies To

Silverlight Plug-in

See Also

Using a Silverlight Plug-in, Using CreateSilverlight.js and Silverlight.js, Color, Windowless


Balance Property

Gets or sets the ratio of volume across stereo speakers.

XAML
<object Balance="Double" .../>
Scripting
value = object.Balance
object.Balance = value

Property Value

Double

The ratio of volume across speakers in the range between -1 and 1.

This property is read/write. The default value is 0.

Remarks

A value of -1 represents 100 percent volume in the left-side speakers, and a value of 1 represents 100 percent volume in the right-side speakers. 0 indicates that the volume is evenly distributed between left and right speakers.

Applies To

MediaElement

See Also

MediaOpened, Source (MediaElement), Media Overview, Supported Media Formats and Protocols


BeginTime Property

Gets or sets the time at which this Timeline should begin.

XAML
<object BeginTime="TimeSpan" .../>
Scripting
value = object.BeginTime
object.BeginTime = value

Property Value

TimeSpan

The start time of the time line.

This property is read/write. The default value is null, which corresponds to a value of 0.

Remarks

See TimeSpan for the string format you use to specify a BeginTime value. Creating a TimeSpan in XAML is only possible through a type conversion syntax when setting a property that takes a TimeSpan as an attribute string.

You can set the BeginTime value in script using object.BeginTime="durationstring" syntax. You must use a quoted string, which then uses the same type conversion behavior as the XAML attribute syntax. You can set the value on a running animation, and the value will apply the next time the same animation is started. You can get the BeginTime value in script using value=object.BeginTime syntax. However, if the BeginTime for an animation is not explicitly set (either through scripting or XAML), then the value of object.BeginTime will be null. A null value for BeginTime has the same implied effect on an animation as does a TimeSpan explicitly set to "0".

Applies To

ColorAnimation, ColorAnimationUsingKeyFrames, DoubleAnimation, DoubleAnimationUsingKeyFrames, PointAnimation, PointAnimationUsingKeyFrames, Storyboard

See Also

Animation Overview


BufferingProgress Property

Gets a value that indicates the current buffering progress.

XAML | Cannot be used in XAML.
Scripting | value = object.BufferingProgress

Property Value

Double

The amount of buffering completed for media content. The value ranges from 0 to 1. Multiply by 100 to obtain a percentage.

This property is read-only. The default value is 0.

Remarks

The BufferingProgressChanged event occurs whenever the BufferingProgress property is updated by 0.05 or more, or reaches 1.0.

Applies To

MediaElement

See Also

Media Overview, Using a Downloader Object


BufferingTime Property

Gets or sets the amount of time to buffer.

XAML
<object BufferingTime="TimeSpan" .../>
Scripting
value = object.BufferingTime
object.BufferingTime = value

Property Value

TimeSpan

The amount of time to buffer. The default value is 5 seconds (0:0:05).

This property is read/write.

Remarks

The string format for specifying a TimeSpan is [days.]hours:minutes:seconds[.fractionalSeconds]. See TimeSpan. Creating a TimeSpan in XAML is only possible through a type conversion syntax when setting a property such as BufferingTime that takes a TimeSpan as an attribute string. Creating a TimeSpan in script also uses the type conversion syntax by setting BufferingTime with a properly formatted string.

Applies To

MediaElement

See Also

Media Overview, Supported Media Formats and Protocols


By Property (ColorAnimation)

Gets or sets the total amount by which the animation changes its starting value.

XAML
<object By="Color" .../>
Scripting
value = object.By
object.By = value

Property Value

Color

The total amount by which the animation changes its starting value.

This property is read/write. The default value is null.

Remarks

See Color for details on the various string formats that can be used to specify a color either in XAML or script.

Use the By property when you want to animate a value "by" a certain amount, rather than specifying a starting or ending value. You may also use the By property with the From property. The following table summarizes how the From, To, and By properties may be used together or separately to determine an animation's target values.

Properties Specified | Resulting Behavior
From | The animation progresses from the value specified by the From property to the base value of the property being animated.
From and To | The animation progresses from the value specified by the From property to the value specified by the To property.
From and By | The animation progresses from the value specified by the From property to the value specified by the sum of the From and By properties.
To | The animation progresses from the animated property's base value or a previous animation's output value to the value specified by the To property.
By | The animation progresses from the base value of the property being animated or a previous animation's output value to the sum of that value and the value specified by the By property.

Note If you set both the To and By properties, the To property takes precedence and the By property is ignored.

To use other interpolation methods or animate between more than two target values, use a ColorAnimationUsingKeyFrames object.

Applies To

ColorAnimation, ColorAnimationUsingKeyFrames

See Also

Animation Overview


By Property (DoubleAnimation)

Gets or sets the total amount by which the animation changes its starting value.

XAML
<object By="Double" .../>
Scripting
value = object.By
object.By = value

Property Value

Double

The total amount by which the animation changes its starting value.

This property is read/write. The default value is null.

Remarks

Use the By property when you want to animate a value "by" a certain amount, rather than specifying a starting or ending value. You may also use the By property with the From property.

The following table summarizes how the From, To, and By properties may be used together or separately to determine an animation's target values.

Properties specified | Resulting behavior
From | The animation progresses from the value specified by the From property to the base value of the property being animated.
From and To | The animation progresses from the value specified by the From property to the value specified by the To property.
From and By | The animation progresses from the value specified by the From property to the value specified by the sum of the From and By properties.
To | The animation progresses from the animated property's base value or a previous animation's output value to the value specified by the To property.
By | The animation progresses from the base value of the property being animated or a previous animation's output value to the sum of that value and the value specified by the By property.

Note If you set both the To and By properties, the To property takes precedence and the By property is ignored.

To use other interpolation methods or animate between more than two target values, use a DoubleAnimationUsingKeyFrames object.

Applies To

DoubleAnimation, DoubleAnimationUsingKeyFrames

See Also

Animation Overview


By Property (PointAnimation)

Gets or sets the total amount by which the animation changes its starting value.

XAML
<object By="Point" .../>
Scripting
value = object.By
object.By = value

Property Value

Point

The total amount by which the animation changes its starting value.

This property is read/write. The default value is null.

Remarks

The Point structure parallels a convention that is supported by a type converter, such that properties that take a Point as their value can specify a Point as a formatted string. The type converter generates a new Point value based on processing the string. The type converter functions both for XAML usages and script usages. In both cases, you supply a quoted string. The format of that string is an X,Y value pair. Alternatively, you can use a space rather than a comma as the delimiter betweeen X and Y in the string.

See remarks in Point for details on scripting usages. The properties of PointAnimation are one of the cases where the object model provides access to an actual Point as a return value if you get this property at runtime. This means that you can potentially use the X and Y properties of the returned Point to adjust the animation either before it runs or while it runs.

Use the By property when you want to animate a value "by" a certain amount, rather than specifying a starting or ending value. You may also use the By property with the From property. The following table summarizes how the From, To, and By properties may be used together or separately to determine an animation's target values.

Properties Specified | Resulting Behavior
From | The animation progresses from the value specified by the From property to the base value of the property being animated.
From and To | The animation progresses from the value specified by the From property to the value specified by the To property.
From and By | The animation progresses from the value specified by the From property to the value specified by the sum of the From and By properties.
To | The animation progresses from the animated property's base value or a previous animation's output value to the value specified by the To property.
By | The animation progresses from the base value of the property being animated or a previous animation's output value to the sum of that value and the value specified by the By property.

Note If you set both the To and By properties, the To property takes precedence and the By property is ignored.

To use other interpolation methods or animate between more than two target values, use a PointAnimationUsingKeyFrames object.

Applies To

PointAnimation, PointAnimationUsingKeyFrames

See Also

PointAnimation, Animation Overview


CanPause Property

Gets a value indicating if media can be paused if the Pause method is called.

XAML | Cannot be used in XAML.
Scripting | value = object.CanPause

Property Value

Boolean

true if the media can be paused; otherwise, false.

This property is read-only. The default value is false.

Remarks

Streaming media cannot be paused. Therefore CanPause returns false for any case where the MediaElement has loaded streaming media.

Calling Pause on a MediaElement that has opened and is playing streaming content does not throw an error. Instead the method call is ignored.

One scenario for this property is to check it after MediaOpened is fired, and potentially change the display characteristics of any "Pause" button that appears in UI if CanPause is false.

Applies To

MediaElement

See Also

Media Overview, Supported Media Formats and Protocols


CanSeek Property

Gets a value indicating if media can be repositioned by setting the value of the Position property.

XAML | Cannot be used in XAML.
Scripting | value = object.CanSeek

Property Value

Boolean

true if the media can be repositioned; otherwise, false.

This property is read-only. The default value is false.

Remarks

Live streaming media cannot be paused. Therefore CanSeek returns false for any case where the MediaElement has loaded live streaming media.

Setting Position on a MediaElement that has opened and is playing streaming content does not throw an error. Instead the method call is ignored.

One scenario for this property is to check it after MediaOpened is fired, and potentially change the display characteristics of any "Scrub" control appears in UI if CanSeek is false.

Applies To

MediaElement

See Also

Media Overview, Supported Media Formats and Protocols


Canvas.Left Property

Gets or sets a value that represents the distance between the left side of an element and the left side of its parent Canvas.

XAML
<object Canvas.Left="Double" .../>
Scripting
value = object["Canvas.Left"]
object["Canvas.Left"] = value

Property Value

Double

A value that represents the offset position from the left side of a parent Canvas.

This property is read/write. The default value is 0.

Remarks

Negative values are permitted. A negative value will place the origin of the element where Canvas.Left is applied offscreen to the left side of the content area.

This property is an example of an attached property, whereby non-Canvas objects can set this property that can then be read and interpreted by a parent Canvas .

Notice particularly the script syntax, which resembles an indexer or array syntax. The ["ownerType.propertyName"] form (with no dot separating this property form and the target object for getting or setting) is necessary to get or set an attached property such as Canvas.Left in script.

The value is interpreted by any immediate parent Canvas. If there are nested canvas elements, values for Canvas.Left that do not come from immediate child elements are ignored. A Canvas can itself have a Canvas.Left value, but the value does not apply on itself, rather it is interpreted by any parent Canvas, as in the nested scenario mentioned.

Canvas.Left or Canvas.Top values on the root canvas are ignored and are not used for positioning by the Silverlight plug-in's content area.

For more details on object positioning and how Canvas.Left participates, see Object Layout in Silverlight.

Applies To

Canvas, Ellipse, Glyphs, Image, InkPresenter, Line, MediaElement, Path, Polygon, Polyline, Rectangle, TextBlock

See Also

Canvas.Top, Canvas.ZIndex, Object Layout in Silverlight, Silverlight Transforms Overview


Canvas.Top Property

Gets or sets a value that represents the distance between the top of an element and the top of its parent Canvas.

XAML
<object Canvas.Top="Double" .../>
Scripting
value = object["Canvas.Top"]
object["Canvas.Top"] = value

Property Value

Double

A value that represents the offset position from the top of a parent Canvas.

This property is read/write. The default value is 0.

Remarks

Negative values are permitted. A negative value will place the origin of the element where Canvas.Top is applied offscreen to the top side of the content area.

This property is an example of an attached property, whereby non-Canvas objects can set this property that can then be read and interpreted by a parent Canvas .

Notice particularly the script syntax, which resembles an indexer or array syntax. The ["ownerType.propertyName"] form (with no dot separating this property form and the target object for getting or setting) is necessary to get or set an attached property such as Canvas.Top in script.

The value is interpreted by any immediate parent Canvas. If there are nested canvas elements, values for Canvas.Top that do not come from immediate child elements are ignored. A Canvas can itself have a Canvas.Top value, but the value does not apply on itself, rather it is interpreted by any parent Canvas, as in the nested scenario mentioned.

Canvas.Left or Canvas.Top values on the root canvas are ignored and are not used for positioning by the Silverlight plug-in's content area.

For more details on object positioning and how Canvas.Top participates, see Object Layout in Silverlight.

Applies To

Canvas, Ellipse, Glyphs, Image, InkPresenter, Line, MediaElement, Path, Polygon, Polyline, Rectangle, TextBlock

See Also

Canvas.Left, Canvas.ZIndex, Object Layout in Silverlight, Silverlight Transforms Overview


Canvas.ZIndex Property

Gets or sets a value that represents the z-order rendering behavior of objects in a collection.

XAML
<object Canvas.ZIndex="integer" .../>
Scripting
value = object["Canvas.ZIndex"]
object["Canvas.ZIndex"] = value

Property Value

integer

A value that represents the z-order of the object within the collection.

This property is read/write. The default value is 0.

Remarks

The value of the Canvas.ZIndex property is expressed as any numeric value, positive or negative. Although you can specify the value as a Double, internally the value will be converted to and treated as an integer.

Elements with higher values for Canvas.ZIndex will render on top of elements with a lower ZIndex. The general effect of Canvas.ZIndex is to potentially override the default rendering order that is determined by the order of elements in a collection.

You can also set the Canvas.ZIndex value to a negative value, such as "-99", which places the object even farther from the foreground. Canvas.ZIndex values are aligned along the z-axis -- higher values are closer to the foreground; lower values are farther from the foreground. The following diagram shows the relationship of z-order to z-axis.

Relationship of z-order to z-axis

Examples

The following XAML example shows how to define two sets of Rectangle objects. The second set of rectangles sets the Canvas.ZIndex property to invert the z-order:

XAML
<!-- Render rectangles using default z-order (position within the collection). -->
<Canvas>
  <Rectangle
    Fill="Maroon" Canvas.Top="20" Canvas.Left="20" Height="100" Width="100" />
  <Rectangle
    Fill="LightBlue" Canvas.Top="40" Canvas.Left="40" Height="100" Width="100" />
  <Rectangle
    Fill="Teal" Canvas.Top="60" Canvas.Left="60" Height="100" Width="100" />
</Canvas>

<!-- Render rectangles using explicit z-order by using Canvas.ZIndex. -->
<Canvas Canvas.Left="200">
  <Rectangle
    Canvas.ZIndex="2"
    Fill="Maroon" Canvas.Top="20" Canvas.Left="20" Height="100" Width="100" />
  <Rectangle
    Canvas.ZIndex="1"
    Fill="LightBlue" Canvas.Top="40" Canvas.Left="40" Height="100" Width="100" />
  <Rectangle
    Canvas.ZIndex="0"
    Fill="Teal" Canvas.Top="60" Canvas.Left="60" Height="100" Width="100" />
</Canvas>

The following image displays the result of the previous XAML content example:

Changing the z-order of objects within a collection

The first set of Rectangle objects uses the default z-order rendering of objects, which is based on the position of the child object in the Canvas collection. The first object in the collection is rendered first, then the second object, and so forth. The second set of Rectangle objects uses the Canvas.ZIndex property to override the default z-ordering of objects in the collection.

In the second set of Rectangle objects, the first object (the Maroon-colored one) is the highest in the z-order, or closest to the foreground. Its Canvas.ZIndex value is "2", a purely arbitrary value. What is more important is that the value must be greater than any other child object Canvas.ZIndex value in the Canvas collection. If you do not explicitly set the Canvas.ZIndex value, it defaults to 0.

Applies To

Canvas, Ellipse, Glyphs, Image, InkPresenter, Line, MediaElement, Path, Polygon, Polyline, Rectangle, TextBlock

See Also

Referencing and Modifying Silverlight Objects, Canvas.Left, Canvas.Top


Center Property (EllipseGeometry)

Gets or sets the center point of the EllipseGeometry.

XAML
<object Center="Point" .../>
Scripting
value = object.Center
object.Center = value

Property Value

Point

The center point of the EllipseGeometry.

This property is read/write. The default value is 0,0.

Remarks

See remarks in Point for scripting usages of this property.

Applies To

EllipseGeometry

See Also

Point, Silverlight Geometries Overview


Center Property (RadialGradientBrush)

Gets or sets the center of the outermost circle of the radial gradient.

XAML
<object Center="Point" .../>
Scripting
value = object.Center
object.Center = value

Property Value

Point

The two-dimensional point located at the center of the radial gradient.

This property is read/write. The default value is 0.5,0.5.

Remarks

The default central point location of the gradient circle is (0.5, 0.5).

See remarks in Point for scripting usages of this property.

Specifying Relative or Absolute Values

The MappingMode property of a RadialGradientBrush determines whether its coordinate properties are interpreted as a relative or absolute value. By default, Center is treated as relative, which corresponds to a MappingMode of RelativeToBoundingBox. A MappingMode of Absolute specifies that the Center value is expressed in device independent pixels, not as a factor within the bounding box of the area where the brush is applied.

Examples

The following XAML example shows some RadialGradientBrush attribute usages.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <!-- This rectangle is painted with a radial gradient. -->
  <Rectangle Width="200" Height="100">
    <Rectangle.Fill>
      <RadialGradientBrush GradientOrigin="0.5,0.5" Center="0.5,0.5"
        RadiusX="0.5" RadiusY="0.5">
        <GradientStop Color="Yellow" Offset="0" />
        <GradientStop Color="Red" Offset="0.25" />
        <GradientStop Color="Blue" Offset="0.75" />
        <GradientStop Color="LimeGreen" Offset="1" />
      </RadialGradientBrush>
    </Rectangle.Fill>
  </Rectangle>

</Canvas>

Applies To

RadialGradientBrush

See Also

LinearGradientBrush, Silverlight Brushes Overview


CenterX Property (RotateTransform)

Gets or sets the x-coordinate of the rotation center point.

XAML
<object CenterX="Double" .../>
Scripting
value = object.CenterX
object.CenterX = value

Property Value

Double

The x-coordinate of the center of rotation.

This property is read/write. The default value is 0.

Remarks

The local 0,0 for an object can be offset on a Canvas using Canvas.Left and Canvas.Top, but this does not count as a transform; the object retains its own local 0,0 in this case for transform purposes. For details on this concept, see Object Layout in Silverlight.

When you use a RotateTransform, using the default values of 0 for CenterX and CenterY, the transform rotates the coordinate system for a particular object around its local 0,0. Therefore, depending on the position of the object and other applied transforms, it might not rotate in place (around its center). For example, if an object is already transformed 200 units from 0 along the x-axis, a rotation of 30 degrees can swing the object 30 degrees along a circle that has a radius of 200, which is drawn around its local 0,0. To rotate an object in place, set the CenterX and CenterY of the RotateTransform to the center of the object to rotate.

Applies To

RotateTransform

See Also

Silverlight Transforms Overview, Object Layout in Silverlight, CenterY


CenterX Property (ScaleTransform)

Gets or sets the x-coordinate of the center point of this ScaleTransform.

XAML
<object CenterX="Double" .../>
Scripting
value = object.CenterX
object.CenterX = value

Property Value

Double

The x-coordinate of the center point of the ScaleTransform.

This property is read/write. The default value is 0.

Remarks

The local origin (0,0) for an object can be offset on a Canvas using Canvas.Left and Canvas.Top, but this does not count as a transform; the object retains its own local origin in this case for transformation purposes. For details on this concept, see Object Layout in Silverlight.

Applies To

ScaleTransform

See Also

Silverlight Transforms Overview, Object Layout in Silverlight


CenterX Property (SkewTransform)

Gets or sets the x-coordinate of the transform center.

XAML
<object CenterX="Double" .../>
Scripting
value = object.CenterX
object.CenterX = value

Property Value

Double

The x-coordinate of the transform center.

This property is read/write. The default value is 0.

Remarks

To skew an object in place, set the CenterX and CenterY properties to the object's center point.

The local origin (0,0) for an object can be offset on a Canvas using Canvas.Left and Canvas.Top, but this does not count as a transform; the object retains its own local origin in this case for transformation purposes. For details on this concept, see Object Layout in Silverlight.

The following illustration shows three examples of a SkewTransform applied to a Rectangle.

Applies To

SkewTransform

See Also

Silverlight Transforms Overview


CenterY Property (RotateTransform)

Gets or sets the y-coordinate of the rotation center point.

XAML
<object CenterY="Double" .../>
Scripting
value = object.CenterY
object.CenterY = value

Property Value

Double

The y-coordinate of the center of rotation.

This property is read/write. The default value is 0.

Remarks

The local 0,0 for an object can be offset on a Canvas using Canvas.Left and Canvas.Top, but this does not count as a transform; the object retains its own local 0,0 in this case for transform purposes. For details on this concept, see Object Layout in Silverlight.

When you use a RotateTransform, using the default values of 0 for CenterX and CenterY, the transform rotates the coordinate system for a particular object around its local 0,0. Therefore, depending on the position of the object and other applied transforms, it might not rotate in place (around its center). For example, if an object is already transformed 200 units from 0 along the x-axis, a rotation of 30 degrees can swing the object 30 degrees along a circle that has a radius of 200, which is drawn around its local 0,0. To rotate an object in place, set the CenterX and CenterY of the RotateTransform to the center of the object to rotate.

Applies To

RotateTransform

See Also

Silverlight Transforms Overview, Object Layout in Silverlight, CenterX


CenterY Property (ScaleTransform)

Gets or sets the y-coordinate of the center point of this ScaleTransform.

XAML
<object CenterY="Double" .../>
Scripting
value = object.CenterY
object.CenterY = value

Property Value

Double

The y-coordinate of the center point of this ScaleTransform.

This property is read/write. The default value is 0.

Remarks

The local origin (0,0) for an object can be offset on a Canvas using Canvas.Left and Canvas.Top, but this does not count as a transform; the object retains its own local origin in this case for transformation purposes. For details on this concept, see Object Layout in Silverlight.

Applies To

ScaleTransform

See Also

Silverlight Transforms Overview, Object Layout in Silverlight


CenterY Property

Silverlight SDK

CenterY Property (SkewTransform)

Gets or sets the y-coordinate of the transform center.

XAML
<object CenterY="Double" .../>
Scripting
value = object.CenterY
object.CenterY = value

Property Value

Double

The y-coordinate of the transform center.

This property is read/write. The default value is 0.

Remarks

To skew an object in place, set the CenterX and CenterY properties to the object's center point.

The local origin (0,0) for an object can be offset on a Canvas using Canvas.Left and Canvas.Top, but this does not count as a transform; the object retains its own local origin in this case for transformation purposes. For details on this concept, see Object Layout in Silverlight.

The following illustration shows three examples of a SkewTransform applied to a Rectangle.

Applies To

SkewTransform

See Also

Silverlight Transforms Overview


CharPosition Property (ParserErrorEventArgs)

The character position within the line that the parser error occurred on.

XAML | Cannot be used in XAML.
Scripting | value = eventargs.CharPosition

Property Value

integer

The character position the parser error occurred on.

This property is read/write.

Remarks

Because you cannot raise your own errors in the Silverlight 1.0 eventing model, the settable aspect of this property does not have a practical usage. Usually, you will only use this property to get its value.

Examples

The following JavaScript example shows the portion of an event handler that displays error information specific to parser errors.

JavaScript
    // errorArgs is an instance of ParserErrorEventArgs
    if(errorArgs.ErrorType == "ParserError")
    {
      var parserErrorMsg = "Silverlight Parser Error  \n\n";

      // Basic error event informaiton.
      parserErrorMsg += "Error Type:    " + errorArgs.errorType     + "\n";
      parserErrorMsg += "Error Message: " + errorArgs.errorMessage  + "\n";
      parserErrorMsg += "Error Code:    " + errorArgs.errorCode  + "\n";

      //Parser specific error event information.
      parserErrorMsg += "XamlFile:      " + errorArgs.xamlFile      + "\n";
      parserErrorMsg += "XmlElement:    " + errorArgs.xmlElement    + "\n";
      parserErrorMsg += "XmlAttribute:  " + errorArgs.xmlAttribute  + "\n";
      parserErrorMsg += "Line:          " + errorArgs.lineNumber    + "\n";
      parserErrorMsg += "Position:      " + errorArgs.charPosition  + "\n";

      // Display the error message.
      alert(parserErrorMsg);
    }

Applies To

ParserErrorEventArgs

See Also

Silverlight Application Scripting Error Handling, ErrorEventArgs, RuntimeErrorEventArgs


CharPosition Property (RuntimeErrorEventArgs)

The character position within the line that the runtime error occurred on.

XAML | Cannot be used in XAML.
Scripting | value = eventargs.CharPosition

Property Value

integer

The character position the runtime error occurred on.

This property is read/write.

Remarks

This property is technically read/write, but there is generally no reason to set it, because the property is just reporting information from existing errors.

Examples

The following JavaScript example shows the portion of an event handler that displays error information specific to runtime errors.

JavaScript
    // errorArgs is an instance of RuntimeErrorEventArgs
    if(errorArgs.ErrorType == "RuntimeError")
    {
      var runtimeErrorMsg = "Silverlight Runtime Error  \n\n";

      // Basic error event informaiton.
      runtimeErrorMsg += "Error Type:    " + errorArgs.errorType     + "\n";
      runtimeErrorMsg += "Error Message: " + errorArgs.errorMessage  + "\n";
      runtimeErrorMsg += "Error Code:    " + errorArgs.errorCode  + "\n";

      // Runtime specific error event information.
      if (errorArgs.lineNumber != 0)
      {
        runtimeErrorMsg += "Line:     " + errorArgs.lineNumber     + "\n";
        runtimeErrorMsg += "Position: " +  errorArgs.charPosition  + "\n";
      }

     runtimeErrorMsg += "MethodName: " + errorArgs.methodName     + "\n";

     alert(runtimeErrorMsg);
    }

Applies To

RunTimeErrorEventArgs

See Also

Silverlight Application Scripting Error Handling, ErrorEventArgs, ParserErrorEventArgs


Children Property (GeometryGroup)

Gets or sets the collection of child Geometry objects.

XAML
<GeometryGroup>
  oneOrMoreGeometries
</GeometryGroup>
Scripting
value = object.Children
object.Children = value

Property Value

GeometryCollection

The collection of child Geometry objects.

This property is read/write. The default value is an empty collection.

Remarks

The XAML syntax for Children is an example of an implicit collection syntax, where you can omit the GeometryCollection object element, as well as the <GeometryGroup.Children> property element. Instead, you generally include one or more Geometry-type object elements (EllipseGeometry, GeometryGroup, LineGeometry, PathGeometry, or RectangleGeometry) as child elements of a GeometryGroup Object. For more information about XAML implicit collection syntax, see XAML Syntax Overview. (Explicitly including a GeometryCollection object element is permissible XAML syntax, and might be useful if you intend to name the collection in XAML and manipulate its contents through script later.)

Applies To

GeometryGroup

See Also

Geometry, GeometryCollection, Silverlight Geometries Overview


Children Property (Canvas)

Gets or sets the collection of child elements on the Canvas.

XAML
<Canvas>
  oneOrMoreChildElements
</Canvas>
Scripting
value = object.Children
No script setting syntax; see Remarks

Property Value

VisualCollection

The collection of child UIElement objects.

This property is read-only. You can use implicit collection syntax in XAML or methods of the VisualCollection in script to add items or otherwise adjust the collection, but you cannot replace it with a completely new collection object. The default value is an empty VisualCollection collection.

Remarks

Only two types of UIElement support a Children property: Canvas, and InkPresenter.

The XAML syntax for Children is an example of an implicit collection syntax. In this case, neither the explicit property element tag <Canvas.Children> nor the object element for the explicit collection <VisualCollection> is permitted by the XAML parser. The implicit collection syntax of placing one or more child elements as direct child elements of a Canvas object element is the only permitted XAML syntax. For more information about XAML implicit collection syntax, see XAML Syntax Overview.

In scripting, you can get the value of Children and retain it for later operations against the collection, but you cannot set the Children property directly by any means. CreateFromXaml is not a viable technique for setting Children directly, because <VisualCollection> is not a parseable object element to use as the CreateFromXaml root. Instead, you typically use CreateFromXaml to create a single node at a time and then add that node to the VisualCollection using the syntax object.Children.Add(xamlNode).

Objects added to the Children collection are rendered immediately.

InkPresenter is a derived class of Canvas and inherits its Children property. The Children for an InkPresenter render on the InkPresenter surface just as they do on a Canvas. For details on how to mix stroke and child element content, see remarks in InkPresenter.

Applies To

Canvas

See Also

VisualCollection, Canvas, UIElement, Root, XAML Syntax Overview, Silverlight Object Models


Children Property (Storyboard)

Gets or sets the collection of collection of child Timeline objects.

XAML
<Storyboard>
  oneOrMoreTimelines
</Storyboard>
Scripting
value = object.Children
object.Children = value

Property Value

TimelineCollection

The collection of child Timeline objects.

This property is read/write. The default value is empty collection.

Remarks

The XAML syntax for Children is an example of an implicit collection syntax. In this case, neither the explicit property element tag <Storyboard.Children> nor the object element for the explicit collection <TimelineCollection> is permitted by the XAML parser. The implicit collection syntax of placing one or more child elements as direct child elements of a Storyboard object element is the only permitted XAML syntax. For more information about XAML implicit collection syntax, see XAML Syntax Overview.

The Children property accepts one or more of any of the following: ColorAnimation, ColorAnimationUsingKeyFrames, DoubleAnimation, DoubleAnimationUsingKeyFrames, PointAnimation, PointAnimationUsingKeyFrames. It also accepts Storyboard. Nesting storyboards can be a useful technique for grouping or ungrouping animations that should sometimes play separately or sometimes together, or for applying properties such as the RepeatBehavior to a group.

In scripting, you can get the value of Children and retain it for later operations against the collection, but you cannot set the Children property directly by any means. CreateFromXaml is not a viable technique for setting Children directly, because <TimelineCollection> is not a parseable object element to use as the CreateFromXaml root. Instead, you typically use CreateFromXaml to create a single node at a time and then add that node to the TimelineCollection using the syntax object.Children.Add(xamlNode).

Applies To

Storyboard

See Also

Animation Overview


Children Property (TransformGroup)

Gets or sets the collection of child Transform objects.

XAML
<TransformGroup>
  oneOrMoreTransforms
</TransformGroup>
Scripting
value = object.Children
object.Children = value

Property Value

TransformCollection

The collection of child Transform objects.

This property is read/write. The default value is an empty collection.

Remarks

The XAML syntax for properties that use a TransformCollection is an example of an implicit collection syntax, where you can omit the TransformCollection object element, as well as the <TransformGroup.Children> property element. Instead, you generally include one or more transform object elements (RotateTransform, ScaleTransform, SkewTransform, TranslateTransform, MatrixTransform, TransformGroup) as child elements of a TransformGroup. For more information about XAML implicit collection syntax, see XAML Syntax Overview. (Explicitly including a TransformCollection object element is permissible XAML syntax and might be useful if you intend to name the collection in XAML and manipulate its contents through script later.)

In a composite transformation, the order of individual transformations is important. For example, if you first rotate, then scale, then translate, you get a different result than if you first translate, then rotate, then scale. One reason order is significant is that transformations such as rotation and scaling are done with respect to the origin of the coordinate system. Scaling an object that is centered at the origin produces a different result than scaling an object that has been moved away from the origin. Similarly, rotating an object that is centered at the origin produces a different result than rotating an object that has been moved away from the origin.

Nesting TransformGroup elements is permitted.

Applies To

TransformGroup

See Also

TransformGroup, TransformCollection, Silverlight Transforms Overview


Clip Property

Gets or sets the Geometry used to define the outline of the contents of an element.

XAML
<object Clip="Geometry" .../>
Scripting
value = object.Clip
object.Clip = value

Property Value

Geometry

The geometry to be used for clipping area sizing.

This property is read/write. The default value is null.

Remarks

Elements outside the geometry will be visually clipped in the rendered layout. The geometry does not have to be rectangular.

Applies To

Canvas, Ellipse, Glyphs, Image, InkPresenter, Line, MediaElement, Path, Polygon, Polyline, Rectangle, TextBlock

See Also

Object Layout in Silverlight, Silverlight Geometries Overview, Silverlight Brushes Overview


Color Property (DrawingAttributes)

The color of the associated stroke.

XAML
<DrawingAttributes Color="Color" .../>
Scripting
value = object.Color
object.Color = value

Property Value

Color

The color of the associated stroke.

This property is read/write. The default value is Black.

Remarks

See Color for details on the various string formats that can be used to specify a color either in XAML or script.

Examples

The following JavaScript example simulates 3 different pen types (pen, marker and highlighter) by setting the Color, Height, OutlineColor and Width, DrawingAttributes properties . First a DrawingAttributes object is created, then it is appended to the Stroke object. The DrawingAttributes properties are then set by one of the three events that simulate a pen type. The EraseCanvas event clears all the Strokes from the Canvas.

JavaScript
var agCtrl;
var inkPresenter; // Corresponds to InkPresenter element in xaml
var newStroke = null; // The Stroke variable we'll use here in mouse handlers
// DrawingAttributes variables
var daWidth = 2;
var daHeight = 2;
var daColor = "Black";
var daOutlineColor = "Black";

function root_Loaded(sender, args)
{
    // Get the html object which contains the Silverlight plug-in
    agCtrl = sender.GetHost();
    inkPresenter = sender.findname("inkPresenterElement");
}

// Capture mouse movement when the left button is pressed and create the stroke
function InkPresenterMouseDown(sender,args)
{
   inkPresenter.CaptureMouse();

   newStroke = agCtrl.content.createFromXaml('<Stroke/>');

   var da = agCtrl.content.CreateFromXaml('<DrawingAttributes/>');
   newStroke.DrawingAttributes = da;

   // Set the drawing attributes properties
   newStroke.DrawingAttributes.Width = daWidth;
   newStroke.DrawingAttributes.Height = daHeight;
   newStroke.DrawingAttributes.Color = daColor;
   newStroke.DrawingAttributes.OutlineColor = daOutlineColor;

   newStroke.StylusPoints.AddStylusPoints(args.GetStylusPoints(inkPresenter));
   inkPresenter.Strokes.Add(newStroke);
}

// Add the new points to the Stroke we're working with
function InkPresenterMouseMove(sender,args)
{
   if (newStroke != null)
   {
      newStroke.StylusPoints.AddStylusPoints(args.GetStylusPoints(inkPresenter));
   }
}

// Release the mouse
function InkPresenterMouseUp(sender,args)
{
   newStroke = null;
   inkPresenter.ReleaseMouseCapture();
}

// Set the Drawing Attributes for a pen
function SelectPen(sender, args)
{
  daWidth = 1;
  daHeight = 1;
  daColor = "Black";
  daOutlineColor = "Black";
}

// Set the Drawing Attributes for a marker
function SelectMarker(sender, args)
{
  daWidth = 10;
  daHeight = 4;
  daColor = "Blue";
  daOutlineColor = "Blue";
}

// Set the Drawing Attributes for a highlighter
function SelectHighlighter(sender, args)
{
  daWidth = 25;
  daHeight = 5;
  daColor = "Yellow";
  daOutlineColor = "Yellow";
}

// Erase all strokes from the canvas
function EraseCanvas(sender, args)
{
  inkPresenter.Strokes.Clear();
}

The XAML sample below creates the canvas and 4 buttons that are used to select the different pen types and the erase all feature that is simulated by the Javascript events above.

XAML
<Canvas xmlns="http://schemas.microsoft.com/client/2007"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Loaded="root_Loaded"
        x:Name="root"
        Width="600" Height="400">
  <InkPresenter
         x:Name="inkPresenterElement"
        Background="transparent"
        Width="600" Height="400"
        MouseLeftButtonDown="InkPresenterMouseDown"
        MouseMove="InkPresenterMouseMove"
        MouseLeftButtonUp="InkPresenterMouseUp"/>

<!-- Pen Button -->
    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="40"
      Stroke="Gray" Fill="Black" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>
    <TextBlock
      Height="21" Width="78"
      Canvas.Top="380" Canvas.Left="71"
      Foreground="Gray"
      FontFamily="Verdana" FontSize="12">Select Pen</TextBlock>

    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="40"
      x:Name="selectPen" MouseLeftButtonDown="SelectPen"
      Stroke="Transparent" Fill="Transparent" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>

<!-- Marker Button -->
    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="170"
      Stroke="Gray" Fill="Black" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>

    <TextBlock
      Height="21" Width="78"
      Canvas.Top="380" Canvas.Left="191"
      Foreground="Gray"
      FontFamily="Verdana" FontSize="12">Select Marker</TextBlock>

    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="170"
      x:Name="selectMarker" MouseLeftButtonDown="SelectMarker"
      Stroke="Transparent" Fill="Transparent" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>

<!-- Highlighter Button -->
    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="300"
      Stroke="Gray" Fill="Black" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>

    <TextBlock
      Height="21" Width="78"
      Canvas.Top="380" Canvas.Left="310"
      Foreground="Gray"
      FontFamily="Verdana" FontSize="12">Select Highlighter</TextBlock>

    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="300"
      x:Name="selectHighlighter" MouseLeftButtonDown="SelectHighlighter"
      Stroke="Transparent" Fill="Transparent" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>

<!-- Erase Canvas Button -->
    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="430"
      Stroke="Gray" Fill="Black" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>

    <TextBlock
      Height="21" Width="78"
      Canvas.Top="380" Canvas.Left="463"
      Foreground="Gray"
      FontFamily="Verdana" FontSize="12">Erase All</TextBlock>

    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="430"
      x:Name="eraseCanvas" MouseLeftButtonDown="EraseCanvas"
      Stroke="Transparent" Fill="Transparent" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>
</Canvas>

Applies To

DrawingAttributes

See Also

Stroke, OutlineColor, Height, Width, DrawingAttributes, DrawingAttributes(Stroke), Ink Support In Microsoft Silverlight


Color Property (GradientStop)

Gets or sets the color of a gradient stop.

XAML
<object Color="Color" .../>
Scripting
value = object.Color
object.Color = value

Property Value

Color

The color of the gradient stop.

This property is read/write. The default value is Transparent.

Remarks

See Color for details on the various string formats that can be used to specify a color either in XAML or script.

Examples

The following example creates a LinearGradientBrush with four gradient stops in the implicit GradientStopCollection, which is used to paint a Rectangle.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <!-- This rectangle is painted with a diagonal linear gradient. -->
  <Rectangle Width="200" Height="100">
    <Rectangle.Fill>
      <LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
        <GradientStop Color="Yellow" Offset="0.0" />
        <GradientStop Color="Red" Offset="0.25" />
        <GradientStop Color="Blue" Offset="0.75" />
        <GradientStop Color="LimeGreen" Offset="1.0" />
      </LinearGradientBrush>
    </Rectangle.Fill>
  </Rectangle>
</Canvas>

Applies To

GradientStop

See Also

Silverlight Brushes Overview


Color Property (SolidColorBrush)

Gets or sets the color of this SolidColorBrush.

XAML
<object Color="Color" .../>
Scripting
value = object.Color
object.Color = value

Property Value

Color

The brush's color.

This property is read/write. The default value is null, which is evaluated as Transparent.

Remarks

For a list of colors, and the script and XAML usages for all properties that take a Color, see Color.

Applies To

SolidColorBrush

See Also

XAML Syntax Overview, Silverlight Brushes Overview


ColorInterpolationMode Property (LinearGradientBrush)

Gets or sets a value that specifies how the colors in the linear gradient stops are interpolated.

XAML
<object ColorInterpolationMode="ColorInterpolationMode" .../>
Scripting
value = object.colorInterpolationMode
object.colorInterpolationMode = value

Property Value

ColorInterpolationMode

A value of the ColorInterpolationMode enumeration.

This property is read/write. The default value is SRgbLinearInterpolation.

Applies To

LinearGradientBrush

See Also

Silverlight Brushes Overview


ColorInterpolationMode Property (RadialGradientBrush)

Gets or sets a value that specifies how the colors in the linear gradient stops are interpolated.

XAML
<object ColorInterpolationMode="ColorInterpolationMode" .../>
Scripting
value = object.colorInterpolationMode
object.colorInterpolationMode = value

Property Value

ColorInterpolationMode

A value of the ColorInterpolationMode enumeration.

This property is read/write. The default value is SRgbLinearInterpolation.

Applies To

RadialGradientBrush

See Also

Silverlight Brushes Overview


Count Property

Gets the number of items contained in the collection.

XAML | Cannot be used in XAML.
Scripting | value = object.Count

Property Value

integer

The number of items contained in the collection.

This property is read-only. The default value is 0 for an initially empty collection.

Remarks

For several common Silverlight elements, you can get the relevant collection and enumerate the child items of a parent object by accessing the "Children" collection of the parent object (Canvas.Children, GeometryGroup.Children, Storyboard.Children, TransformGroup.Children). Other commonly used collection properties are Path.Data, TextBlock.Inlines, and LinearGradientBrush.GradientStops.

Note Using the Count property with an object that does not support a collection will raise a Silverlight runtime error.

Examples

The following JavaScript example shows how to use the Count property to enumerate the children of a parent Canvas object:

JavaScript
function getChildren(parent, index)
{
    // Enumerate the children of the Canvas object.
    for (i = 0; i < parent.children.count; i++)
    {
        var child = parent.children.getItem(i);

        // Display the index and type of the child object.
        alert(i + ": " + child.toString());
    }
}

Applies To

Collection, GeometryCollection, GradientStopCollection, Inlines, PathFigureCollection, PathSegmentCollection, StrokeCollection, StylusPointCollection, TransformCollection, TriggerCollection, VisualCollection

See Also

Referencing and Modifying Silverlight Objects


Ctrl Property (KeyboardEventArgs)

Gets a value specifying whether the control (CTRL) key was down when the event occurred.

XAML | This property cannot be used in XAML.
Scripting | value = eventargs.Ctrl

Property Value

Boolean

true if the CTRL key was down when the event occurred; otherwise, false.

Remarks

Use this property to detect key combinations involving the CTRL key that are otherwise interpreted as commands or gestures in other application programming models.

Note: This property corresponds to the "Control" key on the Macintosh.

Applies To

KeyboardEventArgs

See Also

Silverlight Keyboard Support, Silverlight Events


Ctrl Property (MouseEventArgs)

Gets a value specifying whether the control (CTRL) key was down when the event occurred.

XAML | This property cannot be used in XAML.
Scripting | value = eventargs.Ctrl

Property Value

Boolean

true if the CTRL key was down when the event occurred; otherwise, false.

Applies To

MouseEventArgs

See Also

Silverlight Events


CurrentState Property

Gets the status of the MediaElement.

XAML | Cannot be used in XAML.
Scripting | value = object.CurrentState

Property Value

MediaState

The current state of the MediaElement. The state can be one of the following (as defined in the MediaState enumeration): Buffering, Closed, Error, Opening, Paused, Playing, or Stopped.

This property is read-only. The default value is Closed.

Remarks

When the value of this property changes, the MediaElement raises its CurrentStateChanged event.

CurrentState and CurrentStateChanged are most relevant if your application defines UI that permits transport control of the media (ultimately using MediaElement methods such as Play, Stop, etc.) Certain media states imply that calls to such APIs will not be able to execute immediately, which you could choose to reflect in your UI by temporarily providing visual feedback, or you could also provide fallback information based on state from within your event handlers. For example, if the current state is Buffering, a call to Play will not be immediately responsive until the state changes to another state such as Playing or Paused.

Changing the value of Source on a MediaElement will change the state to Opening, unless Source is set to null in which case the state is Closed.

If the state is Error, that state change will also raise MediaFailed.

The meanings of the states and the possible application responses to them are influenced by the type of media being played. For instance, live streaming media cannot be paused and will never enter that state. For details, see Supported Media Formats and Protocols.

Your code should not rely on states falling in an exact order. The CurrentStateChanged reports that a change has occured, and CurrentState reports the current state, but subframe transitory states might not raise CurrentStateChanged. The intention of the CurrentStateChanged / CurrentState API is that you can use the reported information for changes to UI, and reporting every subframe transitory state is not necessary for this scenario.

If the source is an ASX file, state is captured for the media that is the current media being processed from the playlist. States for referenced media in the playlist that are not the current media being processed are not captured. Downloading progress to the other media in the playlist occurs in the background, and will begin downloading the next item in the playlist 20 seconds before the end of the current entry.

Examples

The following example demonstrates one way to display the CurrentState of a MediaElement. It creates a MediaElement and several buttons for controlling media playback. To display the current state of the MediaElement, the example registers for the CurrentStateChanged event and uses an event handler to update a TextBlock.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Width="300" Height="300">

  <MediaElement
    x:Name="media"
    Source="xbox.wmv"
    CurrentStateChanged="media_state_changed"
    Width="300" Height="300"/>

  <!-- Stops media playback.-->
  <Canvas MouseLeftButtonDown="media_stop"
    Canvas.Left="10" Canvas.Top="265">
    <Rectangle Stroke="Black"
      Height="30" Width="55" RadiusX="5" RadiusY="5">
      <Rectangle.Fill>
        <RadialGradientBrush GradientOrigin="0.75,0.25">
          <GradientStop Color="Orange" Offset="0.0" />
          <GradientStop Color="Red" Offset="1.0" />
        </RadialGradientBrush>
      </Rectangle.Fill>
    </Rectangle>
    <TextBlock Canvas.Left="5" Canvas.Top="5">stop</TextBlock>
  </Canvas>

  <!-- Pauses media playback. -->
  <Canvas MouseLeftButtonDown="media_pause"
    Canvas.Left="70" Canvas.Top="265">
    <Rectangle Stroke="Black"
      Height="30" Width="55" RadiusX="5" RadiusY="5">
      <Rectangle.Fill>
        <RadialGradientBrush GradientOrigin="0.75,0.25">
          <GradientStop Color="Yellow" Offset="0.0" />
          <GradientStop Color="Orange" Offset="1.0" />
        </RadialGradientBrush>
      </Rectangle.Fill>
    </Rectangle>
    <TextBlock Canvas.Left="5" Canvas.Top="5">pause</TextBlock>
  </Canvas>

  <!-- Begins media playback. -->
  <Canvas MouseLeftButtonDown="media_begin"
    Canvas.Left="130" Canvas.Top="265">
    <Rectangle Stroke="Black" RadiusX="5" RadiusY="5"
      Height="30" Width="55">
      <Rectangle.Fill>
        <RadialGradientBrush GradientOrigin="0.75,0.25">
          <GradientStop Color="LimeGreen" Offset="0.0" />
          <GradientStop Color="Green" Offset="1.0" />
        </RadialGradientBrush>
      </Rectangle.Fill>
    </Rectangle>
    <TextBlock Canvas.Left="5" Canvas.Top="5">play</TextBlock>
  </Canvas>

  <TextBlock
    Canvas.Left="190" Canvas.Top="265"
    FontSize="12">CurrentState:</TextBlock>

  <TextBlock
    x:Name="mediaStateTextBlock"
    Canvas.Left="190" Canvas.Top="280"
    FontSize="12"></TextBlock>

</Canvas>
JavaScript
function media_stop(sender, args)
{
    sender.findName("media").stop();
}

function media_pause(sender, args)
{
    sender.findName("media").pause();
}

function media_begin(sender, args)
{
    sender.findName("media").play();
}

function media_state_changed(sender, args)
{
    var mediaStateTextBlock =
    sender.findName("mediaStateTextBlock");
    var media = sender.findName("media");
    mediaStateTextBlock.Text = media.CurrentState;
}

Applies To

MediaElement

See Also

CurrentStateChanged, MediaElement, Supported Media Formats and Protocols, Media Overview


Cursor Property

Gets or sets the cursor that displays when the mouse pointer is over the element.

XAML
<object Cursor="MouseCursor" .../>
Scripting
value = object.Cursor
object.Cursor = value

Property Value

MouseCursor

The cursor to display: Arrow, Default, Eraser, Hand, IBeam, None, Stylus, or Wait. The default is Default.

Remarks

The Default setting indicates that determination of the practical cursor value is deferred here and should be obtained from its parent element. If not specified by a parent element, the default cursor is typically an arrow.

Applies To

Canvas, Ellipse, Glyphs, Image, InkPresenter, Line, MediaElement, Path, Polygon, Polyline, Rectangle, TextBlock

See Also

Ink Support in Microsoft Silverlight, Silverlight Mouse Support


Data Property

Gets or sets a Geometry that specifies the shape to be drawn.

XAML
<object>
  <object.Data>
    oneOrMoreGeometries
  </object.Data>
</object>
-or-
<object Data = "inlinePathSyntax" .../>
Scripting
value = object.Data
object.Data = value

Property Value

Geometry

A description of the shape to be drawn.

This property is read/write. The default value is null.

Remarks

For documentation on the XAML string format to use for inlinePathSyntax, see Path Markup Syntax.

To draw simple shapes, use the EllipseGeometry, LineGeometry, and RectangleGeometry objects. To draw curves, arcs, or complex shapes, use the PathGeometry object. To create a composite geometry, use a GeometryGroup.

Because a GeometryGroup is itself a Geometry, you can either specify single geometries or multiple geometries to populate the Path.Data property element in XAML. In the single geometry child case, there will be no GeometryGroup collection, and the value of Data will be the single geometry. If you specify multiple geometries, the value of Data will be a GeometryGroup whose Children will contain each of the geometries defined as child elements in XAML.

Examples

The following example uses a Path to draw an ellipse.

An EllipseGeometry drawn at (50,50)

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <Path Fill="Gold" Stroke="Black" StrokeThickness="1">
    <Path.Data>
      <EllipseGeometry Center="50,50" RadiusX="50" RadiusY="50" />
    </Path.Data>
  </Path>
</Canvas>

Applies To

Path

See Also

PathGeometry, Silverlight Geometries Overview, Path Markup Syntax


Description Property

Gets or sets a string that provides a description about a Silverlight plug-in's visual appearance.

XAML
Cannot be used in XAML.
Scripting
value = object.Description
object.Description = value

Property Value

string

A string that provides a description for the Silverlight plug-in instance and its content.

This property is read-write. The default is an empty string.

Remarks

The Description property provides a textual description about an object's visual appearance. The description is primarily used to provide greater context for low-vision or blind users, but is also used for context searching or other applications. The Description can help users understand the graphic or the overall visual appearance. If the entirety of the purpose for the Silverlight plug-in instance and its content can be summarized by its Title, do not specify the same string for Description.

Applies To

Accessibility

See Also


DeviceType Property (StylusInfo)

Gets a value that indicates if the stylus represents mouse, stylus, or touch input.

XAML
Cannot be used in XAML.
Scripting
value = object.DeviceType
object.DeviceType = value

Property Value

DeviceType

The type of the input device.

This property is read-only.

Remarks

You obtain StylusInfo by calling a method of the MouseEventArgs that you get from mouse event handler input parameters. The stylus input model is tied to mouse events, so that the mouse can be used as a default input mode.

Examples

The following example demonstrates how to display the type of device that was used to create the current StylusPoint.

JavaScript
// Capture mouse movement when the left button is pressed and create the stroke
function InkPresenterMouseDown(sender,args)
{
  // Display the Type of input device in a TextBlock
  device.Text = args.GetStylusInfo().deviceType;

  inkPresenter.CaptureMouse();
  newStroke = agCtrl.content.createFromXaml('<Stroke/>');

  newStroke.StylusPoints.AddStylusPoints(args.GetStylusPoints(inkPresenter));
  inkPresenter.Strokes.Add(newStroke);
}

Applies To

StylusInfo

See Also

DeviceType, MouseEventArgs, GetStylusInfo, Ink Support In Microsoft Silverlight


DownloadProgress Property (Downloader)

Gets a value that indicates the relative progress of downloaded content.

XAML | Cannot be used in XAML.
Scripting | value = downloaderObject.DownloadProgress

Property Value

Double

A value between 0 and 1 inclusive that represents the amount of total content downloaded. Multiply by 100 to obtain a percentage.

This property is read-only. The default value is 0.

Remarks

Once you have invoked the Send method on the Downloader object, the DownloadProgress property allows you to determine the percentage of total content downloaded. The return value is expressed as double value between 0 and 1.0 inclusive, with 0 representing no content downloaded, and 1.0 representing all content downloaded.

The DownloadProgressChanged event can be used monitor the progress of a download request. The DownloadProgressChanged event occurs whenever the percentage of total content downloaded increases by 0.05 or more, or reaches 1.0.

Examples

The following JavaScript example shows how to use the DownloadProgress property in a DownloadProgressChanged event handler function:

JavaScript
// Event handler for updating visual progress indicator
function onDownloadProgressChanged(sender, eventArgs)
{
    // Calculate the downloaded percentage.
    var percentage = Math.floor(sender.downloadProgress * 100);

    // Update the Rectangle and TextBlock objects of the visual progress indicator.
    progressText.text = percentage + "%";
    progressRectangle.width = percentage * 2;
}

The following image shows the visual progress indicator at the starting, middle, and ending position of the download:

Visual progress indicator

A visual progress indicator can be constructed from a wide variety of XAML content, including animated objects.

Applies To

Downloader

See Also

DownloadProgressChanged, Send, Using a Downloader Object


DownloadProgress Property (MediaElement)

Gets a value that indicates the amount of download completed for content that is located on a remote server.

XAML | You cannot use this property in XAML
Scripting | value = object.DownloadProgress

Property Value

Double

A value that indicates the amount of download completed for content that is located on a remote server. The value ranges from 0 to 1. Multiply by 100 to obtain a percentage.

This property is read-only. The default value is 0.

Remarks

The DownloadProgressChanged event occurs when the DownloadProgress property is updated.

Applies To

MediaElement

See Also

DownloadProgressChanged, Media Overview, Using a Downloader Object


DownloadProgress Property (Image)

Gets a value that indicates the relative progress of downloaded content. This property is only relevant if SetSource is used to set the image source.

XAML | You cannot use this property in XAML
Scripting | value = object.DownloadProgress

Property Value

Double

A value between 0 and 1 inclusive that represents the amount of total content downloaded. Multiply by 100 to obtain a percentage.

This property is read-only. The default value is 0.

Remarks

The DownloadProgressChanged event occurs when the DownloadProgress property value is increased by an amount of 0.05 or greater, or reaches 1.0.

Applies To

Image

See Also

Using a Downloader Object


DownloadProgress Property (ImageBrush)

Gets a value that indicates the relative progress of downloaded content. This property is only relevant if SetSource is used to set the image source.

XAML | You cannot use this property in XAML
Scripting | value = object.DownloadProgress

Property Value

Double

A value between 0 and 1 inclusive that represents the amount of total content downloaded. Multiply by 100 to obtain a percentage.

This property is read-only. The default value is 0.

Remarks

The DownloadProgressChanged event occurs when the DownloadProgress property value is increased by an amount of 0.05 or greater, or reaches 1.0.

Applies To

ImageBrush

See Also

Silverlight Brushes Overview, Using a Downloader Object


DrawingAttributes Property

Specifies the appearance of the Stroke.

XAML
<object.../>
  <object.DrawingAttributes>
    <DrawingAttributes .../>
  </object.DrawingAttributes>
<object.../>
Scripting
value = object.DrawingAttributes
object.DrawingAttributes = value

Property Value

DrawingAttributes

Specifies the appearance of the Stroke.

This property is read/write.

Remarks

DrawingAttributes is not a collection, it is a representative object that is used to set various properties of the object that will be used in the stroke rendering. To set the DrawingAttributes property in XAML, you must use the property element syntax shown above.

Examples

The following JavaScript example simulates 3 different pen types (pen, marker and highlighter) by setting the Color, Height, OutlineColor and Width DrawingAttributes properties. First a DrawingAttributes object is created, then it is appended to the Stroke object. The DrawingAttributes properties are then set by one of the three events that simulate a pen type. The EraseCanvas event clears all the Strokes from the Canvas.

JavaScript
var agCtrl;
var inkPresenter; // Corresponds to InkPresenter element in xaml
var newStroke = null; // The Stroke variable we'll use here in mouse handlers
// DrawingAttributes variables
var daWidth = 2;
var daHeight = 2;
var daColor = "Black";
var daOutlineColor = "Black";

function root_Loaded(sender, args)
{
    // Get the html object which contains the Silverlight plug-in
    agCtrl = sender.GetHost();
    inkPresenter = sender.findname("inkPresenterElement");
}

// Capture mouse movement when the left button is pressed and create the stroke
function InkPresenterMouseDown(sender,args)
{
   inkPresenter.CaptureMouse();

   newStroke = agCtrl.content.createFromXaml('<Stroke/>');

   var da = agCtrl.content.CreateFromXaml('<DrawingAttributes/>');
   newStroke.DrawingAttributes = da;

   // Set the drawing attributes properties
   newStroke.DrawingAttributes.Width = daWidth;
   newStroke.DrawingAttributes.Height = daHeight;
   newStroke.DrawingAttributes.Color = daColor;
   newStroke.DrawingAttributes.OutlineColor = daOutlineColor;

   newStroke.StylusPoints.AddStylusPoints(args.GetStylusPoints(inkPresenter));
   inkPresenter.Strokes.Add(newStroke);
}

// Add the new points to the Stroke we're working with
function InkPresenterMouseMove(sender,args)
{
   if (newStroke != null)
   {
      newStroke.StylusPoints.AddStylusPoints(args.GetStylusPoints(inkPresenter));
   }
}

// Release the mouse
function InkPresenterMouseUp(sender,args)
{
   newStroke = null;
   inkPresenter.ReleaseMouseCapture();
}

// Set the Drawing Attributes for a pen
function SelectPen(sender, args)
{
  daWidth = 1;
  daHeight = 1;
  daColor = "Black";
  daOutlineColor = "Black";
}

// Set the Drawing Attributes for a marker
function SelectMarker(sender, args)
{
  daWidth = 10;
  daHeight = 4;
  daColor = "Blue";
  daOutlineColor = "Blue";
}

// Set the Drawing Attributes for a highlighter
function SelectHighlighter(sender, args)
{
  daWidth = 25;
  daHeight = 5;
  daColor = "Yellow";
  daOutlineColor = "Yellow";
}

// Erase all strokes from the canvas
function EraseCanvas(sender, args)
{
  inkPresenter.Strokes.Clear();
}

The following XAML example creates the canvas and 4 buttons that are used to select the different pen types and the erase all feature that is simulated by the Javascript events above.

XAML
<Canvas xmlns="http://schemas.microsoft.com/client/2007"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Loaded="root_Loaded"
        x:Name="root"
        Width="600" Height="400">
  <InkPresenter
         x:Name="inkPresenterElement"
        Background="transparent"
        Width="600" Height="400"
        MouseLeftButtonDown="InkPresenterMouseDown"
        MouseMove="InkPresenterMouseMove"
        MouseLeftButtonUp="InkPresenterMouseUp"/>

<!-- Pen Button -->
    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="40"
      Stroke="Gray" Fill="Black" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>
    <TextBlock
      Height="21" Width="78"
      Canvas.Top="380" Canvas.Left="71"
      Foreground="Gray"
      FontFamily="Verdana" FontSize="12">Select Pen</TextBlock>

    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="40"
      x:Name="selectPen" MouseLeftButtonDown="SelectPen"
      Stroke="Transparent" Fill="Transparent" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>

<!-- Marker Button -->
    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="170"
      Stroke="Gray" Fill="Black" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>

    <TextBlock
      Height="21" Width="78"
      Canvas.Top="380" Canvas.Left="191"
      Foreground="Gray"
      FontFamily="Verdana" FontSize="12">Select Marker</TextBlock>

    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="170"
      x:Name="selectMarker" MouseLeftButtonDown="SelectMarker"
      Stroke="Transparent" Fill="Transparent" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>

<!-- Highlighter Button -->
    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="300"
      Stroke="Gray" Fill="Black" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>

    <TextBlock
      Height="21" Width="78"
      Canvas.Top="380" Canvas.Left="310"
      Foreground="Gray"
      FontFamily="Verdana" FontSize="12">Select Highlighter</TextBlock>

    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="300"
      x:Name="selectHighlighter" MouseLeftButtonDown="SelectHighlighter"
      Stroke="Transparent" Fill="Transparent" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>

<!-- Erase Canvas Button -->
    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="430"
      Stroke="Gray" Fill="Black" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>

    <TextBlock
      Height="21" Width="78"
      Canvas.Top="380" Canvas.Left="463"
      Foreground="Gray"
      FontFamily="Verdana" FontSize="12">Erase All</TextBlock>

    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="430"
      x:Name="eraseCanvas" MouseLeftButtonDown="EraseCanvas"
      Stroke="Transparent" Fill="Transparent" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>
</Canvas>

Applies To

Stroke

See Also

Stroke, Color, Height, Width, DrawingAttributes


Duration Property

Gets or sets the length of time for which this timeline plays, not counting repetitions.

XAML
<object Duration="Duration" ...>
Scripting
value = object.Duration
object.Duration = value

Property Value

Duration

The timeline's simple duration, which is the amount of time this timeline takes to complete a single forward iteration.

This property is read/write. The default value is null, which corresponds to the Automatic behavior.

Remarks

A timeline's simple duration constitutes the time for a single forward iteration versus the total play time, which includes repetitions.

See Duration for details on the string format you use to specify a Duration value, either in script or XAML. Creating a Duration in XAML is only possible through a type conversion syntax when setting a property that takes a Duration as an attribute string. Basically, a Duration can be defined as an h:m:s string, or the special values "Automatic" or "Forever".

You can set the Duration value in script using object.Duration="stringvalue" syntax. You must use a quoted string, which then uses the same type conversion behavior as the XAML attribute syntax. You can set the value on a running animation, and the value will apply immediately. The new current state of the animation will reflect the progress of the animation that had already run prior to the change, with that same progress applied towards the new Duration. You can get the Duration value in script using value=object.Duration syntax. However, if the Duration for an animation is not explicitly set (either through scripting or XAML), then the value of object.Duration will be null. A null value for Duration has the same implied effect on an animation as does a Duration explicitly set to "Automatic".

If the AutoReverse property is set to true, the timeline plays for twice the length of time specified by its Duration.

This property applies both to specific animations and to the parent storyboard. For an animation in a storyboard, if you set a Duration other than the default "Automatic" at the storyboard level, make sure you are not unintentionally clipping the durations of child animations.

Applies To

ColorAnimation, ColorAnimationUsingKeyFrames, DoubleAnimation, DoubleAnimationUsingKeyFrames, PointAnimation, PointAnimationUsingKeyFrames, Storyboard

See Also

Animation Overview


EnableFramerateCounter Property

Gets or sets a value that determines whether to display the current framerate in the hosting browser's status bar. (Microsoft Internet Explorer only)

Scripting (Instantiation)
Not exposed by CreateObject/CreateObjectEx
Scripting (Runtime)
value = silverlightObject.settings.enableFramerateCounter
silverlightObject.settings.enableFramerateCounter = value

Property Value

Boolean

Determines whether to show the frames-per-second (fps) of the current rendered Silverlight content in the hosting browser's status bar.

This property is read/write. The default value is false.

Remarks

This property is available on the settings sub-object of a Silverlight plug-in instance.

The EnableFramerateCounter property is useful for optimizing your application by showing the frames-per-second (fps) of the current rendered Silverlight content. You can use the framerate information to identify performance bottlenecks in your application. This property is supported only for Microsoft Internet Explorer running on Windows XP SP2 or Windows Vista

This property does not have a matching parameter on CreateObject/CreateObjectEx in Silverlight.js. You can set it at runtime, for instance in an OnLoad handler.

The following screenshot shows the framerate displayed in the left side of the browser status bar. The framerate value changes in response to Silverlight rendering requests:

Current framerate displayed in the browser status bar

Examples

The following JavaScript example shows how to retrieve the value of the EnableFramerateCounter property:

JavaScript
// Retrieve a reference to the plug-in.
var plugin = sender.getHost();

// Retrieve the EnableFramerateCounter property.
var enableFramerateCounter = plugin.settings.enableFramerateCounter;

Applies To

Silverlight Plug-in

See Also

MaxFrameRate, Using a Silverlight Plug-in, Using CreateSilverlight.js and Silverlight.js


EnableHtmlAccess Property

Gets whether the hosted content in the Silverlight plug-in has access to the browser Document Object Model (DOM).

Scripting (Instantiation)
Silverlight.CreateObject(,,,{enableHtmlAccess:'booleanValue'})
-or-
Silverlight.CreateObjectEx({properties:{enableHtmlAccess:'booleanValue'}})
Scripting (Runtime)
booleanValue = silverlightObject.settings.EnableHtmlAccess

Property Value

Boolean

Determines whether the hosted content has access to the browser DOM.

The default value is true.

Remarks

This property is not relevant for Silverlight 1.0. In Silverlight 1.0, the Silverlight object model always has access to the browser DOM. This parameter exists for use by Silverlight 1.1 Alpha versions.

This property is available on the settings sub-object of a Silverlight plug-in instance.

Applies To

Silverlight Plug-in

See Also

Using a Silverlight Plug-in, Silverlight 1.0 Architecture, Silverlight Object Models


EnableRedrawRegions Property

Gets or sets a value that determines whether to show the areas of the plug-in that are being redrawn each frame.

Scripting (Instantiation)
Cannot be set during instantiation.
Scripting (Runtime)
value = silverlightObject.settings.EnableRedrawRegions
silverlightObject.settings.EnableRedrawRegions = value

Property Value

Boolean

true to show areas of the plug-in that are being redrawn each frame; otherwise, false.

This property is read/write. The default value is false.

Remarks

This property is available on the settings sub-object of a Silverlight plug-in instance.

The EnableRedrawRegions property is used during development for performance-tuning your application by showing the areas of the plug-in that are being redrawn each frame. You cannot set this property during initialization. Typically you would turn this property on and off using an event handler, such as OnLoad.

Applies To

Silverlight Plug-in

See Also

Using a Silverlight Plug-in


EndPoint Property (LinearGradientBrush)

Gets or sets the ending two-dimensional coordinate point of the linear gradient axis.

XAML
<object EndPoint="Point" .../>
Scripting
value = object.EndPoint
object.EndPoint = value

Property Value

Point

The ending two-dimensional coordinates of the linear gradient.

This property is read/write. The default value is 1,1.

Remarks

See remarks in Point for scripting usages of this property.

A LinearGradientBrush paints an area with a linear gradient. A linear gradient defines a gradient along a line. The line's end points are defined by the StartPoint and EndPoint properties of the linear gradient. A LinearGradientBrush brush paints its GradientStops along this line.

The default linear gradient is diagonal, and the default mode for the gradient coordinate system is RelativeToBoundingBox. With these defaults, the StartPoint of a linear gradient the upper-left corner of the area being painted, 0,0. Its EndPoint is the lower-right corner of the area being painted, 1.1. The colors in the resulting gradient are interpolated and applied along vectors that parallel this diagonal axis.

The following illustration shows a diagonal gradient. A line was added to highlight the interpolation path of the gradient from the start point to the end point.

Gradient axis for a diagonal linear gradient

The next illustration shows the same linear gradient, but with highlighted gradient stops.

Gradient stops in a linear gradient

Specifying Relative or Absolute Values

The MappingMode Property property of a LinearGradientBrush determines whether its EndPoint is interpreted as a relative or absolute value. By default, it is treated as relative, which corresponds to a MappingMode of RelativeToBoundingBox. A MappingMode of Absolute specifies that the EndPoint value is expressed in device independent pixels. If you use Absolute mode, you will almost certainly also want to change the EndPoint, because a value of 1,1 versus a StartPoint of 0,0 would only apply the brush to a single pixel.

Applies To

LinearGradientBrush

See Also

RadialGradientBrush, Silverlight Brushes Overview


EndPoint Property (LineGeometry)

Gets or sets the endpoint of the line.

XAML
<object EndPoint="Point" .../>
Scripting
value = object.EndPoint
object.EndPoint = value

Property Value

Point

The endpoint of the line.

This property is read/write. The default value is 0,0.

Remarks

See remarks in Point for scripting usages of this property.

Applies To

LineGeometry

See Also

Silverlight Geometries Overview


ErrorCode Property

Gets the error code associted witht he error.

XAML | Cannot be used in XAML.
Scripting | value = eventargs.ErrorCode

Property Value

integer

The error code of the event.

This property is read-only.

Remarks

For the listing of error codes and their meanings and error strings, see Silverlight Application Scripting Error Handling.

Examples

The following JavaScript example shows how to create an onError event handler that displays specific error information pertaining to the type of error. The ErrorType property on the ErrorEventArgs is used to determine the type of error.

JavaScript
function OnErrorEventHandler(sender, errorArgs)
{
    // The error message to display.
    var errorMsg = "Silverlight Error: \n\n";

    // Error information common to all errors.
    errorMsg += "Error Type:    " + errorArgs.errorType + "\n";
    errorMsg += "Error Message: " + errorArgs.errorMessage + "\n";
    errorMsg += "Error Code:    " + errorArgs.errorCode + "\n";

    // Determine the type of error and add specific error information.
    switch(errorArgs.errorType)
    {
        case "RuntimeError":
            // Display properties specific to RuntimeErrorEventArgs.
            if (errorArgs.lineNumber != 0)
            {
                errorMsg += "Line: " + errorArgs.lineNumber + "\n";
                errorMsg += "Position: " +  errorArgs.charPosition + "\n";
            }
            errorMsg += "MethodName: " + errorArgs.methodName + "\n";
            break;
        case "ParserError":
            // Display properties specific to ParserErrorEventArgs.
            errorMsg += "Xaml File:      " + errorArgs.xamlFile      + "\n";
            errorMsg += "Xml Element:    " + errorArgs.xmlElement    + "\n";
            errorMsg += "Xml Attribute:  " + errorArgs.xmlAttribute  + "\n";
            errorMsg += "Line:           " + errorArgs.lineNumber    + "\n";
            errorMsg += "Position:       " + errorArgs.charPosition  + "\n";
            break;
        default:
            break;
    }
    // Display the error message.
    alert(errorMsg);
}

Applies To

ErrorEventArgs, ParserErrorEventArgs, RuntimeErrorEventArgs

See Also

Silverlight Application Scripting Error Handling,


ErrorMessage Property

Gets the error description associated with the error.

XAML | Cannot be used in XAML.
Scripting | value = eventargs.ErrorMessage

Property Value

string

The error messge describing the error.

This property is read-only.

Remarks

For the listing of error codes and their meanings and error strings, see Silverlight Application Scripting Error Handling.

Examples

The following JavaScript example shows how to create an onError event handler that displays specific error information pertaining to the type of error. The ErrorType property on the ErrorEventArgs is used to determine the type of error.

JavaScript
function OnErrorEventHandler(sender, errorArgs)
{
    // The error message to display.
    var errorMsg = "Silverlight Error: \n\n";

    // Error information common to all errors.
    errorMsg += "Error Type:    " + errorArgs.errorType + "\n";
    errorMsg += "Error Message: " + errorArgs.errorMessage + "\n";
    errorMsg += "Error Code:    " + errorArgs.errorCode + "\n";

    // Determine the type of error and add specific error information.
    switch(errorArgs.errorType)
    {
        case "RuntimeError":
            // Display properties specific to RuntimeErrorEventArgs.
            if (errorArgs.lineNumber != 0)
            {
                errorMsg += "Line: " + errorArgs.lineNumber + "\n";
                errorMsg += "Position: " +  errorArgs.charPosition + "\n";
            }
            errorMsg += "MethodName: " + errorArgs.methodName + "\n";
            break;
        case "ParserError":
            // Display properties specific to ParserErrorEventArgs.
            errorMsg += "Xaml File:      " + errorArgs.xamlFile      + "\n";
            errorMsg += "Xml Element:    " + errorArgs.xmlElement    + "\n";
            errorMsg += "Xml Attribute:  " + errorArgs.xmlAttribute  + "\n";
            errorMsg += "Line:           " + errorArgs.lineNumber    + "\n";
            errorMsg += "Position:       " + errorArgs.charPosition  + "\n";
            break;
        default:
            break;
    }
    // Display the error message.
    alert(errorMsg);
}

Applies To

ErrorEventArgs, ParserErrorEventArgs, RuntimeErrorEventARgs

See Also

Silverlight Application Scripting Error Handling,


ErrorType Property

Gets the ErrorType of the error associated with the event.

XAML | Cannot be used in XAML.
Scripting | value = eventargs.ErrorType

Property Value

ErrorType

The type of the error that occurred, expressed as a value of the ErrorType enumeration.

This property is read-only.

Remarks

For the listing of error codes and their meanings and error strings, see Silverlight Application Scripting Error Handling.

Examples

The following JavaScript example shows how to create an onError event handler that displays specific error information pertaining to the type of error. The ErrorType property on the ErrorEventArgs is used to determine the type of error.

JavaScript
function OnErrorEventHandler(sender, errorArgs)
{
    // The error message to display.
    var errorMsg = "Silverlight Error: \n\n";

    // Error information common to all errors.
    errorMsg += "Error Type:    " + errorArgs.errorType + "\n";
    errorMsg += "Error Message: " + errorArgs.errorMessage + "\n";
    errorMsg += "Error Code:    " + errorArgs.errorCode + "\n";

    // Determine the type of error and add specific error information.
    switch(errorArgs.errorType)
    {
        case "RuntimeError":
            // Display properties specific to RuntimeErrorEventArgs.
            if (errorArgs.lineNumber != 0)
            {
                errorMsg += "Line: " + errorArgs.lineNumber + "\n";
                errorMsg += "Position: " +  errorArgs.charPosition + "\n";
            }
            errorMsg += "MethodName: " + errorArgs.methodName + "\n";
            break;
        case "ParserError":
            // Display properties specific to ParserErrorEventArgs.
            errorMsg += "Xaml File:      " + errorArgs.xamlFile      + "\n";
            errorMsg += "Xml Element:    " + errorArgs.xmlElement    + "\n";
            errorMsg += "Xml Attribute:  " + errorArgs.xmlAttribute  + "\n";
            errorMsg += "Line:           " + errorArgs.lineNumber    + "\n";
            errorMsg += "Position:       " + errorArgs.charPosition  + "\n";
            break;
        default:
            break;
    }
    // Display the error message.
    alert(errorMsg);
}

Applies To

ErrorEventArgs, ParserErrorEventArgs, RuntimeErrorEventARgs

See Also

Silverlight Application Scripting Error Handling,


Figures Property

Gets or sets the collection of PathFigure objects that describe the path's contents.

XAML
<PathGeometry>
  oneOrMorePathFigures
</PathGeometry>
Scripting
value = object.Figures
object.Figures = value

Property Value

PathFigureCollection

A collection of PathFigure objects that describe the path's contents. Each individual PathFigure describes a shape.

This property is read/write. The default value is an empty collection.

Remarks

The XAML syntax for Figures is an example of an implicit collection syntax, where you can omit the PathFigureCollection object element, as well as the <PathGeometry.Figures> property element. Instead, you generally include one or more PathFigure object elements as child elements of a PathGeometry. For more information about XAML implicit collection syntax, see XAML Syntax Overview. (Explicitly including a PathFigureCollection object element is permissible XAML syntax, and might be useful if you intend to name the collection in XAML and manipulate its contents through script later. Including the <PathGeometry.Figures> property element might also be useful for markup clarity, because of the nested Figures and Segments collections found in a typical complex PathGeometry Object.)

Applies To

PathGeometry

See Also

StartPoint, Silverlight Geometries Overview, Path Markup Syntax


Fill Property (Glyphs)

Gets the sets the Brush that is used for the fill of the Glyphs.

XAML
<object Fill="Brush" .../>
-or-
<object>
  <object.Fill>
    <Brush .../>
  </object.Fill>
</object>
Scripting
value = object.Fill
object.Fill = value

Property Value

Brush

A value of type Brush.

This property is read/write. The default value is a null Brush, which is evaluated as Transparent.

Remarks

The first XAML syntax shown is an attribute syntax. You would use this syntax if you wanted the Fill to be a SolidColorBrush, which can be expressed as its Color value, for example "Red" or "#FF0000".

The second XAML syntax shown is a property element syntax. You would use this syntax if you wanted the Fill to be a more complex brush than a SolidColorBrush, such as ImageBrush, LinearGradientBrush or RadialGradientBrush.

Note that the default Fill is null. Therefore in order to render anything with Glyphs you should specify a Fill either in XAML or script. This is in contrast to TextBlock.Foreground, which defaults to Black.

Applies To

Glyphs

See Also

TextBlock, Silverlight Brushes Overview, Text and Fonts Overview,


Fill Property (Shape)

Gets or sets the Brush that specifies how to paint the interior of the shape.

XAML
<object Fill="Brush" .../>
-or-
<object>
  <object.Fill>
    <Brush" .../>
  </object.Fill>
</object>
Scripting
value = object.Fill
object.Fill = value

Property Value

Brush

The Brush that describes how the interior of the shape is painted.

This property is read/write. The default value is a null Brush, which has no color value. A value of null Brush has no hit-testable region, while a value of Transparent, does.

Remarks

Setting the Fill for a line (Line or Polyline) has no effect, because a line has no interior. Use Stroke and StrokeThickness for lines instead.

Some brush types (SolidColorBrush) support a XAML attribute syntax, whereas other brush types (ImageBrush, LinearGradientBrush, RadialGradientBrush) only support an object element syntax. This is why two versions of XAML syntax are shown for this property.

When animating a Fill, you must use indirect targeting. For instance, if you are animating the color of a SolidColorBrush that is the Fill of a Rectangle, the syntax would be <ColorAnimation ... Storyboard.TargetProperty="(Rectangle.Fill).(SolidColorBrush.Color)" />.

The area where the Fill applies to a Path is potentially influenced by its geometry data's FillRule. For details, see Silverlight Geometries Overview.

If a Fill is null (or not specified), there is no hit-testable region within the object.

Applies To

Ellipse, Line, Path, Polygon, Polyline, Rectangle

See Also

Shapes Overview, Silverlight Brushes Overview


FillBehavior Property

Gets or sets a value that specifies how the Timeline behaves after it reaches the end of its active period.

XAML
<object FillBehavior="FillBehavior" .../>
Scripting
value = object.FillBehavior
object.FillBehavior = value

Property Value

FillBehavior

A value of the FillBehavior enumeration that specifies how the timeline behaves after it reaches the end of its active period but its parent is inside its active or fill period.

This property is read/write. The default value is HoldEnd.

Remarks

The FillBehavior property specifies how a timeline behaves when it ends. By default, a timeline starts filling when it ends. An animation that is filling holds its final output value.

The filling behavior can create the illusion that a property is unsettable at runtime if you are not careful about stopping unintended animations. Attempting to change the animated value coming from a filling animation in code will appear to have no effect until the filling animation is stopped.

Examples

The following example uses the nondefault FillBehavior value of Stop. As a result, the Opacity value of the rectangle reverts to 1 after the animation ends.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Rectangle
    x:Name="MyAnimatedRectangle"
    Width="100"
    Height="100"
    Fill="Blue">
    <Rectangle.Triggers>

      <!-- Animates the rectangle's opacity. -->
      <EventTrigger RoutedEvent="Rectangle.Loaded">
        <BeginStoryboard>
          <Storyboard>
            <DoubleAnimation
              Storyboard.TargetName="MyAnimatedRectangle"
              Storyboard.TargetProperty="Opacity"
              From="1.0" To="0" Duration="0:0:5" FillBehavior="Stop" />
          </Storyboard>
        </BeginStoryboard>
      </EventTrigger>
    </Rectangle.Triggers>
  </Rectangle>
</Canvas>

Applies To

ColorAnimation, ColorAnimationUsingKeyFrames, DoubleAnimation, DoubleAnimationUsingKeyFrames, PointAnimation, PointAnimationUsingKeyFrames, Storyboard

See Also

Animation Overview


FillRule Property (Geometry)

Silverlight SDK

FillRule Property (PathGeometry)

Gets or sets a value that determines how the intersecting areas (typically PathFigure objects, or combined geometries in a GeometryGroup) contained in this Geometry are combined.

XAML
<object FillRule="FillRule" .../>
Scripting
value = object.FillRule
object.FillRule = value

Property Value

FillRule

A value of the FillRule enumeration.

This property is read/write. The default value is EvenOdd.

Remarks

The fill area is determined by applying the specified rule to the entire Geometry. To give the fill a different appearance, you set a Fill value on the parent Path of the Geometry.

FillRule is mainly relevant for two types of geometries, PathGeometry or GeometryGroup. On other geometries such as RectangleGeometry, the property exists but will have no effect because there is no way in the properties of these geometries to specify segment relationships such that a fill rule behavior is relevant.

The value of IsClosed on a PathFigure within a PathGeometry does not affect the calculation of the fill area, it only affects whether that segment is drawn; the fill area is evaluated as if the first and last segments were connected.

Applies To

EllipseGeometry, GeometryGroup, LineGeometry, PathGeometry, RectangleGeometry

See Also

Silverlight Geometries Overview


FillRule Property (Polygon)

Gets or sets a value that specifies how the interior fill of the shape is determined.

XAML
<object FillRule="FillRule" .../>
Scripting
value = object.FillRule
object.FillRule = value

Property Value

FillRule

A value of the FillRule enumeration that specifies the fill behavior.

This property is read/write. The default value is EvenOdd.

Remarks

The EvenOdd enumeration value determines the "insideness" of a point on the shape. It draws a ray from the point to infinity in any direction and counts the number of path segments from the specified shape that the ray crosses. If the number is odd, the point is inside; if it is even, the point is outside.

The Nonzero enumeration value determines the "insideness" of a point on the shape by a different model than EvenOdd. It draws a ray from the point to infinity in any direction and then examines the places where a segment of the shape crosses the ray. Starting with a count of zero, it adds one each time a segment crosses the ray from left to right and subtracts one each time a path segment crosses the ray from right to left. After it counts the crossings, if the result is zero, the point is outside the path. Otherwise, it is inside.

Fill rule illustration

Applies To

Polygon

See Also

Shapes and Drawing in Silverlight Overview


FillRule Property (Polyline)

Gets or sets a value that specifies how the interior fill of the shape is determined.

XAML
<object FillRule="FillRule" .../>
Scripting
value = object.fillRule
object.fillRule = value

Property Value

FillRule

A value of the FillRule enumeration that specifies the fill behavior.

This property is read/write. The default value is EvenOdd.

Remarks

The EvenOdd enumeration value determines the "insideness" of a point on the shape. It draws a ray from the point to infinity in any direction and counts the number of path segments from the specified shape that the ray crosses. If the number is odd, the point is inside; if it is even, the point is outside.

The Nonzero enumeration value determines the "insideness" of a point on the shape by a different model than EvenOdd. It draws a ray from the point to infinity in any direction and then examines the places where a segment of the shape crosses the ray. Starting with a count of zero, it adds one each time a segment crosses the ray from left to right and subtracts one each time a path segment crosses the ray from right to left. After it counts the crossings, if the result is zero, the point is outside the path. Otherwise, it is inside.

Fill rule illustration

Applies To

Polyline


FontFamily Property

Gets or sets the preferred top-level font family for the content in this element.

XAML
<object FontFamily="string" .../>
Scripting
value = object.FontFamily
object.FontFamily = value

Property Value

string

A FontFamily object specifying the preferred font family, or a primary preferred font family with one or more fallback font families.

This property is read/write. The default value is "Portable User Interface", which is used as an alias for the font family value of "Lucida Sans Unicode, Lucida Grande".

Remarks

A font family is a set of typefaces that share the same family name, such as "Times New Roman", but that differ in features. These feature differences include font style, such as italic, and font weight, such as bold. The following illustration shows typefaces that are members of the "Times New Roman" font family.

Times New Roman font family

The following nine fonts are supported by Silverlight text elements:

Supported fonts for text elements

The SetFontSource method can be used as a way of adding downloaded font content to the existing collection of type faces for Silverlight text elements. The downloaded content can either be an individual font file or packaged content, such as a Zip file, that contains one or more font files. For more information, see Using a Downloader Object.

Applies To

LineBreak, Run, TextBlock

See Also

Text and Fonts Overview, FontSize, FontStretch, FontStyle, FontWeight


FontRenderingEmSize Property

Gets or sets the em size used for rendering the Glyphs.

XAML
<object FontRenderingEmSize="Double" .../>
Scripting
value = object.FontRenderingEmSize
object.FontRenderingEmSize = value

Property Value

Double

A value that represents the em size used for rendering.

This property is read/write. The default value is 0.

Remarks

The apparent visual size of the em size varies per font.

Note that the default FontRenderingEmSize is 0. Therefore in order to render anything with Glyphs you should specify a FontRenderingEmSize either in XAML or script. This is in contrast to TextBlock, which defaults its font sizing to 14.666 (pixels).

Applies To

Glyphs

See Also

TextBlock, Silverlight Brushes Overview,


FontSize Property

Gets or sets the font size for the content in this element.

XAML
<object FontSize="Double" .../>
Scripting
value = object.FontSize
object.FontSize = value

Property Value

Double

A non-negative value specifying the desired font size in pixels.

This property is read/write. The default value is 14.666 pixels.

Examples

The following XAML example shows how to use the FontSize property to define several differently-formatted text strings.

XAML
<!-- Display formatted text as Run objects within a TextBlock. -->
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007">

<TextBlock
  FontFamily="Arial" Width="400" Text="Sample text formatting runs">
  <LineBreak/>
  <Run Foreground="Maroon" FontFamily="Courier New" FontSize="24">Courier New 24</Run>
  <LineBreak/>
  <Run Foreground="Teal" FontFamily="Times New Roman" FontSize="18" FontStyle="Italic">Times New Roman Italic 18</Run>
  <LineBreak/>
  <Run Foreground="SteelBlue" FontFamily="Verdana" FontSize="14" FontWeight="Bold">Verdana Bold 14</Run>
</TextBlock>

</Canvas>

The following screenshot shows the rendered formatted text from the previous XAML content example.

TextBlock rendering different font sizes

Applies To

LineBreak, Run, TextBlock

See Also

Text and Fonts Overview, FontFamily, FontStretch, FontStyle, FontWeight


FontStretch Property

Gets or sets the font stretch for the content in this element.

XAML
<object FontStretch="FontStretch" .../>
Scripting
value = object.FontStretch
object.FontStretch = value

Property Value

FontStretch

A value specifying the desired font stretch.

This property is read/write. The default value is Normal.

Remarks

A font stretch describes the degree to which a font form is stretched from its normal aspect ratio, which is the original width to height ratio specified for the glyphs in the font.

The FontStretch values correspond to the usWidthClass definition in the OpenType specification. The usWidthClass represents an integer value between 1 and 9--lower values indicate narrower widths; higher values indicate wider widths. Refer to the enumeration table in FontWeight for usWidthClass information.

Note The FontStretch property value may not be the font stretch used during rendering due to font fallback. For example, if the font stretch ExtraExpanded is specified but Normal is the closest font stretch available, the value of FontStretch is still ExtraExpanded.

Applies To

LineBreak, Run, TextBlock

See Also

Text and Fonts Overview, FontFamily, FontSize, FontStyle, FontWeight


FontStyle Property

Gets or sets the font style for the content in this element.

XAML
<object FontStyle="FontStyle" .../>
Scripting
value = object.FontStyle
object.FontStyle = value

Property Value

FontStyle

A value specifying the desired font style.

This property is read/write. The default value is Normal.

Remarks

The characters in an italic font are truly slanted and appear as they were designed. They are not simulated by performing a shear transformation on the characters from a normal font. The following illustration shows the Normal and Italic font styles for the Palatino Linotype font.

Note The FontStyle property value may not be the font style used during rendering due to font fallback. For example, if the font style, Italic, is specified but Normal is the only font style available, the value of FontStyle is still Italic.

Applies To

LineBreak, Run, TextBlock

See Also

Text and Fonts Overview, FontFamily, FontSize, FontStretch, FontWeight


FontUri Property

Gets or sets the Uri that represents the location of the font used for rendering the Glyphs.

XAML
<object FontUri="string" .../>
Scripting
value = object.FontUri
object.FontUri = value

Property Value

string

A value that represents the URI source of the font.

This property is read/write. The default value is null.

Remarks

The URI you specify must use the same scheme as the hosting HTML page. Generally, the best practice for specifying the URI is to use a relative URI. The starting location for the relative reference is the HTML page that contains the current Silverlight plug-in. Setting a cross-domain URI or explicit file: scheme for FontUri is not permitted; a downloader error is thrown. Also, backslashes (\) in Silverlight URIs are not permitted; always use forward slashes (/). An additional URI consideration for FontUri is that the hash sign (#) has special meaning that overrides its usual HTML meaning; the hash is used to target a font offset within a TrueType collection.

FontUri supports fonts in the OTF and TTF formats.

FontUri supports obfuscated fonts. Obfuscated fonts are an XPS concept that is implemented by Microsoft technologies that use XPS as a document format. You can produce an XPS document that contains the necessary obfuscated subsetted font, rename the XPS document so that it can be recognized as a ZIP package, then extract the obfuscated font as a part. The part name will be a GUID. Changing the name of the obfuscated font file/part is not supported and must conform to the XPS obfuscation scheme. In addition, obfuscated fonts must have the "odttf" or "odttc" file extension.

If you use obfuscated fonts in this way, make sure that the XPS document that produces the obfuscated font has a matching UnicodeString content within the XPS content to what you will specify as the Glyph UnicodeString. Depending on your document save options, the XPS obfuscated font is typically drastically subsetted and will only include glyph mappings for the Unicode information from that XPS document.

FontUri also supports TTC (TrueType Collection) fonts. Using this mode, you can index a specific font face offset in the collection, in the format collectionname.ttc#n where n is the index within the collection. You can omit "#0" if you intend to reference the first font face in the collection.

Note As with most types of software, font files are licensed, rather than sold, and licenses that govern the use of fonts vary from vendor to vendor. As a developer it is your responsibility to ensure that you have the required license rights for any font you embed within a document or application, or otherwise redistribute.

Applies To

Glyphs

See Also

Text and Fonts Overview, TextBlock, Glyphs


FontWeight Property

Gets or sets the top-level font weight for the content in this element.

XAML
<object FontWeight="FontWeight" .../>
Scripting
value = object.FontWeight
object.FontWeight = value

Property Value

FontWeight

A value specifying the desired font weight.

This property is read/write. The default value is Normal.

Remarks

The FontWeights values correspond to the usWeightClass definition in the OpenType specification. The usWeightClass represents an integer value between 1 and 999. Lower values indicate lighter weights; higher values indicate heavier weights. Refer to the enumeration table in FontWeight for usWeightClass information.

Note The FontWeight property value may not be the font weight used during rendering due to font fallback. For example, if the font weight, ExtraBlack, is specified but Bold is the closest font weight available, the value of FontWeight is still ExtraBold.

A font weight describes the relative weight of a font, in terms of the lightness or heaviness of the strokes. Weight differences are generally differentiated by an increased stroke or thickness that is associated with a given character in a font, as compared to a "normal" character from that same font. The following illustration shows the Normal and UltraBold font weights for the Palatino Linotype.

For more information about the OpenType usWeightClass value, see the "Font File Tables" section of the OpenType specification.

Applies To

LineBreak, Run, TextBlock

See Also

Text and Fonts Overview, FontFamily, FontSize, FontStretch, FontStyle


Foreground Property

Gets or sets the Brush to apply to the content in this element.

XAML
<object Foreground="Brush" .../>
-or-
<object>
  <object.Foreground>
    <Brush" .../>
  </object.Foreground>
</object>
Scripting
value = object.Foreground
object.Foreground = value

Property Value

Brush

The brush used to apply to the text contents.

This property is read/write. The default value is Black.

Remarks

The Foreground property specifies a Brush for the rendered text. A Brush can represent a solid color, a linear or radial gradient, or an image.

Some brush types (SolidColorBrush) support a XAML attribute syntax, whereas other brush types (ImageBrush, LinearGradientBrush, RadialGradientBrush) only support an object element syntax. This is why two versions of XAML syntax are shown for this property.

When animating a Foreground, you must use indirect targeting. For instance, if you are animating the color of a SolidColorBrush that is the Foreground of a TextBlock, the syntax would be <ColorAnimation ... Storyboard.TargetProperty="(TextBlock.Foreground).(SolidColorBrush.Color)" />.

Examples

The following XAML example shows how to set the Foreground property to a solid color and a linear gradient. Notice that the Foreground property can also be used in a Run in order to display a different color than Foreground property value of the TextBlock.

XAML
<!-- TextBlock with a single brush applied to the text. -->
<TextBlock
  FontSize="32"
  FontWeight="Bold"
  Foreground="Maroon">
  Maroon
</TextBlock>

<!-- TextBlock with three brushes applied to the text. -->
<TextBlock
  Canvas.Top="60"
  FontFamily="Arial"
  FontSize="32"
  FontWeight="Bold"
  Foreground="Navy">
  Navy
  <Run Text="DodgerBlue " Foreground="DodgerBlue"/>
  <Run Text="LightSteelBlue " Foreground="LightSteelBlue"/>
</TextBlock>

<!-- TextBlock with a linear gradient brush applied to the text. -->
<TextBlock
  Canvas.Top="100"
  FontFamily="Verdana"
  FontSize="32"
  FontWeight="Bold">
  LINEAR GRADIENT BRUSH
  <TextBlock.Foreground>
    <LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
      <GradientStop Color="Red" Offset="0.0" />
      <GradientStop Color="Orange" Offset="0.2" />
      <GradientStop Color="Yellow" Offset="0.4" />
      <GradientStop Color="Green" Offset="0.6" />
      <GradientStop Color="Blue" Offset="0.8" />
      <GradientStop Color="Violet" Offset="1.0" />
    </LinearGradientBrush>
  </TextBlock.Foreground>
  <TextBlock.RenderTransform>
    <ScaleTransform ScaleY="3.0" />
  </TextBlock.RenderTransform>
</TextBlock>

The following image shows the rendered text from the previous XAML example.

TextBlocks rendering solid color and linear gradient brushes

Applies To

LineBreak, Run, TextBlock

See Also

Text and Fonts Overview, FontFamily, FontSize, FontStretch, FontStyle, FontWeight


From Property (ColorAnimation)

Gets or sets the animation's starting value.

XAML
<object From="Color" .../>
Scripting
value = object.From
object.From = value

Property Value

Color

The starting value of the animation.

This property is read/write. The default value is null.

Remarks

See Color for details on the various string formats that can be used to specify a color either in XAML or script.

The following table summarizes how the From, To, and By properties may be used together or separately to determine an animation's target values.

Properties Specified | Resulting Behavior
From | The animation progresses from the value specified by the From property to the base value of the property being animated.
From and To | The animation progresses from the value specified by the From property to the value specified by the To property.
From and By | The animation progresses from the value specified by the From property to the value specified by the sum of the From and By properties.
To | The animation progresses from the animated property's base value or a previous animation's output value to the value specified by the To property.
By | The animation progresses from the base value of the property being animated or a previous animation's output value to the sum of that value and the value specified by the By property.

Note If you set both the To and By properties, the To property takes precedence and the By property is ignored.

To use other interpolation methods or animate between more than two target values, use a ColorAnimationUsingKeyFrames object.

Applies To

ColorAnimation, ColorAnimationUsingKeyFrames

See Also

Animation Overview


From Property (DoubleAnimation)

Gets or sets the animation's starting value.

XAML
<object From="Double" .../>
Scripting
value = object.From
object.From = value

Property Value

Double

The starting value of the animation.

This property is read/write. The default value is null.

Remarks

The following table summarizes how the From, To, and By properties may be used together or separately to determine an animation's target values.

Properties specified | Resulting behavior
From | The animation progresses from the value specified by the From property to the base value of the property being animated.
From and To | The animation progresses from the value specified by the From property to the value specified by the To property.
From and By | The animation progresses from the value specified by the From property to the value specified by the sum of the From and By properties.
To | The animation progresses from the animated property's base value or a previous animation's output value to the value specified by the To property.
By | The animation progresses from the base value of the property being animated or a previous animation's output value to the sum of that value and the value specified by the By property.

Note If you set both the To and By properties, the To property takes precedence and the By property is ignored.

To use other interpolation methods or animate between more than two target values, use a DoubleAnimationUsingKeyFrames object.

Applies To

DoubleAnimation, DoubleAnimationUsingKeyFrames

See Also

Animation Overview


From Property (PointAnimation)

Gets or sets the animation's starting value.

XAML
<object From="Point" .../>
Scripting
value = object.From
object.From = value

Property Value

Point

The starting value of the animation.

This property is read/write. The default value is null.

Remarks

The Point structure parallels a convention that is supported by a type converter, such that properties that take a Point as their value can specify a Point as a formatted string. The type converter generates a new Point value based on processing the string. The type converter functions both for XAML usages and script usages. In both cases, you supply a quoted string. The format of that string is an X,Y value pair. Alternatively, you can use a space rather than a comma as the delimiter betweeen X and Y in the string.

See remarks in Point for details on scripting usages. The properties of PointAnimation are one of the cases where the object model provides access to an actual Point as a return value if you get this property at runtime. This means that you can potentially use the X and Y properties of the returned Point to adjust the animation either before it runs or while it runs.

The following table summarizes how the From, To, and By properties may be used together or separately to determine an animation's target values.

Properties Specified | Resulting Behavior
From | The animation progresses from the value specified by the From property to the base value of the property being animated.
From and To | The animation progresses from the value specified by the From property to the value specified by the To property.
From and By | The animation progresses from the value specified by the From property to the value specified by the sum of the From and By properties.
To | The animation progresses from the animated property's base value or a previous animation's output value to the value specified by the To property.
By | The animation progresses from the base value of the property being animated or a previous animation's output value to the sum of that value and the value specified by the By property.

Note If you set both the To and By properties, the To property takes precedence and the By property is ignored.

To use other interpolation methods or animate between more than two target values, use a PointAnimationUsingKeyFrames object.

Applies To

PointAnimation, PointAnimationUsingKeyFrames

See Also

PointAnimation, Animation Overview


FullScreen Property

Gets or sets whether the Silverlight plugin displays as a full-screen plugin.

Scripting (Instantiation)
Cannot be set during instantiation.
Scripting (Runtime)
value = silverlightObject.content.FullScreen
silverlightObject.content.FullScreen = value

Property Value

Boolean

Determines whether the Silverlight plugin displays as a full-screen plugin or embedded plugin.

This property is read/write. The default value is false.

Remarks

This property is available on the content sub-object of a Silverlight plugin instance.

If the value is set to true, the Silverlight plugin displays as a full-screen plugin. Otherwise, the Silverlight plugin displays as an embedded plugin.

You cannot set this property during instantiation. Typically you would switch to fullscreen only as a user-initiated action and therefore you would set fullscreen to true as part of a mouse or keyboard event handler.

A Silverlight plugin can display in either embedded mode or full-screen mode:

  • embedded mode--plugin displays within the Web browser.
  • full-screen mode--plugin displays on top of all other applications.

When the Silverlight plugin displays in embedded mode, the plugin is contained within the browser window. When Silverlight plugin displays in full-screen mode, the plugin resizes to the current resolution of the display and overlays all other applications, including the browser. The following images show the differences between embedded mode and full-screen mode:

Embedded mode and full-screen mode
Silverlight plugin displaying as embedded and full-screen mode

When a Silverlight plugin is displayed as full-screen, the following message appears briefly. This message alerts the user that the application is now in full-screen mode, and provides information on how to return to embedded mode:

Full-screen mode message

The OnFullScreenChange event occurs whenever the FullScreen property changes.

Performance Note For best performance, when your application goes into full screen, hide or disconnect from the tree all objects not being rendered in full screen mode. You can hide an object by setting its Visibility property to Collapsed.

Applies To

Silverlight Plugin

See Also

ActualHeight, ActualWidth, OnFullScreenChange, Silverlight Full Screen Support


GradientOrigin Property

Gets or sets the location of the two-dimensional focal point that defines the beginning of the gradient.

XAML
<object GradientOrigin="Point" .../>
Scripting
value = object.GradientOrigin
object.GradientOrigin = value

Property Value

Point

The location of the two-dimensional focal point of the gradient.

This property is read/write. The default value is (0.5,0.5).

Remarks

See remarks in Point for scripting usages of this property.

Specifying Relative or Absolute Values

The MappingMode property of a RadialGradientBrush determines whether its coordinate properties are interpreted as a relative or absolute value. By default, GradientOrigin is treated as relative, which corresponds to a MappingMode of RelativeToBoundingBox. A MappingMode of Absolute specifies that the GradientOrigin value is expressed in device independent pixels, not as a factor within the bounding box of the area where the brush is applied.

When GradientOrigin and Center are the same, this can be used to create the illusion/effect of a specular highlight from a "straight-on" lighting source applied to the object where the brush is used. By contrast, when GradientOrigin and Center are offset, this can create the illusion/effect of a specular highlight from an "off-center" lighting source. This technique is very useful for creating 3-D effects from out of 2-D objects.

Applies To

RadialGradientBrush

See Also

LinearGradientBrush, Silverlight Brushes Overview


GradientStops Property (LinearGradientBrush)

Gets or sets the collection of the brush's gradient stops.

XAML
<LinearGradientBrush ...>
  oneOrMoreGradientStops
</LinearGradientBrush>
Scripting
value = object.GradientStops
object.GradientStops = value

Property Value

GradientStopCollection

A collection of the GradientStop objects associated with the brush, each of which specifies a color and an offset along the brush's gradient axis.

This property is read/write. The default value is an empty GradientStopCollection.

Remarks

The XAML syntax for GradientStops is an example of an implicit collection syntax, where you can omit the GradientStopCollection object element, as well as the <object.GradientStops> property element. Instead, you generally include one or more GradientStop object elements as child elements of a LinearGradientBrush. For more information about XAML implicit collection syntax, see XAML Syntax Overview. (Explicitly including a GradientStopCollection object element is permissible XAML syntax, and might be useful if you intend to name the collection in XAML and manipulate its contents through script later.)

Generally a GradientStopCollection contains a minimum of two gradient stops.

Examples

The following example creates a LinearGradientBrush with four gradient stops in the implicit GradientStopCollection, which is used to paint a Rectangle.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <!-- This rectangle is painted with a diagonal linear gradient. -->
  <Rectangle Width="200" Height="100">
    <Rectangle.Fill>
      <LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
        <GradientStop Color="Yellow" Offset="0.0" />
        <GradientStop Color="Red" Offset="0.25" />
        <GradientStop Color="Blue" Offset="0.75" />
        <GradientStop Color="LimeGreen" Offset="1.0" />
      </LinearGradientBrush>
    </Rectangle.Fill>
  </Rectangle>
</Canvas>

Applies To

LinearGradientBrush

See Also

Silverlight Brushes Overview


GradientStops Property (RadialGradientBrush)

Gets or sets the collection of the brush's gradient stops.

XAML
<RadialGradientBrush ...>
  oneOrMoreGradientStops
</RadialGradientBrush>
Scripting
value = object.GradientStops
object.GradientStops = value

Property Value

GradientStopCollection

A collection of the GradientStop objects associated with the brush, each of which specifies a color and an offset along the brush's gradient axis.

This property is read/write. The default value is an empty GradientStopCollection.

Remarks

The XAML syntax for GradientStops is an example of an implicit collection syntax, where you can omit the GradientStopCollection object element, as well as the <object.GradientStops> property element. Instead, you generally include one or more GradientStop object elements as child elements of a LinearGradientBrush. For more information about XAML implicit collection syntax, see XAML Syntax Overview. (Explicitly including a GradientStopCollection object element is permissible XAML syntax, and might be useful if you intend to name the collection in XAML and manipulate its contents through script later.)

Generally a GradientStopCollection contains a minimum of two gradient stops.

Examples

The following example creates a RadialGradientBrush with three gradient stops in the implicit GradientStopCollection. The three gradient stops specify a brush with a varying transparency, which is then applied as the OpacityMask for an Image.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <Image Source="sampleImages/forest.jpg" Height="100">
    <Image.OpacityMask>
      <RadialGradientBrush Center="0.5,0.5">
        <!-- This gradient stop is partially transparent. -->
        <GradientStop Color="#00000000" Offset="1" />
        <!-- This gradient stop is partially transparent. -->
        <GradientStop Color="#20000000" Offset="0.8" />
        <!-- This gradient stop is fully opaque. -->
        <GradientStop Color="#FF000000" Offset="0" />
      </RadialGradientBrush>
    </Image.OpacityMask>
  </Image>
</Canvas>

This example displays as follows:

RadialGradientBrush applied to OpacityMask of an image

Applies To

RadialGradientBrush

See Also

Silverlight Brushes Overview


Height Property (DrawingAttributes)

Gets or sets the height of the associated stroke.

XAML
<DrawingAttributes Height="Double" .../>
Scripting
value = object.Height
object.Height = value

Property Value

Double

The height of the associated stroke.

This property is read/write. The default value is 3.0.

Examples

The following JavaScript example simulates 3 different pen types (pen, marker and highlighter) by setting the Color, Height, OutlineColor and Width DrawingAttributes properties . First a DrawingAttributes object is created, then it is appended to the Stroke object. The DrawingAttributes properties are then set by one of the three events that simulate a pen type. The "EraseCanvas" event handler clears all the Strokes from the Canvas.

JavaScript
var agCtrl;
var inkPresenter; // Corresponds to InkPresenter element in xaml
var newStroke = null; // The Stroke variable we'll use here in mouse handlers
// DrawingAttributes variables
var daWidth = 2;
var daHeight = 2;
var daColor = "Black";
var daOutlineColor = "Black";

function root_Loaded(sender, args)
{
    // Get the html object which contains the Silverlight plug-in
    agCtrl = sender.GetHost();
    inkPresenter = sender.findname("inkPresenterElement");
}

// Capture mouse movement when the left button is pressed and create the stroke
function InkPresenterMouseDown(sender,args)
{
   inkPresenter.CaptureMouse();

   newStroke = agCtrl.content.createFromXaml('<Stroke/>');

   var da = agCtrl.content.CreateFromXaml('<DrawingAttributes/>');
   newStroke.DrawingAttributes = da;

   // Set the drawing attributes properties
   newStroke.DrawingAttributes.Width = daWidth;
   newStroke.DrawingAttributes.Height = daHeight;
   newStroke.DrawingAttributes.Color = daColor;
   newStroke.DrawingAttributes.OutlineColor = daOutlineColor;

   newStroke.StylusPoints.AddStylusPoints(args.GetStylusPoints(inkPresenter));
   inkPresenter.Strokes.Add(newStroke);
}

// Add the new points to the Stroke we're working with
function InkPresenterMouseMove(sender,args)
{
   if (newStroke != null)
   {
      newStroke.StylusPoints.AddStylusPoints(args.GetStylusPoints(inkPresenter));
   }
}

// Release the mouse
function InkPresenterMouseUp(sender,args)
{
   newStroke = null;
   inkPresenter.ReleaseMouseCapture();
}

// Set the Drawing Attributes for a pen
function SelectPen(sender, args)
{
  daWidth = 1;
  daHeight = 1;
  daColor = "Black";
  daOutlineColor = "Black";
}

// Set the Drawing Attributes for a marker
function SelectMarker(sender, args)
{
  daWidth = 10;
  daHeight = 4;
  daColor = "Blue";
  daOutlineColor = "Blue";
}

// Set the Drawing Attributes for a highlighter
function SelectHighlighter(sender, args)
{
  daWidth = 25;
  daHeight = 5;
  daColor = "Yellow";
  daOutlineColor = "Yellow";
}

// Erase all strokes from the canvas
function EraseCanvas(sender, args)
{
  inkPresenter.Strokes.Clear();
}

The XAML sample below creates the canvas and 4 buttons that are used to select the different pen types and the erase all feature that is simulated by the Javascript events above.

XAML
<Canvas xmlns="http://schemas.microsoft.com/client/2007"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Loaded="root_Loaded"
        x:Name="root"
        Width="600" Height="400">
  <InkPresenter
         x:Name="inkPresenterElement"
        Background="transparent"
        Width="600" Height="400"
        MouseLeftButtonDown="InkPresenterMouseDown"
        MouseMove="InkPresenterMouseMove"
        MouseLeftButtonUp="InkPresenterMouseUp"/>

<!-- Pen Button -->
    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="40"
      Stroke="Gray" Fill="Black" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>
    <TextBlock
      Height="21" Width="78"
      Canvas.Top="380" Canvas.Left="71"
      Foreground="Gray"
      FontFamily="Verdana" FontSize="12">Select Pen</TextBlock>

    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="40"
      x:Name="selectPen" MouseLeftButtonDown="SelectPen"
      Stroke="Transparent" Fill="Transparent" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>

<!-- Marker Button -->
    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="170"
      Stroke="Gray" Fill="Black" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>

    <TextBlock
      Height="21" Width="78"
      Canvas.Top="380" Canvas.Left="191"
      Foreground="Gray"
      FontFamily="Verdana" FontSize="12">Select Marker</TextBlock>

    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="170"
      x:Name="selectMarker" MouseLeftButtonDown="SelectMarker"
      Stroke="Transparent" Fill="Transparent" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>

<!-- Highlighter Button -->
    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="300"
      Stroke="Gray" Fill="Black" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>

    <TextBlock
      Height="21" Width="78"
      Canvas.Top="380" Canvas.Left="310"
      Foreground="Gray"
      FontFamily="Verdana" FontSize="12">Select Highlighter</TextBlock>

    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="300"
      x:Name="selectHighlighter" MouseLeftButtonDown="SelectHighlighter"
      Stroke="Transparent" Fill="Transparent" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>

<!-- Erase Canvas Button -->
    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="430"
      Stroke="Gray" Fill="Black" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>

    <TextBlock
      Height="21" Width="78"
      Canvas.Top="380" Canvas.Left="463"
      Foreground="Gray"
      FontFamily="Verdana" FontSize="12">Erase All</TextBlock>

    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="430"
      x:Name="eraseCanvas" MouseLeftButtonDown="EraseCanvas"
      Stroke="Transparent" Fill="Transparent" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>
</Canvas>

Applies To

DrawingAttributes

See Also

Stroke, Color, OutlineColor, Width, DrawingAttributes, DrawingAttributes (Stroke)


Height Property (Rect)

Gets or sets the Y-coordinate value of this Rect.

XAML
See Remarks.
Scripting
value = object.Height
object.Height = value

Property Value

Double

The height value of this Rect structure.

This property is read/write. The default value is 0.

Remarks

Property values for a Rect and an object for Rect are not available for all cases where Rect is used as a property type. See Remarks for Rect.

The properties of a Rect do not have a XAML usage because there is no way to create a Rect in XAML as an object element. Instead, you always specify a Rect as a string that is either provided as a XAML attribute value or set to a property value in script. Each of these cases is supported by a type conversion behavior. If the particular property being set can return a Rect as an object to script, then the value as provided in the original string can be retrieved as the Height value of that Rect object.

Applies To

Rect

See Also

Ink Support In Microsoft Silverlight, Silverlight Geometries Overview, Rect


Height Property (UIElement)

Gets or sets the height of the object.

XAML
<object Height="Double" .../>
Scripting
value = object.Height
object.Height = value

Property Value

Double

The height of the object.

This property is read/write. The default value is 0.

Remarks

Many of the UIElement derived objects are also derived from Shape. Not all of the Shape classes typically use Height or Width to specify their appearance, and instead use specific properties that might define a set of points. In this case a Height or Width is calculated, but is not typically set directly. For details, see Shapes and Drawing in Silverlight Overview.

TextBlock is a container object that displays text within it. The size of that text can influence the size of the rendered TextBlock, so TextBlock supports two additional properties that expose that calculated size, ActualHeight and ActualWidth. For details, see Text and Fonts Overview.

Applies To

Canvas, Ellipse, Glyphs, Image, InkPresenter, Line, MediaElement, Path, Polygon, Polyline, Rectangle, TextBlock

See Also

Object Layout in Silverlight


ImageSource Property

Gets or sets the URI of the image file source displayed by this ImageBrush.

XAML
<object ImageSource="string" .../>
Scripting
value = object.ImageSource
object.ImageSource = value

Property Value

string

The image displayed by this ImageBrush.

This property is read/write. The default value is null.

Remarks

The ImageSource property can be used to reference images in the JPEG and PNG file formats.

The string provided for the ImageSource property is interpreted as a Uniform Resource Identifier (URI). This is in contrast to an Internationalized Resource Identifiers (IRI). This distinction means that characters used to identify an ImageSource that are outside of US-ASCII will need to be encoded.

Relative references are permitted. The starting location for the relative reference is the HTML page that contains the current Silverlight plug-in.

Cross-domain URIs are permitted, and specifying the scheme is permitted, but mixing URI schemes (such as accessing an HTTPS image from a Silverlight plug-in hosted on an HTTP-served HTML page) is not permitted. The JPEG and PNG filename extensions are not required to be in the URI, but if the retrieved file is not determined to be either in JPEG or PNG format, a runtime exception is thrown.

If you are not accessing cross-domain sources, you should consider using SetSource rather than setting ImageSource directly. This provides the advantage of being able to track the download. Also, you can download images as a package and access parts from within the package.

In JavaScript, you can set the value to null or empty string at runtime to cause the image to unload and no longer render. Doing so does not fire an ImageFailed event. In contrast, setting an ImageSource to a URI value that does not resolve or that does not result in a valid image file download will fire an ImageFailed event. Also, a SetValue error is thrown, even if ImageFailed is handled.

You can specify an initial XAML value of "" (empty string) and then set the value in script at a later time, to create a nonrendering placeholder.

The ImageFailed event can occur if the initial ImageSource attribute value in XAML does not specify a valid source.

Applies To

ImageBrush

See Also

ImageFailed, Using a Downloader Object


Indices Property

Gets or sets the glyph indices that represent the Glyphs object.

XAML
<object Indices="string" .../>
Scripting
value = object.Indices
object.Indices = value

Property Value

string

A value that defines glyph indices as well as other glyph specifics in a string mini-language.

This property is read/write. The default value is null.

Remarks

The format for glyph indices is complex and is not documented completely here. The following is an approximate grammar of one index point:

[GlyphIndex][,[Advance][,[uOffset][,[vOffset]]]]

Each such index point is then separated in the string by a semicolon (;).

Term | Underlying type | Definition
GlyphIndex | integer | Index of a glyph in the font.
Advance | double | Placement for next glyph relative to origin of this glyph.
uOffset, vOffset | double | Offset relative to glyph origin to move this glyph. Usually used to attach marks to base characters.

The most relevant purpose for the Indices property in Silverlight is to use it for spacing the characters within the specified Unicode string, rather than for full specification of each glyph. In this case you would always use the Unicode string for the true indices and leave GlyphIndex blank in each index point. For example, to apply an advance spacing of 80 for each character in the Unicode string "Hello", the Indices value would be ",80;,80;,80;,80;,80;".

For more information see this document in the Windows Presentation Foundation (WPF) area of the .NET SDK: Introduction to the GlyphRun Object and Glyphs Element. This document discusses glyphs within the WPF framework, but the description of the indices format is applicable to glyphs in Silverlight.

Applies To

Glyphs

See Also

Text and Fonts Overview, TextBlock,


InitParams Property

Gets or sets an optional set of user-defined initialization parameters.

Scripting (Instantiation) | Silverlight.CreateObject(,,,,,initParams) -or- Silverlight.CreateObjectEx({initparams:initParams})
Scripting (Runtime) | value = silverlightObject.InitParams

Property Value

string

Specifies a string that represents a set of user-defined initialization parameters. The string format of the value is user-defined.

This property is settable only as an initialization parameter, and is read-only for scripting thereafter. The default value is null.

Remarks

The InitParams property cannot be set after initialization. The initParams initialization parameter specifies user-defined parameter values. These parameters values can be retrieved at run time by accessing the plug-in's InitParams property. InitParams provides a convenient way to pass your own string values from the HTML DOM into the Silverlight object model. For more information on how this property is set during plug-in initialization, see Using CreateSilverlight.js and Silverlight.js.

Generally, if you have more than one string atom to pass, you would use some character (such as a comma) as a delimiter in the combined InitParams string and then split the string into atoms again from your Silverlight JavaScript code.

Examples

The following JavaScript example shows how to specify the initParams parameter value in the user-defined CreateSilverlight method in CreateSilverlight.js.

JavaScript
function createSilverlight()
{
    Silverlight.createObject(
        "plugin.xaml",                  // Source property value.
        parentElement,                  // DOM reference to hosting DIV tag.
        "myPlugin",                    // Unique plug-in id value.
        {                               // Plug-in properties.
            width:'600',                // Width of rectangular region of plug-in in pixels.
            height:'200',               // Height of rectangular region of plug-in in pixels.
            version:'1.0'               // Plug-in version to use.
        },
        { },                            // No events defined -- use empty list.
        "param1, param2");              // InitParams property value.
}

To access the value of the initParams initialization parameter values at run time, use the InitParams property of the plug-in. The following JavaScript example shows how to retrieve the parameter values using the InitParams property.

JavaScript
function onLoaded(sender, eventArgs)
{
    // Retrieve a reference to the plug-in.
    var plugin = sender.getHost();

    // Retrieve the InitParams value and split comma-delimited string.
    var params = plugin.initParams.split(",");

    // Display the parameter values.
    var msg = "Params: ";
    for (var i = 0; i < params.length; i++)
    {
        msg += params[i] + " ";
    }

    alert(msg);
}

Applies To

Silverlight Plug-in

See Also

Using CreateSilverlight.js and Silverlight.js


Inlines Property

Gets the collection of inline text elements within a TextBlock.

XAML
<object ...>
  oneOrMoreInlineElements
</object>
Scripting
value = object.Inlines

Property Value

Inlines

A collection that holds all inline text elements within the TextBlock.

This property is read-only. The default value is an empty collection.

Remarks

You can add inline text elements such as Run or LineBreak to the collection, by first creating the element with CreateFromXaml and then passing the return value to Inlines.Add or Inlines.Insert. Unlike the initial XAML markup, you cannot simply add a string. You must create a new Run that has string content in order to add text to an existing Inlines collection.

You can also remove elements from the existing collection using Inlines.Remove or Inlines.RemoveAt.

You can access elements in the existing collection with Inlines.GetItem, or clear the entire collection with Inlines.Clear.

A TextBlock can be thought of as having two simultaneous object models within it:

  • A representation as a Text property, which represents only string content (no formatting other than the formatting declared at the TextBlock level).
  • A representation as an Inlines collection. The collection contains primarily Run objects, each of which can declare its own formatting properties such as FontSize. The Text property still returns a value (the appended text of all Run elements in the Inlines) but does not capture any formatting applied to the Run elements. If created from XAML as inner text of a <TextBlock> tag, or by setting to Text property, the Inlines collection contains a single Run that contains that text.

You can choose to work with either object model. However, you should be aware that if you adjust the text by appending to the Text value, when the text is actually a series of text elements with individual formatting in an Inlines collection, you will flatten the previous Inlines collection content and replace it with a single new unformatted Run with your new text. This generally is not a desired behavior.

A TextBlock can contain mixed inner text and inline elements. In this case, each of the inner text sections is parsed and converted into a Run, rather than being preserved as true inner text of TextBlock if you were to examine the output in an XML DOM. Because of this behavior, you can freely mix inner text and inline elements; inner text can appear before any inlines or after them, and multiple blocks of inner text can be mixed with multiple inlines.

The Inlines collection is implicitly created by parsing the TextBlock content. TextBlock.Inlines as a property element is marginally permitted in XAML. The marginal aspect is because even XML white space is interpreted as possible content of the TextBlock, and if any content is detected the parser will populate the implicit Inlines collection using that content as an initial Run. Defining TextBlock.Inlines thereafter is thus interpreted as an attempt to set Inlines twice. Therefore the only way to specify TextBlock.Inlines would be if there were was no white space at all between the <TextBlock> object element and <TextBlock.Inlines> object element.

The XAML syntax for Inlines is an example of an implicit collection syntax, where you omit an actual Inlines object element. Instead, you generally include one or more inline types (Run and LineBreak elements) as child elements of a TextBlock. For more information about XAML implicit collection syntax, see XAML Syntax Overview. In addition to the implicit collection syntax of inlines, TextBlock also supports setting content as inner text, or by specifically setting the value of Text with a string. For details, see TextBlock.

Applies To

TextBlock

See Also

Text and Fonts Overview, Using the createFromXaml Method, XAML Syntax Overview, Collection


IsClosed Property

Gets or sets a value that specifies whether this figure's first and last segments are connected.

XAML
<object IsClosed="Boolean" .../>
Scripting
value = object.IsClosed
object.IsClosed = value

Property Value

Boolean

true if this figure's first and last segments are connected; otherwise, false.

This property is read/write. The default value is false.

Remarks

Setting this property to true connects the first segment (and the StartPoint of the PathFigure) to the final point of the last segment defined in the Segments collection.

Applies To

PathFigure

See Also

Figures, StartPoint, Path Markup Syntax


IsHitTestVisible Property

Gets or sets whether the contained area of this UIElement can be used for hit-testing.

XAML
<object IsHitTestVisible="Boolean" .../>
Scripting
value = object.IsHitTestVisible
object.IsHitTestVisible = value

Property Value

Boolean

Determines whether the contained area of this UIElement can be used for hit-testing.

This property is read/write. The default value is true.

Remarks

If this property is set to false, the element ignores any events, such as MouseLeftButtonUp.

Applies To

Canvas, Ellipse, Glyphs, Image, InkPresenter, Line, MediaElement, Path, Polygon, Polyline, Rectangle, Shape, TextBlock


IsInverted Property

Gets or sets a value that specifies whether the stylus is inverted.

XAML
Cannot be used in XAML.
Scripting
value = object.IsInverted
object.IsInverted = value

Property Value

Boolean

true if the stylus is inverted; otherwise, false.

This property is read/write. The default value is false.

Remarks

When the stylus is inverted, it indicates erase mode. Although the property is technically settable, this is of little practical use because the StylusInfo is merely reporting the real state of the input device.

Applies To

StylusInfo

Examples

JavaScript
// Add the new points to the Stroke we're working with or
// delete strokes if stylus is inverted. Thus, implementing back of pen erase.
function InkPresenterMouseMove(sender,args)
{
  // Erase mode?
  if (args.GetStylusInfo().IsInverted)
  {
    // Use HitTest to get all the strokes that were intersected
    var hitStrokes = inkPresenter.Strokes.HitTest(args.GetStylusPoints(inkPresenter));

    // Remove the strokes that were intersected above
    for (var i = 0; i < hitStrokes.Count; i++)
    {
      inkPresenter.Strokes.Remove(hitStrokes.GetItem(i));
    }
  }
  else
  {
    if (newStroke != null)
    {
      newStroke.StylusPoints.AddStylusPoints(args.GetStylusPoints(inkPresenter));
    }
  }
}

See Also

StylusInfo


IsLargeArc Property

Gets or sets a value that indicates whether the arc should be greater than 180 degrees.

XAML
<object IsLargeArc="Boolean" .../>
Scripting
value = object.IsLargeArc
object.IsLargeArc = value

Property Value

Boolean

true if the arc should be greater than 180 degrees; otherwise, false.

This property is read/write. The default value is false.

Remarks

For most arcs of a particular position, size, and rotation, there are four different arcs that can be drawn; the IsLargeArc and SweepDirection properties indicate which arc to use.

Of the four candidate arc sweeps, two represent large arcs with sweeps of 180 degrees or greater, and two represent smaller arcs with sweeps 180 degrees or less. If IsLargeArc is true, then one of the two larger arc sweeps is chosen; otherwise, if is false, one of the smaller arc sweeps is chosen. The remaining two arc candidates are each drawn in a different direction: Counterclockwise or Clockwise. The SweepDirection property specifies which one to use.

The following illustration shows two elliptical arcs that are identical except for their IsLargeArc settings.

ArcSegments with different IsLargeArc settings

Applies To

ArcSegment

See Also

Path Markup Syntax, SweepDirection


IsLoaded Property

Gets a value that indicates whether the Silverlight plug-in is loaded.

Scripting (Instantiation) | Cannot be set during instantiation.
Scripting (Runtime) | value = silverlightObject.IsLoaded

Property Value

Boolean

true if the Silverlight plug-in is loaded; otherwise, false.

This property is read-only. The default value is false.

Remarks

The IsLoaded property is set to true after the XAML content in the Silverlight plug-in has completely loaded, but before the OnLoad event occurs.

Applies To

Silverlight Plug-in

See Also

OnLoad, Using a Silverlight Plug-in


IsMuted Property

Gets or sets a value that indicates whether the audio is muted.

XAML
<object IsMuted="Boolean" .../>
Scripting
value = object.IsMuted
object.IsMuted = value

Property Value

Boolean

true if audio is muted; otherwise, false.

This property is read/write. The default value is false.

Applies To

MediaElement

See Also

Silverlight Properties


Key Property

Gets the keyboard key associated with the event.

XAML | This property cannot be used in XAML.
Scripting | value = eventargs.Key

Property Value

Key

The Key referenced by the event.

Remarks

Key codes have possible platform variations. For details see Silverlight Keyboard Support.

Check Ctrl and Shift to determine if the key event is a key combination.

Applies To

KeyboardEventArgs

See Also

Silverlight Keyboard Support, Silverlight Events


KeyFrames Property (ColorAnimationUsingKeyFrames)

Gets or sets the collection of ColorKeyFrame objects that define the animation.

XAML Property Element Usage
<ColorAnimationUsingKeyFrames ...>
  oneOrMoreColorKeyFrames
</ColorAnimationUsingKeyFrames>
Scripting
value = object.KeyFrames
object.KeyFrames = value

Property Value

ColorKeyFrameCollection

The collection of ColorKeyFrame objects that define the key frames for the animation.

This property is read/write. The default value is null.

Remarks

The XAML syntax for properties that use a ColorKeyFrameCollection is an example of an implicit collection syntax, where you can omit the ColorKeyFrameCollection object element, as well as the <ColorAnimationUsingKeyFrames.KeyFrames> property element. Instead, you generally include one or more DiscreteColorKeyFrame, LinearColorKeyFrame, or SplineColorKeyFrame object elements as child elements of a ColorAnimationUsingKeyFrames. For more information about XAML implicit collection syntax, see XAML Syntax Overview. (Explicitly including a ColorKeyFrameCollection object element is permissible XAML syntax, and might be useful if you intend to name the collection in XAML and manipulate its contents through script later.)

Applies To

ColorAnimationUsingKeyFrames

See Also

Animation Overview


KeyFrames Property (DoubleAnimationUsingKeyFrames)

Gets or sets the collection of DoubleKeyFrame objects that define the animation.

XAML Usage
<DoubleAnimationUsingKeyFrames ...>
  oneOrMoreDoubleKeyFrames
</DoubleAnimationUsingKeyFrames>
Scripting
value = object.KeyFrames
object.KeyFrames = value

Property Value

DoubleKeyFrameCollection

The collection of DoubleKeyFrame objects that define the animation.

This property is read/write. The default value is null.

Remarks

The XAML syntax for properties that use a DoubleKeyFrameCollection is an example of an implicit collection syntax, where you can omit the DoubleKeyFrameCollection object element, as well as the <DoubleAnimationUsingKeyFrames.KeyFrames> property element. Instead, you generally include one or more DiscreteDoubleKeyFrame, LinearDoubleKeyFrame, or SplineDoubleKeyFrame object elements as child elements of a DoubleAnimationUsingKeyFrames. For more information about XAML implicit collection syntax, see XAML Syntax Overview. (Explicitly including a DoubleKeyFrameCollection object element is permissible XAML syntax, and might be useful if you intend to name the collection in XAML and manipulate its contents through script later.)

Applies To

DoubleAnimationUsingKeyFrames

See Also

Animation Overview


KeyFrames Property (PointAnimationUsingKeyFrames)

Gets or sets the collection of PointKeyFrame objects that define the animation.

XAML Property Element Usage
<PointAnimationUsingKeyFrames ...>
  oneOrMorePointKeyFrames
</PointAnimationUsingKeyFrames>
Scripting
value = object.KeyFrames
object.KeyFrames = value

Property Value

PointKeyFrameCollection

The collection of PointKeyFrame objects that define the animation.

This property is read/write. The default value is null.

Remarks

The XAML syntax for properties that use a PointKeyFrameCollection is an example of an implicit collection syntax, where you can omit the PointKeyFrameCollection object element, as well as the <PointAnimationUsingKeyFrames.KeyFrames> property element. Instead, you generally include one or more DiscretePointKeyFrame, LinearPointKeyFrame, or SplinePointKeyFrame object elements as child elements of a PointAnimationUsingKeyFrames. For more information about XAML implicit collection syntax, see XAML Syntax Overview. (Explicitly including a PointKeyFrameCollection object element is permissible XAML syntax, and might be useful if you intend to name the collection in XAML and manipulate its contents through script later.)

Applies To

PointAnimationUsingKeyFrames

See Also

Animation Overview, Point


KeySpline Property (SplineColorKeyFrame)

Gets or sets the two control points that define animation progress for this key frame.

XAML
<object KeySpline="KeySpline" .../>
Scripting
value = object.KeySpline
object.KeySpline = value

Property Value

KeySpline

The two control points that specify the cubic Bezier curve which defines the progress of the key frame.

This property is read/write. The default value is "0,0 1,1".

Remarks

To specify a KeySpline, use the following string format: "cp1x,cp1y cp2x,cp2y". For details, see remarks for KeySpline.

To understand how a KeySpline works, it is helpful to understand cubic Bezier curves. A cubic Bezier curve is defined by a start point, an end point, and two control points. The two coordinates in the KeySpline defines those two control points. When describing key splines, the start point of the Bezier curve is always 0, and the end point is always 1, which is why you define only the two control points. The resulting curve specifies how an animation is interpolated during a time segment; that is, the curve represents the rate of change in the animation's target attribute over the time segment.

Applies To

SplineColorKeyFrame

See Also

Animation Overview


KeySpline Property (SplineDoubleKeyFrame)

Gets or sets the two control points that define animation progress for this key frame.

XAML
<object KeySpline="KeySpline" .../>
Scripting
value = object.KeySpline
object.KeySpline = value

Property Value

KeySpline

The two control points that specify the cubic Bezier curve which defines the progress of the key frame.

This property is read/write. The default value is "0,0 1,1".

Remarks

To specify a KeySpline, use the following string format: "cp1x,cp1y cp2x,cp2y". For details, see remarks for KeySpline.

To understand how a KeySpline works, it is helpful to understand cubic Bezier curves. A cubic Bezier curve is defined by a start point, an end point, and two control points. The two coordinates in the KeySpline defines those two control points. When describing key splines, the start point of the Bezier curve is always 0, and the end point is always 1, which is why you define only the two control points. The resulting curve specifies how an animation is interpolated during a time segment; that is, the curve represents the rate of change in the animation's target attribute over the time segment.

Applies To

SplineColorKeyFrame

See Also

Animation Overview


KeySpline Property (SplinePointKeyFrame)

Gets or sets the two control points that define animation progress for this key frame.

XAML
<object KeySpline="KeySpline" .../>
Scripting
value = object.KeySpline
object.KeySpline = value

Property Value

KeySpline

The two control points that specify the cubic Bezier curve which defines the progress of the key frame.

This property is read/write. The default value is "0,0 1,1".

Remarks

To specify a KeySpline, use the following string format: "cp1x,cp1y cp2x,cp2y". For details, see remarks for KeySpline.

To understand how a KeySpline works, it is helpful to understand cubic Bezier curves. A cubic Bezier curve is defined by a start point, an end point, and two control points. The two coordinates in the KeySpline defines those two control points. When describing key splines, the start point of the Bezier curve is always 0, and the end point is always 1, which is why you define only the two control points. The resulting curve specifies how an animation is interpolated during a time segment; that is, the curve represents the rate of change in the animation's target attribute over the time segment.

Applies To

SplinePointKeyFrame

See Also

Animation Overview


KeyTime Property (ColorKeyFrame)

Gets or sets the time at which the key frame's target Value should be reached.

XAML
<object KeyTime="KeyTime" .../>
Scripting
value = object.KeyTime
object.KeyTime = value

Property Value

KeyTime

The time at which the key frame's current value should be equal to its Value property.

This property is read/write. The default value is null.

Remarks

The string format for specifying a KeyTime is [days.]hours:minutes:seconds[.fractionalSeconds]. See KeyTime.

Creating a Duration, KeyTime, RepeatBehavior, or TimeSpan in XAML is only possible through a type conversion syntax when setting a property such as KeyTime that takes one of these types, with the value specified as an attribute string. The string format for all three is identical except that Duration can take the literals "Automatic" and "Forever" and RepeatBehavior can take the literal "Forever".

Although they can be obtained as objects from property values, the properties and methods on Duration, KeyTime or TimeSpan have very little practical usage other than possibly resetting the Seconds property.

Applies To

DiscreteColorKeyFrame, LinearColorKeyFrame, SplineColorKeyFrame

See Also

Animation Overview


KeyTime Property (DoubleKeyFrame)

Gets or sets the time at which the key frame's target Value should be reached.

XAML
<object KeyTime="KeyTime" .../>
Scripting
value = object.KeyTime
object.KeyTime = value

Property Value

KeyTime

The time at which the key frame's current value should be equal to its Value property.

This property is read/write. The default value is null.

Remarks

The string format for specifying a KeyTime is [days.]hours:minutes:seconds[.fractionalSeconds]. See KeyTime.

Creating a Duration, KeyTime, RepeatBehavior, or TimeSpan in XAML is only possible through a type conversion syntax when setting a property such as KeyTime that takes one of these types, with the value specified as an attribute string. The string format for all three is identical except that Duration can take the literals "Automatic" and "Forever" and RepeatBehavior can take the literal "Forever".

Although they can be obtained as objects from property values, the properties and methods on Duration, KeyTime or TimeSpan have very little practical usage other than possibly resetting the Seconds property.

Applies To

DiscreteDoubleKeyFrame, LinearDoubleKeyFrame, SplineDoubleKeyFrame

See Also

Animation Overview


KeyTime Property (PointKeyFrame)

Gets or sets the time at which the key frame's target Value should be reached.

XAML
<object KeyTime="KeyTime" .../>
Scripting
value = object.KeyTime
object.KeyTime = value

Property Value

KeyTime

The time at which the key frame's current value should be equal to its Value property.

This property is read/write. The default value is null.

Remarks

The string format for specifying a KeyTime is [days.]hours:minutes:seconds[.fractionalSeconds]. See KeyTime.

Creating a Duration, KeyTime, RepeatBehavior, or TimeSpan in XAML is only possible through a type conversion syntax when setting a property such as KeyTime that takes one of these types, with the value specified as an attribute string. The string format for all three is identical except that Duration can take the literals "Automatic" and "Forever" and RepeatBehavior can take the literal "Forever".

Although they can be obtained as objects from property values, the properties and methods on Duration, KeyTime or TimeSpan have very little practical usage other than possibly resetting the Seconds property.

Applies To

DiscretePointKeyFrame, LinearPointKeyFrame, SplinePointKeyFrame

See Also

Animation Overview


LineNumber Property (ParserErrorEventArgs)

Gets or sets the line number at which the parser error occurred.

XAML | Cannot be used in XAML.
Scripting | value = eventargs.LineNumber

Property Value

integer

The number of the line the parser error occurred on.

This property is read/write. The default value is 0.

Remarks

Because you cannot raise your own errors in the Silverlight 1.0 eventing model, the settable aspect of this property does not have a practical usage. Usually, you will only use this property to get its value.

Examples

The following JavaScript example shows the portion of an event handler that displays error information specific to parser errors.

JavaScript
    // errorArgs is an instance of ParserErrorEventArgs
    if(errorArgs.ErrorType == "ParserError")
    {
      var parserErrorMsg = "Silverlight Parser Error  \n\n";

      // Basic error event informaiton.
      parserErrorMsg += "Error Type:    " + errorArgs.errorType     + "\n";
      parserErrorMsg += "Error Message: " + errorArgs.errorMessage  + "\n";
      parserErrorMsg += "Error Code:    " + errorArgs.errorCode  + "\n";

      //Parser specific error event information.
      parserErrorMsg += "XamlFile:      " + errorArgs.xamlFile      + "\n";
      parserErrorMsg += "XmlElement:    " + errorArgs.xmlElement    + "\n";
      parserErrorMsg += "XmlAttribute:  " + errorArgs.xmlAttribute  + "\n";
      parserErrorMsg += "Line:          " + errorArgs.lineNumber    + "\n";
      parserErrorMsg += "Position:      " + errorArgs.charPosition  + "\n";

      // Display the error message.
      alert(parserErrorMsg);
    }

Applies To

ParserErrorEventArgs

See Also

Silverlight Application Scripting Error Handling, ErrorEventArgs, RuntimeErrorEventArgs


LineNumber Property (RuntimeErrorEventArgs)

Gets the line number at which the runtime error occurred.

XAML | Cannot be used in XAML.
Scripting | value = eventargs.LineNumber

Property Value

integer

The number of the line the runtime error occurred on.

This property is read-write. The default value is 0.

Remarks

This property is technically read/write, but there is generally no reason to set it, because the property is just reporting information from existing errors.

Examples

The following JavaScript example shows the portion of an event handler that displays error information specific to runtime errors.

JavaScript
    // errorArgs is an instance of RuntimeErrorEventArgs
    if(errorArgs.ErrorType == "RuntimeError")
    {
      var runtimeErrorMsg = "Silverlight Runtime Error  \n\n";

      // Basic error event informaiton.
      runtimeErrorMsg += "Error Type:    " + errorArgs.errorType     + "\n";
      runtimeErrorMsg += "Error Message: " + errorArgs.errorMessage  + "\n";
      runtimeErrorMsg += "Error Code:    " + errorArgs.errorCode  + "\n";

      // Runtime specific error event information.
      if (errorArgs.lineNumber != 0)
      {
        runtimeErrorMsg += "Line:     " + errorArgs.lineNumber     + "\n";
        runtimeErrorMsg += "Position: " +  errorArgs.charPosition  + "\n";
      }

     runtimeErrorMsg += "MethodName: " + errorArgs.methodName     + "\n";

     alert(runtimeErrorMsg);
    }

Applies To

RunTimeErrorEventArgs

See Also

Silverlight Application Scripting Error Handling, ErrorEventArgs, ParserErrorEventArgs


M11 Property

Silverlight SDK

M11 Property (Matrix)

Gets or sets the value of the first row and first column of this matrix.

XAML
<object M11="Double" .../>
Scripting
value = object.M11
object.M11 = value

Property Value

Double

The value of the first row and first column of this matrix.

This property is read/write. The default value is 1.

Remarks

The Matrix class is for custom transformations. Often it is easier to use the specific transformations RotateTransform, ScaleTransform, SkewTransform, or TranslateTransform.

Applies To

Matrix

See Also

Matrix, Silverlight Transforms Overview


M12 Property

Silverlight SDK

M12 Property (Matrix)

Gets or sets the value of the first row and second column of this matrix.

XAML
<object M12="Double" .../>
Scripting
value = object.M12
object.M12 = value

Property Value

Double

The value of the first row and second column of this matrix.

This property is read/write. The default value is 0.

Remarks

The Matrix class is for custom transformations. Often it is easier to use the specific transformations RotateTransform, ScaleTransform, SkewTransform, or TranslateTransform.

Applies To

Matrix

See Also

Matrix, Silverlight Transforms Overview


M21 Property

Silverlight SDK

M21 Property (Matrix)

Gets or sets the value of the second row and first column of this matrix.

XAML
<object M21="Double" .../>
Scripting
value = object.M21
object.M21 = value

Property Value

Double

The value of the second row and first column of this matrix.

This property is read/write. The default value is 0.

Remarks

The Matrix class is for custom transformations. Often it is easier to use the specific transformations RotateTransform, ScaleTransform, SkewTransform, or TranslateTransform.

Applies To

Matrix

See Also

Matrix, Silverlight Transforms Overview


M22 Property

Silverlight SDK

M22 Property (Matrix)

Gets or sets the value of the second row and second column of this matrix.

XAML
<object M22="Double" .../>
Scripting
value = object.M22
object.M22 = value

Property Value

Double

The value of the second row and second column of this matrix.

This property is read/write. The default value is 1.

Remarks

The Matrix class is for custom transformations. Often it is easier to use the specific transformations RotateTransform, ScaleTransform, SkewTransform, or TranslateTransform.

Applies To

Matrix

See Also

Matrix, Silverlight Transforms Overview


MappingMode Property (LinearGradientBrush)

Gets or sets value that specifies whether the LinearGradientBrush positioning coordinates are absolute or relative to the output area.

XAML
<object MappingMode="BrushMappingMode" .../>
Scripting
value = object.MappingMode
object.MappingMode = value

Property Value

BrushMappingMode

A value of the BrushMappingMode enumeration that specifies how the LinearGradientBrush positioning coordinates are interpreted.

This property is read/write. The default value is RelativeToBoundBox.

Remarks

A value of Absolute indicates the LinearGradientBrush coordinates are expressed using device independent pixels.

Applies To

LinearGradientBrush

See Also

Silverlight Brushes Overview


MappingMode Property (RadialGradientBrush)

Gets or sets value that specifies whether the RadialGradientBrush positioning coordinates are absolute or relative to the output area.

XAML
<object MappingMode="BrushMappingMode" .../>
Scripting
value = object.MappingMode
object.MappingMode = value

Property Value

BrushMappingMode

A value of the BrushMappingMode enumeration that specifies how the RadialGradientBrush positioning coordinates are interpreted.

This property is read/write. The default value is RelativeToBoundBox.

Remarks

A value of Absolute indicates the RadialGradientBrush coordinates are expressed using device independent pixels.

Applies To

RadialGradientBrush

See Also

Silverlight Brushes Overview


Marker (TimelineMarkerEventArgs) Property

Gets the TimelineMarker that triggered this event.

XAML
Cannot be used in XAML.
Scripting
value = eventargs.Marker

Property Value

TimelineMarker

The TimelineMarker that triggered this event.

This property is read-only.

Examples

The following example creates a MediaElement object and responds to its MarkerReached event. Each time a timeline marker is reached, the example displays the timeline marker's Time, Type, and Text values.

XAML
<Canvas
   xmlns="http://schemas.microsoft.com/client/2007"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 Width="300" Height="300">

  <MediaElement x:Name="media"
    Canvas.Top="50"
    MediaOpened="onMediaOpened"
    MarkerReached="onMarkerReached" Source="thebutterflyandthebear.wmv"
    Width="300" Height="200" />

  <Canvas Canvas.Left="10" Canvas.Top="5">

    <TextBlock
      FontSize="12" Foreground="DarkGray">Time:</TextBlock>

    <TextBlock x:Name="timeTextBlock"
      Canvas.Left="40"
      FontSize="12" />

    <TextBlock Canvas.Top="12"
      FontSize="12" Foreground="DarkGray">Type:</TextBlock>

    <TextBlock x:Name="typeTextBlock"
      Canvas.Left="40" Canvas.Top="12"
      FontSize="12" />

    <TextBlock
      Canvas.Top="24"
      FontSize="12" Foreground="DarkGray">Value:</TextBlock>

    <TextBlock x:Name="valueTextBlock"
      Canvas.Left="40" Canvas.Top="24"
      FontSize="12" />

  </Canvas>

  <!-- Stops media playback.-->
  <Canvas MouseLeftButtonDown="media_stop"
    Canvas.Left="10" Canvas.Top="265">
    <Rectangle Stroke="Black"
       Height="30" Width="55" RadiusX="5" RadiusY="5">
      <Rectangle.Fill>
        <RadialGradientBrush GradientOrigin="0.75,0.25">
          <GradientStop Color="Orange" Offset="0.0" />
          <GradientStop Color="Red" Offset="1.0" />
        </RadialGradientBrush>
      </Rectangle.Fill>
    </Rectangle>
    <TextBlock Canvas.Left="5" Canvas.Top="5">stop</TextBlock>
  </Canvas>

  <!-- Pauses media playback. -->
  <Canvas MouseLeftButtonDown="media_pause"
     Canvas.Left="70" Canvas.Top="265">
    <Rectangle Stroke="Black"
       Height="30" Width="55" RadiusX="5" RadiusY="5">
      <Rectangle.Fill>
        <RadialGradientBrush GradientOrigin="0.75,0.25">
          <GradientStop Color="Yellow" Offset="0.0" />
          <GradientStop Color="Orange" Offset="1.0" />
        </RadialGradientBrush>
      </Rectangle.Fill>
    </Rectangle>
    <TextBlock Canvas.Left="5" Canvas.Top="5">pause</TextBlock>
  </Canvas>

  <!-- Begins media playback. -->
  <Canvas MouseLeftButtonDown="media_begin"
    Canvas.Left="130" Canvas.Top="265">
    <Rectangle Stroke="Black" RadiusX="5" RadiusY="5"
       Height="30" Width="55">
      <Rectangle.Fill>
        <RadialGradientBrush GradientOrigin="0.75,0.25">
          <GradientStop Color="LimeGreen" Offset="0.0" />
          <GradientStop Color="Green" Offset="1.0" />
        </RadialGradientBrush>
      </Rectangle.Fill>
    </Rectangle>
    <TextBlock Canvas.Left="5" Canvas.Top="5">play</TextBlock>
  </Canvas>

</Canvas>
JavaScript
function media_stop(sender, args) {
    sender.findName("media").stop();
}

function media_pause(sender, args) {
    sender.findName("media").pause();
    alert(sender.findName("media").name);
}

function media_begin(sender, args) {
    sender.findName("media").play();

}

function onMarkerReached(sender, markerEventArgs)
{

  sender.findName("timeTextBlock").Text =
      markerEventArgs.marker.time.seconds.toString();

  sender.findName("typeTextBlock").Text =
       markerEventArgs.marker.type;

  sender.findName("valueTextBlock").Text =
       markerEventArgs.marker.text;

}

Applies To

TimelineMarkerEventArgs

See Also

Time, TimelineMarker, MediaElement, Media Overview


Markers Property

Gets the collection of timeline markers associated with the currently loaded media file.

XAML
See Remarks.
Scripting
value = object.markers

Property Value

TimelineMarkerCollection

The collection of timeline markers (represented as TimelineMarker objects) associated with the currently loaded media file.

This property is read-only. The default value is an empty collection.

Remarks

This collection is cleared and repopulated each time this MediaElement opens a new source file, and is only considered valid after the MediaOpened event has occurred.

Although the MediaElement object supports all Windows media technology markers (markers, metadata script commands, and separate-stream script commands), this collection does not include any timeline markers encoded as a separate stream in the media file, such as separate-stream script commands. If a file contains both header-embedded script commands and separate-stream script commands, this collection only contains those embedded in the file header. This is because MediaOpened is raised after reading the headers and metadata, but the full source might still be buffering and thus any separate stream markers are not available yet. Separate-stream script commands do trigger the MarkerReached event when encountered during media playback. However these markers are not accessible ahead of time using the Markers property.

You can create strings for TimelineMarker elements that you create through CreateFromXaml and then add them to a media file. But you cannot access the Markers property itself through XAML, or specify an initial set of markers in XAML, because the collection only comes from a populated Source and therefore is not tied to the XAML. If you want to prepopulate markers, you should embed them in the media instead.

Applies To

MediaElement

See Also

MarkerReached, TimelineMarker, Media Overview


Matrix Property

Gets or sets the Matrix that defines this transformation.

XAML
<object>
  <object.Matrix>
    <Matrix .../>
  </object.Matrix>
</object>
Scripting
value = object.Matrix
object.Matrix = value

Property Value

Matrix

The Matrix structure that defines this transformation. The default value is an identity Matrix. An identity matrix has a value of 1 in coefficients [1,1], [2,2], and [3,3]; and a value of 0 in the rest of the coefficients.

This property is read/write. The default value is Identity Matrix.

Remarks

The Matrix class is for custom transformations. Often it is easier to use the specific transformations RotateTransform, ScaleTransform, SkewTransform, or TranslateTransform.

Applies To

MatrixTransform


MaxFrameRate Property

Gets or sets the maximum number of frames to render per second.

Scripting (Instantiation)
Silverlight.CreateObject(,,,{framerate:'framerate'})

-or-

Silverlight.CreateObjectEx({properties:{framerate:'framerate'}})
Scripting (Runtime)
frameRate = silverlightObject.settings.MaxFrameRate
silverlightObject.settings.MaxFrameRate = frameRate

Property Value

integer

An integer value that specifies the maximum number of frames to render per second.

This property is read/write. The default value is 24.

Remarks

This property is available on the settings sub-object of a Silverlight plug-in instance.

The actual frame rate that Silverlight content renders is dependent on system load performance. The maximum frame rate is 64. Any value that is set to greater than 64 is considered to be set to 64.

For more information on how this property is set during plug-in initialization, see Using CreateSilverlight.js and Silverlight.js.

Applies To

Silverlight Plug-in

See Also

Using a Silverlight Plug-in, Using CreateSilverlight.js and Silverlight.js


MethodName Property

Gets the name of the method associated with the runtime error.

XAML | Cannot be used in XAML.
Scripting | value = eventargs.MethodName

Property Value

string

The name of the method.

This property is read/write.

Remarks

This property is technically read/write, but there is generally no reason to set it, because the property is just reporting information from existing errors.

Examples

The following JavaScript example shows the portion of an event handler that displays error information specific to runtime errors.

JavaScript
    // errorArgs is an instance of RuntimeErrorEventArgs
    if(errorArgs.ErrorType == "RuntimeError")
    {
      var runtimeErrorMsg = "Silverlight Runtime Error  \n\n";

      // Basic error event informaiton.
      runtimeErrorMsg += "Error Type:    " + errorArgs.errorType     + "\n";
      runtimeErrorMsg += "Error Message: " + errorArgs.errorMessage  + "\n";
      runtimeErrorMsg += "Error Code:    " + errorArgs.errorCode  + "\n";

      // Runtime specific error event information.
      if (errorArgs.lineNumber != 0)
      {
        runtimeErrorMsg += "Line:     " + errorArgs.lineNumber     + "\n";
        runtimeErrorMsg += "Position: " +  errorArgs.charPosition  + "\n";
      }

     runtimeErrorMsg += "MethodName: " + errorArgs.methodName     + "\n";

     alert(runtimeErrorMsg);
    }

Applies To

RunTimeErrorEventArgs

See Also

Silverlight Application Scripting Error Handling, ErrorEventArgs, ParserErrorEventArgs


Name Property (DependencyObject)

Gets or sets a unique identification for the object. A Name can only be set from initial parsing of XAML.

XAML
<object Name="string" .../>
-or-
<object x:Name="string" .../>
Scripting
value = object.Name

Property Value

string

A string representing the name of the object.

This property is read-only for scripting, write-only for XAML.

Remarks

The Name property is read-only for scripting. The only permitted set mechanism is as an attribute in XAML markup.

The Name property is generally equivalent to the x:Name attribute specified in XAML. Name and x:Name differ in the following aspects:

  • x:Name as an attribute is understood by all XAML readers. Name as an attribute in the default xmlns is only understood if it maps to an existing property on the element where it is declared. In the case of DependencyObject.Name, all common elements used for UI definition will possess the Name property/attribute through DependencyObject. DependencyObject provides core support for all Silverlight classes that can be declared as object elements in XAML, so this XAML language versus XAML implementation distinction is not relevant for Silverlight XAML. However, you should keep this distinction in mind if you are importing XAML that may have served as the UI definition for related XAML-consuming technologies (such as WPF).
  • Markup attributes are by nature write-only, unless you are examining the markup with a dedicated XML DOM, so the only operation you can perform with x:Name is to set the attribute value. The Name property is read-only for scripting at runtime, and can be used to get names where the name came either from a Name attribute or from an x:Name attribute value in markup. Certain Silverlight objects (for example Inlines) cannot be created in XAML as object elements, which means that there is no way to set a Name. Nevertheless the Name property is available in the object model for such objects, even though it will always return an empty string.
  • Using x:Name will require that you map the XAML xmlns to the x: prefix. This is typically done initially in most XAML files that are generated by tools, templates, or visual editors. The prefix x: is used by convention for the XAML xmlns; you can choose a different prefix that you will map to the XAML xmlns if you wish.

The reason why you set Name or x:Name in XAML is so that you can easily obtain a runtime reference to the object that was created by parsing the XAML. In order to get that reference, simply use the return value of the FindName method, specifying the name of the object you want to retrieve as an input parameter. FindName works from almost any scope and will search the entire runtime set of objects; you are not limited to searching in particular parent-child axes (although if you create discrete namescopes with CreateFromXaml, that might complicate your FindName usages; see XAML Namescopes).

The string that can be used for Name is slightly constained by a grammar that is defined by the XAML language and influenced by other parsing considerations. For instance, you cannot use an ampersand (&) in a XAML name, because that triggers the entity escape sequence in XML. For best results, use numbers, letters, and the underscore character only. For details, see XamlName Grammar.

Some of the object types listed in Applies To are abstract types, therefore this property cannot be retreived or set on that type in JavaScript because there is no way to obtain instances of abstract types in JavaScript programming.

Applies To

Accessibility, ArcSegment, BeginStoryboard, BezierSegment, Boolean, Brush, Canvas, Color, ColorAnimation, ColorAnimationUsingKeyFrames, ColorKeyFrame, ColorKeyFrameCollection, DependencyObject, DiscreteColorKeyFrame, DiscreteDoubleKeyFrame, DiscretePointKeyFrame, DoubleAnimation, DoubleAnimationUsingKeyFrames, DoubleKeyFrame, DoubleKeyFrameCollection, Downloader, DrawingAttributes, Duration, Ellipse, EllipseGeometry, EventTrigger, Geometry, GeometryCollection, GeometryGroup, Glyphs, GradientStop, GradientStopCollection, Image, ImageBrush, InkPresenter, Inlines, KeySpline, KeyTime, Line, LinearColorKeyFrame, LinearDoubleKeyFrame, LinearGradientBrush, LinearPointKeyFrame, LineBreak, LineGeometry, LineSegment, Matrix, MatrixTransform, MediaAttribute, MediaAttributeCollection, MediaElement, Path, PathFigure, PathFigureCollection, PathGeometry, PathSegment, PathSegmentCollection, Point, PointAnimation, PointAnimationUsingKeyFrames, PointKeyFrame, PointKeyFrameCollection, PolyBezierSegment, Polygon, Polyline, PolyLineSegment, PolyQuadraticBezierSegment, QuadraticBezierSegment, RadialGradientBrush, Rect, Rectangle, RectangleGeometry, RepeatBehavior, ResourceDictionary, RotateTransform, Run, RuntimeErrorEventArgs, ScaleTransform, SkewTransform, SolidColorBrush, SplineColorKeyFrame, SplineDoubleKeyFrame, SplinePointKeyFrame, Storyboard, Stretch, Stroke, StrokeCollection, StylusInfo, StylusPoint, StylusPointCollection, TextBlock, Timeline, TimelineCollection, TimelineMarker, TimelineMarkerCollection, TimelineMarkerEventArgs, TimeSpan, TransformCollection, TransformGroup, TranslateTransform, TriggerActionCollection, TriggerCollection, VisualCollection, VideoBrush

See Also


Name Property (MediaAttribute)

Gets the name of the MediaAttribute.

XAML
Cannot be used in XAML. See ASX documentation for markup information.
Scripting
value = object.Name
object.Name = value

Property Value

string

The name of the attribute.

This property is read-only.

Remarks

The Name of a MediaAttribute is the name of the xml element in the ASX file that the MediaAttribute corresponds to. The Value of the MediaAttribute is the text value of the xml element. For example, if the ASX tag that the MediaAttribute corresponds to is:

<Title>Clip1</Title>

the Name of the MediaAttribute is "Title" and the Value is "Clip1".

Examples

The following JavaScript example shows how to retrieve the Attributes property of a MediaElement that has a Source property set to an ASX playlist file. The retrieved MediaAttributeCollection is iterated through and the Name and Value properties of each MediaAttribute is displayed.

JavaScript
    // Get the MediaElement name MediaPlayer.
    player = sender.findName("MediaPlayer");

    // The display message.
    var msg;
    msg =  "MediaElement Source: " + player.source + "\n\n";
    msg += "Attributes: \n";

    // Variable to hold the MediaAttribute.
    var attribute;

    // Iterate through the collection of MediaAttributes.
    var loop = 0;
    while(loop < player.Attributes.count)
    {
        // Get the current Attribute.
        attribute = player.Attributes.getItem(loop);

        msg += "Name: "  + attribute.Name + "\n";
        msg += "Value: " + attribute.Value + " \n\n";
        loop++;
    }

    // Display the MediaAttribute information.
    alert(msg);
}

Applies To

MediaAttribute

See Also

MediaElement, MediaAttributeCollection, Attributes, MediaAttribute


NaturalDuration Property

Gets the natural duration of the media.

XAML | Cannot be used in XAML.
Scripting | value = object.NaturalDuration

Property Value

Duration

The natural duration of the media.

This property is read-only. The default value is Automatic, which is the value held if you query this property before MediaOpened.

Remarks

The property value is not available until the MediaOpened event has been raised.

If the opened media is live streaming media, NaturalDuration is null.

Once you have the Duration, you can get its Seconds value.

Applies To

MediaElement

See Also

Media Overview, Supported Media Formats and Protocols


NaturalVideoHeight Property

Gets the height of the video that is associated with the media.

XAML | Cannot be used in XAML.
Scripting | value = object.NaturalVideoHeight

Property Value

Double

The height of the video that is associated with the media, in pixels. Audio files will return 0.

This property is read-only. The default value is 0.

Remarks

The property value is not available until the MediaOpened event has been raised.

Applies To

MediaElement

See Also

Media Overview, Supported Media Formats and Protocols


NaturalVideoWidth Property

Gets the width of the video that is associated with the media.

XAML | Cannot be used in XAML.
Scripting | value = object.NaturalVideoWidth

Property Value

Double

The width of the video that is associated with the media.

This property is read-only. The default value is 0.

Remarks

The property value is not available until the MediaOpened event has been raised.

Applies To

MediaElement

See Also

Media Overview, Supported Media Formats and Protocols


Offset Property

Gets the location of the gradient stop within the gradient vector.

XAML
<object Offset="Double" .../>
Scripting
value = object.Offset
object.Offset = value

Property Value

Double

The relative location of this gradient stop along the gradient vector.

This property is read/write. The default value is 0.

Remarks

The MappingMode of a LinearGradientBrush or RadialGradientBrush influences how the Offset values are interpreted. Typically you use the default MappingMode, which interprets the offsets as being a relative factor of the total area where the brush is applied. A value of 0 specifies that the stop is positioned at the beginning of the gradient vector, while a value of 1.0 specifies that the stop is positioned at the end of the gradient vector. For a LinearGradientBrush the 0 offset specifies its StartPoint. For a RadialGradientBrush the 0 offset specifies its GradientOrigin Property. This gradient stop offset factor is then mapped onto how each type of brush specifies its vector. A LinearGradientBrush vector follows a line that runs from its StartPoint to its EndPoint. A RadialGradientBrush vector radiates from its GradientOrigin towards the ellipse formed by Center, RadiusX and RadiusY.

Generally an Offset value is provided between 0 and 1.0 when using the default MappingMode. Values slightly above 1 or slightly below 0 will influence the gradient for this mode and are valid, but the same resulting gradient could be achieved entirely using values between 0 and 1 if all the gradient stops are adjusted relatively.

If you change the MappingMode to be Absolute, then the Offset is interpreted as pixels within the area where the brush is applied.

For examples and illustrations, see Silverlight Brushes Overview.

Applies To

GradientStop

See Also

Silverlight Brushes Overview


OffsetX Property

Silverlight SDK

OffsetX Property (Matrix)

Gets or sets the value of the third row and first column of this matrix.

XAML
<object OffsetX="Double" .../>
Scripting
value = object.OffsetX
object.OffsetX = value

Property Value

Double

The value of the first row and third column of this matrix.

This property is read/write. The default value is 0.

Remarks

The Matrix class is for custom transformations. Often it is easier to use the specific transformations RotateTransform, ScaleTransform, SkewTransform, or TranslateTransform.

Applies To

Matrix

See Also

Matrix, Silverlight Transforms Overview


OffsetY Property

Silverlight SDK

OffsetY Property (Matrix)

Gets or sets the value of the third row and second column of this matrix.

XAML
<object OffsetY="Double" .../>
Scripting
value = object.OffsetY
object.OffsetY = value

Property Value

Double

The value of the third row and second column of this matrix.

This property is read/write. The default value is 0.

Remarks

The Matrix class is for custom transformations. Often it is easier to use the specific transformations RotateTransform, ScaleTransform, SkewTransform, or TranslateTransform.

Applies To

Matrix

See Also

Matrix, Silverlight Transforms Overview


Opacity Property (Brush)

Gets or sets the degree of opacity of a Brush.

XAML
<object Opacity="Double" .../>
Scripting
value = object.Opacity
object.Opacity = value

Property Value

Double

The value of the Opacity property is expressed as a value between 0 and 1.0.

This property is read/write. The default value is 1.0.

Remarks

A Opacity value of 0 indicates that the brush is completely transparent, while a value of 1 indicates that the brush is completely opaque. A value of 0.5 indicates the brush is 50% opaque, a value of 0.725 indicates the brush is 72.5% opaque, and so on. Values less than 0 are treated as 0, while values greater than 1 are treated as 1.

Applies To

ImageBrush, LinearGradientBrush, RadialGradientBrush, SolidColorBrush, VideoBrush


Opacity Property

Gets or sets the degree of the object's opacity.

XAML
<object Opacity="Double" .../>
Scripting
value = object.Opacity
object.Opacity = value

Property Value

Double

A value between 0 and 1.0 that declares the opacity, with 1.0 meaning full opacity and 0 meaning transparent.

This property is read/write. The default value is 1.0.

Remarks

An Opacity value of 0 does not exclude an element from hit testing. This behavior can be useful for creating imagemap-style overlays of Canvas, Rectangle or other shapes to capture hits on elements that exist at z-orders greater than other visible objects underneath. In order to exclude an element from hit testing, you should set IsHitTestVisible to true.

When Opacity is set on elements that are nested, the effective opacity is the product of all applicable opacity factors. For instance, if an element that has Opacity=0.5 is contained in a Canvas that is also Opacity=0.5, the effective Opacity value is 0.25.

Opacity values greater than 1.0 are treated as 1.0 when the value is used, although obtaining the property value will still give you the original greater-than-one value. Opacity values less than zero are treated as 0 when the value is used. For instance, setting an Opacity to 2 to cancel out the effects of a nested element with 0.5 Opacity element does not work; the 2 value is treated as 1.0 even before the nested-element factoring is calculated.

The following screenshot shows a TextBlock displayed as a window-less plug-in on a Microsoft Virtual Earth mashup. The Background value of the plug-in is #00000000, which is totally transparent. In addition, the Opacity of the TextBlock is set to 0.7, which allows the map underneath to partially show through the text.

TextBlock with partial opacity

Performance Note For best performance, use the Visibility property instead of the Opacity property when possible. The Visibility property is best when you simply want to make an object completely visible or completely not visible rather than using partial opacity or fading in or out of view. An object with an Opacity of 0 is still hit tested and the rendering engine still technically renders the object, you just cannot see it. Setting Visibility to Collapsed avoids these costs.

Applies To

Canvas, Ellipse, Glyphs, Image, InkPresenter, Line, MediaElement, Path, Polygon, Polyline, Rectangle, TextBlock

See Also

Windowless


OpacityMask Property

Gets or sets the brush used to alter the opacity of select regions of this object.

XAML
<object ...>
  <object.OpacityMask>
    <Brush .../>
  </object.OpacityMask>
</object>
Scripting
value = object.OpacityMask
object.OpacityMask = value

Property Value

Brush

A Brush that describes the opacity of this object.

This property is read/write. The default value is null.

Remarks

This property only uses whatever the alpha channel value is for the supplied Brush. The other channels of the Brush's rendered content (Red, Green, or Blue) are ignored.

The most typical Brush for this purpose is an ImageBrush, which can be used for a variety of photo masking techniques such as a vignette. But any defined Brush (such as LinearGradientBrush) can be used. All of these brushes require a Brush object element in XAML, so this is the XAML syntax shown.

Examples

The following example creates a RadialGradientBrush with three gradient stops in the implicit GradientStopCollection. The three gradient stops specify a brush with a varying transparency, which is then applied as the OpacityMask for an Image.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <Image Source="sampleImages/forest.jpg" Height="100">
    <Image.OpacityMask>
      <RadialGradientBrush Center="0.5,0.5">
        <!-- This gradient stop is partially transparent. -->
        <GradientStop Color="#00000000" Offset="1" />
        <!-- This gradient stop is partially transparent. -->
        <GradientStop Color="#20000000" Offset="0.8" />
        <!-- This gradient stop is fully opaque. -->
        <GradientStop Color="#FF000000" Offset="0" />
      </RadialGradientBrush>
    </Image.OpacityMask>
  </Image>
</Canvas>

This example displays as follows:

RadialGradientBrush applied to OpacityMask of an image

Applies To

Canvas, Ellipse, Glyphs, Image, InkPresenter, Line, MediaElement, Path, Polygon, Polyline, Rectangle, TextBlock

See Also

Silverlight Brushes Overview


OriginX Property

Gets or sets the value of the x origin for the Glyphs object.

XAML
<object OriginX="Double" .../>
Scripting
value = object.OriginX
object.OriginX = value

Property Value

Double

A value that represents the x origin of the Glyphs object.

This property is read/write. The default value is 0.

Applies To

Glyphs

See Also

Text and Fonts Overview, TextBlock,


OriginY Property

Gets or sets the value of the x origin for the Glyphs object.

XAML
<object OriginY="Double" .../>
Scripting
value = object.OriginY
object.OriginY = value

Property Value

Double

A value that represents the y origin of the Glyphs object.

This property is read/write. The default value is 0.

Applies To

Glyphs

See Also

Text and Fonts Overview, TextBlock,


OutlineColor Property

Gets or sets the outline color of the associated stroke.

XAML
<DrawingAttributes OutlineColor="Color" .../>
Scripting
value = object.OutlineColor
object.OutlineColor = value

Property Value

Color

The outline color of the associated stroke.

This property is read/write. The default value is null.

Remarks

The outline color makes the rendered stroke two pixels wider in each direction.

Examples

The following Javascript events simulate 3 different pen types (pen, marker and highlighter) by setting the Color, Height, OutlineColor and Width DrawingAttributes properties . First a DrawingAttributes object is created, then it is appended to the Stroke object. The DrawingAttributes properties are then set by one of the three events that simulate a pen type. The EraseCanvas event clears all the Strokes from the Canvas.

JavaScript
var agCtrl;
var inkPresenter; // Corresponds to InkPresenter element in xaml
var newStroke = null; // The Stroke variable we'll use here in mouse handlers
// DrawingAttributes variables
var daWidth = 2;
var daHeight = 2;
var daColor = "Black";
var daOutlineColor = "Black";

function root_Loaded(sender, args)
{
    // Get the html object which contains the Silverlight plug-in
    agCtrl = sender.GetHost();
    inkPresenter = sender.findname("inkPresenterElement");
}

// Capture mouse movement when the left button is pressed and create the stroke
function InkPresenterMouseDown(sender,args)
{
   inkPresenter.CaptureMouse();

   newStroke = agCtrl.content.createFromXaml('<Stroke/>');

   var da = agCtrl.content.CreateFromXaml('<DrawingAttributes/>');
   newStroke.DrawingAttributes = da;

   // Set the drawing attributes properties
   newStroke.DrawingAttributes.Width = daWidth;
   newStroke.DrawingAttributes.Height = daHeight;
   newStroke.DrawingAttributes.Color = daColor;
   newStroke.DrawingAttributes.OutlineColor = daOutlineColor;

   newStroke.StylusPoints.AddStylusPoints(args.GetStylusPoints(inkPresenter));
   inkPresenter.Strokes.Add(newStroke);
}

// Add the new points to the Stroke we're working with
function InkPresenterMouseMove(sender,args)
{
   if (newStroke != null)
   {
      newStroke.StylusPoints.AddStylusPoints(args.GetStylusPoints(inkPresenter));
   }
}

// Release the mouse
function InkPresenterMouseUp(sender,args)
{
   newStroke = null;
   inkPresenter.ReleaseMouseCapture();
}

// Set the Drawing Attributes for a pen
function SelectPen(sender, args)
{
  daWidth = 1;
  daHeight = 1;
  daColor = "Black";
  daOutlineColor = "Black";
}

// Set the Drawing Attributes for a marker
function SelectMarker(sender, args)
{
  daWidth = 10;
  daHeight = 4;
  daColor = "Blue";
  daOutlineColor = "Blue";
}

// Set the Drawing Attributes for a highlighter
function SelectHighlighter(sender, args)
{
  daWidth = 25;
  daHeight = 5;
  daColor = "Yellow";
  daOutlineColor = "Yellow";
}

// Erase all strokes from the canvas
function EraseCanvas(sender, args)
{
  inkPresenter.Strokes.Clear();
}

The XAML sample below creates the canvas and 4 buttons that are used to select the different pen types and the erase all feature that is simulated by the Javascript events above.

XAML
<Canvas xmlns="http://schemas.microsoft.com/client/2007"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Loaded="root_Loaded"
        x:Name="root"
        Width="600" Height="400">
  <InkPresenter
         x:Name="inkPresenterElement"
        Background="transparent"
        Width="600" Height="400"
        MouseLeftButtonDown="InkPresenterMouseDown"
        MouseMove="InkPresenterMouseMove"
        MouseLeftButtonUp="InkPresenterMouseUp"/>

<!-- Pen Button -->
    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="40"
      Stroke="Gray" Fill="Black" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>
    <TextBlock
      Height="21" Width="78"
      Canvas.Top="380" Canvas.Left="71"
      Foreground="Gray"
      FontFamily="Verdana" FontSize="12">Select Pen</TextBlock>

    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="40"
      x:Name="selectPen" MouseLeftButtonDown="SelectPen"
      Stroke="Transparent" Fill="Transparent" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>

<!-- Marker Button -->
    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="170"
      Stroke="Gray" Fill="Black" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>

    <TextBlock
      Height="21" Width="78"
      Canvas.Top="380" Canvas.Left="191"
      Foreground="Gray"
      FontFamily="Verdana" FontSize="12">Select Marker</TextBlock>

    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="170"
      x:Name="selectMarker" MouseLeftButtonDown="SelectMarker"
      Stroke="Transparent" Fill="Transparent" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>

<!-- Highlighter Button -->
    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="300"
      Stroke="Gray" Fill="Black" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>

    <TextBlock
      Height="21" Width="78"
      Canvas.Top="380" Canvas.Left="310"
      Foreground="Gray"
      FontFamily="Verdana" FontSize="12">Select Highlighter</TextBlock>

    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="300"
      x:Name="selectHighlighter" MouseLeftButtonDown="SelectHighlighter"
      Stroke="Transparent" Fill="Transparent" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>

<!-- Erase Canvas Button -->
    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="430"
      Stroke="Gray" Fill="Black" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>

    <TextBlock
      Height="21" Width="78"
      Canvas.Top="380" Canvas.Left="463"
      Foreground="Gray"
      FontFamily="Verdana" FontSize="12">Erase All</TextBlock>

    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="430"
      x:Name="eraseCanvas" MouseLeftButtonDown="EraseCanvas"
      Stroke="Transparent" Fill="Transparent" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>
</Canvas>

Applies To

DrawingAttributes

See Also

Stroke, Color, Height, Width, DrawingAttributes, DrawingAttributes(Stroke)


PlatformKeyCode Property

Gets a value representing the platform key associated with the event.

XAML | This property cannot be used in XAML.
Scripting | value = eventargs.PlatformKeyCode

Property Value

Key

The platform key referenced by the event.

Remarks

Key codes have possible platform variations. For details see Silverlight Keyboard Support.

Check Ctrl and Shift to determine if the key event is a key combination.

Applies To

KeyboardEventArgs

See Also

Silverlight Keyboard Support, Silverlight Events


Point Property (ArcSegment)

Gets or sets the endpoint of the elliptical arc.

XAML
<object Point="Point" .../>
Scripting
value = object.Point
object.Point = value

Property Value

Point

The point to which the arc is drawn.

This property is read/write. The default value is "0,0".

Remarks

See remarks in Point for scripting usages of this property.

An ArcSegment defines only the destination point of the arc it represents; the beginning point of the arc is the current point of the PathFigure to which the ArcSegment is added.

If the arc segment's start point and end point are the same, no arc is drawn.

Applies To

ArcSegment

See Also

Path Markup Syntax


Point Property (LineSegment)

Gets or sets the end point of the line segment.

XAML
<object Point="Point" .../>
Scripting
value = object.Point
object.Point = value

Property Value

Point

The end point of the line segment.

This property is read/write. The default value is 0,0.

Remarks

See remarks in Point for scripting usages of this property.

The LineSegment class does not contain a property for the starting point of the line. The starting point of the line is the current point of the PathFigure object where you add the line.

Applies To

LineSegment

See Also

PathFigure, PathSegmentCollection, Path Markup Syntax


Point1 Property

Silverlight SDK

Point1 Property (BezierSegment)

Gets or sets the first control point of the curve.

XAML
<object Point1="Point" .../>
Scripting
value = object.Point1
object.Point1 = value

Property Value

Point

The first control point of the curve.

This property is read/write. The default value is 0,0.

Remarks

See remarks in Point for scripting usages of this property.

The two control points of a cubic Bezier curve behave like magnets, attracting portions of what would otherwise be a straight line toward themselves and producing a curve. The first control point, Point1, affects the beginning portion of the curve; the second control point, Point2, affects the ending portion of the curve. Note that the curve doesn't necessarily pass through either of the control points; each control point moves its portion of the line toward itself, but not through itself.

Applies To

BezierSegment

See Also

Path Markup Syntax, Point2, Point3


Point1 Property (QuadraticBezierSegment)

Gets or sets the control Point of the curve.

XAML
<object Point1="Point" .../>
Scripting
value = object.Point1
object.Point1 = value

Property Value

Point

The control point of this QuadraticBezierSegment.

This property is read/write. The default value is 0,0.

Remarks

See remarks in Point for scripting usages of this property.

Applies To

QuadraticBezierSegment

See Also

Silverlight Geometries Overview


Point2 Property

Silverlight SDK

Point2 Property (BezierSegment)

Gets or sets the second control point of the curve.

XAML
<object Point2="Point" .../>
Scripting
value = object.Point2
object.Point2 = value

Property Value

Point

The second control point of the curve.

This property is read/write. The default value is 0,0.

Remarks

See remarks in Point for scripting usages of this property.

The two control points of a cubic Bezier curve behave like magnets, attracting portions of what would otherwise be a straight line toward themselves and producing a curve. The first control point, Point1, affects the beginning portion of the curve; the second control point, Point2, affects the ending portion of the curve. Note that the curve doesn't necessarily pass through either of the control points; each control point moves its portion of the line toward itself, but not through itself.

Applies To

BezierSegment

See Also

Path Markup Syntax, Point1, Point3


Point2 Property (QuadraticBezierSegment)

Gets or sets the end Point of this QuadraticBezierSegment.

XAML
<object Point2="Point" .../>
Scripting
value = object.Point2
object.Point2 = value

Property Value

Point

The end point of this QuadraticBezierSegment.

This property is read/write. The default value is 0,0.

Remarks

See remarks in Point for scripting usages of this property.

Applies To

QuadraticBezierSegment

See Also

Silverlight Geometries Overview


Point3 Property

Silverlight SDK

Point3 Property (BezierSegment)

Gets or sets the end point of the curve.

XAML
<object Point3="Point" .../>
Scripting
value = object.Point3
object.Point3 = value

Property Value

Point

The end point of the curve.

This property is read/write. The default value is 0,0.

Remarks

See remarks in Point for scripting usages of this property.

The BezierSegment does not contain a property for the starting point of the curve; it only defines the end point. The beginning point of the curve is the current point of the PathFigure to which the BezierSegment is added.

Applies To

BezierSegment

See Also

Path Markup Syntax, Point1, Point2


Points Property (PolyBezierSegment)

Gets or sets the set of points that define this PolyBezierSegment object.

XAML | <object Points="pointSetString" .../>
Scripting | object.Points = "value"

Property Value

string

The set of points that define this PolyBezierSegment object, as a delimed string that represents a point set. See Remarks.

This property is write-only.

Remarks

A set of points is defined through a string syntax, enabled by an underlying type converter. There is no object available in the object model for accessing the set of points as a collection. In either script or XAML, Points is write-only. You set the value by specifying a string. Without a collection object, there is no means in the object model to obtain a count, although you could parse the string yourself and count separators or otherwise get a count before you pass the string as input.

The format for a Points string is to specify double values with separators. There are separators between the X,Y pairs that designate a single point as well as between each of the point pairs. You can use either comma or a space as the separator. A grammar approximation for pointSet, using comma as the separator (and with the [] characters not being literals but indicators of optional values) is:

Ax,Ay[,Bx,By,Cx,Cy ...]

In this grammar, the Ax and Ay are the X and Y values of a point "A", Bx and By the X and Y values of a point "B", and so on. For instance, the string "0,0,100,100" would produce a line segment from the point 0,0 to 100,100. If this were a LineSegment the line would be diagonal, but other objects that take a set of points (like PolyBezierSegment) might render differently, depending on other point values.

Any odd number of double values in a Points value / set of points is illegal and will throw either a parser or runtime error. The number of double values in the string must always be even so that it evaluates as pairs of points. A single point, such as "0,0", is a valid value, but generally will not render anything because you need a minimum of two points to produce a rendered output for any of the objects that use sets of points for property values.

Applies To

PolyBezierSegment

See Also

Path Markup Syntax, Silverlight Geometries Overview


Points Property (Polygon)

Gets or sets the vertex points of the polygon.

XAML | <object Points="pointSetString" .../>
Scripting | object.Points = "value"

Property Value

string

The set of points that define the vertex points of the polygon, as a delimited string that represents a point set.

This property is write-only. The default value is null.

Remarks

A set of points is defined through a string syntax, enabled by an underlying type converter. There is no object available in the object model for accessing the set of points as a collection. In either script or XAML, Points is write-only. You set the value by specifying a string.

The format for a Points string is to specify double values with separators. There are separators between the X,Y pairs that designate a single point as well as between each of the point pairs. You can use either comma or a space as the separator. A grammar approximation for pointSet, using comma as the separator (and with the [] characters not being literals but indicators of optional values) is:

Ax,Ay[,Bx,By,Cx,Cy ...]

In this grammar, the Ax and Ay are the X and Y values of a point "A", Bx and By the X and Y values of a point "B", and so on. For instance, the string "0,0,100,100" would produce a line segment from the point 0,0 to 100,100. If this were a LineSegment the line would be diagonal, but other objects that take a set of points (like PolyBezierSegment) might render differently, depending on other point values.

Any odd number of double values in a Points value / set of points is illegal and will throw either a parser or runtime error. The number of double values in the string must always be even so that it evaluates as pairs of points. A single point, such as "0,0", is a valid value, but generally will not render anything because you need a minimum of two points to produce a rendered output for any of the objects that use sets of points for property values.

Applies To

Polygon

See Also

Shapes and Drawing in Silverlight Overview


Points Property (Polyline)

Gets or sets a collection that contains the vertex points of the Polyline.

XAML | <object Points="pointSet" .../>
Scripting | object.Points = "pointSet"

Property Value

pointSet

String

The set of points that describe the vertex points of the Polyline.

This property is write-only. The default value is null.

Remarks

A set of points is defined through a string syntax, enabled by an underlying type converter. There is no object available in the object model for accessing the set of points as a collection. In either script or XAML, Points is write-only. You set the value by specifying a string.

The format for a Points string is to specify double values with separators. There are separators between the X,Y pairs that designate a single point as well as between each of the point pairs. You can use either comma or a space as the separator. A grammar approximation for pointSet, using comma as the separator (and with the [] characters not being literals but indicators of optional values) is:

Ax,Ay[,Bx,By,Cx,Cy ...]

In this grammar, the Ax and Ay are the X and Y values of a point "A", Bx and By the X and Y values of a point "B", and so on. For instance, the string "0,0,100,100" would produce a line segment from the point 0,0 to 100,100. If this were a LineSegment the line would be diagonal, but other objects that take a set of points (like PolyBezierSegment) might render differently, depending on other point values.

Any odd number of double values in a Points value / set of points is illegal and will throw either a parser or runtime error. The number of double values in the string must always be even so that it evaluates as pairs of points. A single point, such as "0,0", is a valid value, but generally will not render anything because you need a minimum of two points to produce a rendered output for any of the objects that use sets of points for property values.

Applies To

Polyline

See Also

Shapes and Drawing in Silverlight Overview


Points Property (PolyLineSegment)

Gets or sets the set of points that defines this PolyLineSegment object.

XAML | <object Points="pointSet" .../>
Scripting | object.Points = "value"

Property Value

string

The set of points that define this PolyLineSegment object, as a delimited string that represents a point set.

This property is write-only.

Remarks

A line is drawn from the end point of the previous segment or, if this is the first segment, from the StartPoint of the PathFigure to the first point in the set of points. Lines are then drawn between each subsequent point.

A set of points is defined through a string syntax, enabled by an underlying type converter. There is no object available in the object model for accessing the set of points as a collection. In either script or XAML, Points is write-only. You set the value by specifying a string.

The format for a Points string is to specify double values with separators. There are separators between the X,Y pairs that designate a single point as well as between each of the point pairs. You can use either comma or a space as the separator. A grammar approximation for pointSet, using comma as the separator (and with the [] characters not being literals but indicators of optional values) is:

Ax,Ay[,Bx,By,Cx,Cy ...]

In this grammar, the Ax and Ay are the X and Y values of a point "A", Bx and By the X and Y values of a point "B", and so on. For instance, the string "0,0,100,100" would produce a line segment from the point 0,0 to 100,100. If this were a LineSegment the line would be diagonal, but other objects that take a set of points (like PolyBezierSegment) might render differently, depending on other point values.

Any odd number of double values in a Points value / set of points is illegal and will throw either a parser or runtime error. The number of double values in the string must always be even so that it evaluates as pairs of points. A single point, such as "0,0", is a valid value, but generally will not render anything because you need a minimum of two points to produce a rendered output for any of the objects that use sets of points for property values.

Applies To

PolyLineSegment

See Also

Path Markup Syntax


Points Property (PolyQuadraticBezierSegment)

Gets or sets the set of points that defines this PolyQuadraticBezierSegment object.

XAML | <object Points="pointSetString" .../>
Scripting | object.Points = "value"

Property Value

String

The set of points that defines this PolyQuadraticBezierSegment object, as a delimited string that represents a point set.

This property is write-only. The default value is an empty collection.

Remarks

The first two points in the collection specify the control point and end point of the first curve segment. The next two points specify the control point and end point of the second curve segment, and so on. The collection should contain an even number of points.

A set of points is defined through a string syntax, enabled by an underlying type converter. There is no object available in the object model for accessing the set of points as a collection. In either script or XAML, Points is write-only. You set the value by specifying a string.

The format for a Points string is to specify double values with separators. There are separators between the X,Y pairs that designate a single point as well as between each of the point pairs. You can use either comma or a space as the separator. A grammar approximation for pointSet, using comma as the separator (and with the [] characters not being literals but indicators of optional values) is:

Ax,Ay,Bx,By[,Cx,Cy,Dx,Dy ...]

In this grammar, the Ax and Ay are the X and Y values of a point "A", Bx and By the X and Y values of a point "B", and so on.

Any odd number of double values in a Points value / set of points is illegal and will throw either a parser or runtime error. The number of double values in the string must always be even so that it evaluates as pairs of points, and must contain at least two points to form a valid control point and end point.

Applies To

PolyQuadraticBezierSegment

See Also

Silverlight Geometries Overview


Position Property

Gets or sets the current progress through the media's playback time.

XAML
See Remarks.
Scripting
value = object.Position
object.Position = value

Property Value

TimeSpan

The amount of time since the beginning of the media.

This property is read/write. The default value is 00:00:00.

Remarks

The string format for specifying a TimeSpan is [days.]hours:minutes:seconds[.fractionalSeconds]. See TimeSpan. Creating a TimeSpan in XAML is only possible through a type conversion syntax when setting a property such as Position that takes a TimeSpan as an attribute string. Creating a TimeSpan in script also uses the type conversion syntax by setting Position with a properly formatted string.

Use this property to set to a specific position within the media. This property is settable, rather than there being a specific "MediaElement.Seek" method.

The maximum value is the NaturalDuration of the media.

If the media does not support seek operations (which is the case for live streaming media), setting this property will have no effect on media playback. Check the the value of CanSeek before attempting to set Position.

If the Position is settable but the Position value is either set to a negative value or is set to a value larger than the media's NaturalDuration, the property value will be set to 00:00:00 or NaturalDuration, respectively.

You generally should not set this value in XAML, because until the media source is loaded there is no guarantee that the media is positionable. After MediaOpened is raised, check the value of CanSeek. If it is true, then the media is positionable, and then you can set Position in scripting.

Applies To

MediaElement

See Also

Media Overview, Supported Media Formats and Protocols


PressureFactor Property

Gets or sets the pressure factor of the stylus on the screen.

XAML
<StylusPoint PressureFactor="Double" .../>
Scripting
value = object.PressureFactor
object.PressureFactor = value

Property Value

Double

The pressure factor of the stylus on the screen.

This property is read/write. The default value is 0.5.

Remarks

The allowed range is 0 to 1.0. Values obtained from input will always be within this range. Setting the value to outside this range throws an error.

The value is a percentage of the total possible pressure.

The typical scenario for this property is to modify the DrawingAttributes on the basis of the PressureFactor captured in a StylusPoint obtained from user input, although note that while PressureFactor comes from individual points, DrawingAttributes must apply to an entire Stroke.

Examples

The following example uses the PressureFactor property to determine the size of a stroke. The PressureFactor is obtained from the first StylusPoint of each stroke, then the stroke Width and Height is calculated by multiplying the PressureFactor by 20.

JavaScript
var agCtrl;
var inkPresenter; // Corresponds to InkPresenter element in xaml
var newStroke = null; // The Stroke variable we'll use here in mouse handlers
var daWidth;
var daHeight;

function root_Loaded(sender, args)
{
    // Get the html object which contains the Silverlight plug-in
    agCtrl = sender.GetHost();
    inkPresenter = sender.findname("inkPresenterElement");
}

// Capture mouse movement when the left button is pressed then create the stroke.
function InkPresenterMouseDown(sender,args)
{
   inkPresenter.CaptureMouse();
   newStroke = agCtrl.content.createFromXaml('<Stroke/>');

   // Get the DeviceType
   if(args.GetStylusInfo().deviceType == "Stylus")
   {
     var sps = args.GetStylusPoints(inkPresenter);
     SetStylusStrokeSize(sps);
   }
   // If the device type is not a stylus then use the default stroke height and width.
   else
   {
     daWidth = 3;
     daHeight = 3;
   }

   // Set the drawing attributes properties
   newStroke.DrawingAttributes.Width = daWidth;
   newStroke.DrawingAttributes.Height = daHeight;
   newStroke.DrawingAttributes.Color = "Blue";
   newStroke.DrawingAttributes.OutlineColor = "Orange";

   newStroke.StylusPoints.AddStylusPoints(args.GetStylusPoints(inkPresenter));
   inkPresenter.Strokes.Add(newStroke);
}

// Add the new points to the Stroke we're working with
function InkPresenterMouseMove(sender,args)
{
   if (newStroke != null)
   {
      newStroke.StylusPoints.AddStylusPoints(args.GetStylusPoints(inkPresenter));
   }
}

// Release the mouse
function InkPresenterMouseUp(sender,args)
{
   newStroke = null;
}

// Set the size of the stroke based on the initial pressureFactor of the stroke.
function SetStylusStrokeSize(sps)
{
    var p;
    // Set variable p to the first StylusPoint in the Stroke
    p = sps.getItem(0).pressureFactor;
    daWidth = p * 20.0;
    daHeight = p * 20.0;
}

Applies To

StylusPoint

See Also

StylusPoint Object, Ink Support In Microsoft Silverlight


RadiusX Property (EllipseGeometry)

Gets or sets the x-radius value of the EllipseGeometry.

XAML
<object RadiusX="Double" .../>
Scripting
value = object.RadiusX
object.RadiusX = value

Property Value

Double

The x-radius value of the EllipseGeometry.

This property is read/write. The default value is 0. If you do not specify a value for RadiusX and RadiusY, the ellipse will not render.

Remarks

Setting identical RadiusX and RadiusY values results in a circle.

Applies To

EllipseGeometry

See Also

Silverlight Geometries Overview, RadiusY, Ellipse


RadiusX Property (RadialGradientBrush)

Gets or sets the horizontal radius of the outermost circle of the radial gradient.

XAML
<object RadiusX="Double" .../>
Scripting
value = object.RadiusX
object.RadiusX = value

Property Value

Double

The horizontal radius of the outermost circle of the radial gradient.

This property is read/write. The default value is 0.5.

Remarks

The MappingMode property of a RadialGradientBrush determines whether its properties are interpreted as a relative or absolute value. By default, RadiusX is treated as relative, which corresponds to a MappingMode of RelativeToBoundingBox. In this case, the default value of 0.5, combined with the default Center value of 0.5,0.5, makes the circle be as wide as the area where the brush is applied, centered exactly on the middle of that area. A MappingMode of Absolute specifies that the RadiusX value is expressed in device independent pixels, not as a factor within the bounding box of the area where the brush is applied.

Applies To

RadialGradientBrush

See Also

LinearGradientBrush, Silverlight Brushes Overview


RadiusX Property (Rectangle)

Gets or sets the x-axis radius of the ellipse that is used to round the corners of the rectangle.

XAML
<object RadiusX="Double" .../>
Scripting
value = object.RadiusX
object.RadiusX = value

Property Value

Double

The x-axis radius of the ellipse that is used to round the corners of the rectangle.

This property is read/write. The default value is 0.

Remarks

For the rectangle to have rounded corners, both the RadiusX and RadiusY properties must be non-zero.

A value greater than or equal to zero and less than or equal to half the rectangle's width that describes the x-radius of the ellipse is used to round the corners of the rectangle. Values greater than half the rectangle's width are treated as though equal to half the rectangle's width. Negative values are treated as positive values.

Applies To

Rectangle

See Also

Width, Height, Shapes and Drawing in Silverlight Overview


RadiusX Property (RectangleGeometry)

Gets or sets the x-radius of the ellipse used to round the corners of the rectangle geometry.

XAML
<object RadiusX="Double" .../>
Scripting
value = object.RadiusX
object.RadiusX = value

Property Value

Double

The x-radius of the ellipse used to round the corners of the rectangle geometry.

This property is read/write. The default value is 0.

Remarks

For the rectangle geometry to have rounded corners, both the RadiusX and RadiusY properties must be non-zero.

A value greater than or equal to zero and less than or equal to half the rectangle's width that describes the x-radius of the ellipse is used to round the corners of the rectangle. Values greater than half the rectangle's width are treated as though equal to half the rectangle's width. Negative values are treated as positive values.

The following illustration shows three rectangles with varying degress of rounded corners:

Rectangles with different RadiusX/RadiusY settings

Applies To

RectangleGeometry

RectangleGeometry, Silverlight Geometries Overview


RadiusY Property (EllipseGeometry)

Gets or sets the y-radius value of the EllipseGeometry.

XAML
<object RadiusY="Double" .../>
Scripting
value = object.RadiusY
object.RadiusY = value

Property Value

Double

The y-radius value of the EllipseGeometry.

This property is read/write. The default value is 0. If you do not specify a value for RadiusX and RadiusY, the ellipse will not render.

Remarks

Setting identical RadiusX and RadiusY values results in a circle.

Applies To

EllipseGeometry

See Also

Silverlight Geometries Overview, RadiusX, Ellipse


RadiusY Property (RadialGradientBrush)

Gets or sets the vertical radius of the outermost circle of a radial gradient.

XAML
<object RadiusY="Double" .../>
Scripting
value = object.RadiusY
object.RadiusY = value

Property Value

Double

The vertical radius of the outermost circle of a radial gradient.

This property is read/write. The default value is 0.5.

Remarks

The MappingMode property of a RadialGradientBrush determines whether its properties are interpreted as a relative or absolute value. By default, RadiusY is treated as relative, which corresponds to a MappingMode of RelativeToBoundingBox. In this case, the default value of 0.5, combined with the default Center value of 0.5,0.5, makes the circle be as high as the area where the brush is applied, centered exactly on the middle of that area. A MappingMode of Absolute specifies that the RadiusY value is expressed in device independent pixels, not as a factor within the bounding box of the area where the brush is applied.

Applies To

RadialGradientBrush

See Also

LinearGradientBrush, Silverlight Brushes Overview


RadiusY Property (Rectangle)

Gets or sets the y-axis radius of the ellipse that is used to round the corners of the rectangle.

XAML
<object RadiusY="Double" .../>
Scripting
value = object.RadiusY
object.RadiusY = value

Property Value

Double

The y-axis radius of the ellipse that is used to round the corners of the rectangle.

This property is read/write. The default value is 0.

Remarks

For the rectangle to have rounded corners, both the RadiusX and RadiusY properties must be non-zero.

A value greater than or equal to zero and less than or equal to half the rectangle's width that describes the y-radius of the ellipse is used to round the corners of the rectangle. Values greater than half the rectangle's width are treated as though equal to half the rectangle's width. Negative values are treated as positive values.

Applies To

Rectangle

See Also

Width, Height, Shapes and Drawing in Silverlight Overview


RadiusY Property (RectangleGeometry)

Gets or sets the y-radius of the ellipse use to round the corners of the rectangle geometry.

XAML
<object RadiusY="Double" .../>
Scripting
value = object.RadiusY
object.RadiusY = value

Property Value

Double

The y-radius of the ellipse used to round the corners of the rectangle geometry.

This property is read/write. The default value is 0.

Remarks

For the rectangle geometry to have rounded corners, both the RadiusX and RadiusY properties must be non-zero.

A value greater than or equal to zero and less than or equal to half the rectangle's width that describes the y-radius of the ellipse use to round the corners of the rectangle. Values greater than half the rectangle's width are treated as though equal to half the rectangle's width. Negative values are treated as positive values.

The following illustration shows three rectangles with varying degress of rounded corners:

Rectangles with different RadiusX/RadiusY settings

Applies To

RectangleGeometry, Silverlight Geometries Overview


Rect Property

Gets or sets the dimensions of the rectangle.

XAML
<object Rect="Rect" .../>
Scripting
value = object.Rect
object.Rect = value

Property Value

Rect

An object that declares the position and size of the rectangle.

This property is read/write. The default value is null.

Remarks

See remarks in Rect for scripting usages of this property.

Applies To

RectangleGeometry

See Also

Rect, Silverlight Geometries Overview


RelativeTransform Property

Gets or sets the transformation that is applied to the brush using relative coordinates.

XAML
<object RelativeTransform="Transform" .../>
Scripting
value = object.RelativeTransform
object.RelativeTransform = value

Property Value

Transform

The transformation that is applied to the brush using relative coordinates.

This property is read/write. The default value is null.

Remarks

This property is especially useful when you want to rotate, scale, skew, or otherwise transform a brush about its center, but you don't know the size of the area painted with the brush, or you are using the same brush to paint different areas with different sizes.

Applies To

ImageBrush, LinearGradientBrush, RadialGradientBrush, SolidColorBrush, VideoBrush


RenderTransform Property

Gets or sets transform information that affects the rendering position of this object.

XAML
<object ...>
  <object.RenderTransform>
    <Transform .../>
  </object.RenderTransform>
</object>
Scripting
value = object.RenderTransform
object.RenderTransform = value

Property Value

Transform

Describes the specifics of the desired render transform.

This property is read/write. The default value is null.

The Transform object can either be a single type of transform (such as RotateTransform) or a TransformGroup. The TransformGroup is not a transform per se, but is instead a container that enables you to specify more than one transform for a RenderTransform as markup children in XAML, or through TransformGroup.Children in script.

The local 0,0 for an object can be offset on a Canvas using Canvas.Left and Canvas.Top, but this does not count as a transform; the object retains its own local 0,0 in this case for transform purposes. For details on this concept, see Object Layout in Silverlight.

The render transform origin can also be offset with RenderTransformOrigin.

Applies To

Canvas, Ellipse, Glyphs, Image, InkPresenter, Line, MediaElement, Path, Polygon, Polyline, Rectangle, TextBlock

See Also

RenderTransformOrigin, Silverlight Transforms Overview


RenderTransformOrigin Property

Gets or sets the center point of any possible render transform declared by RenderTransform, relative to the bounds of the element.

XAML
<object RenderTransformOrigin="Point" .../>
Scripting
value = object.renderTransformOrigin
object.renderTransformOrigin = value

Property Value

Point

The center point of the render transform.

This property is read/write. The default value is 0,0.

Applies To

Canvas, Ellipse, Glyphs, Image, InkPresenter, Line, MediaElement, Path, Polygon, Polyline, Rectangle, TextBlock

See Also

RenderTransform


RepeatBehavior Property

Gets or sets the repeating behavior of this timeline.

XAML
<object RepeatBehavior="RepeatBehavior" .../>
Scripting
value = object.RepeatBehavior
object.RepeatBehavior = value

Property Value

RepeatBehavior

Describes the repeating behavior of this timeline

This property is read/write. The default is 1x (one iteration).

Remarks

RepeatBehavior has three possible modes: a duration, an iteration count, or the literal "Forever". The duration mode is assumed if there is no literal "x" in the string. To specify a duration in seconds, you must precede the value with "0:0:", because the duration is in the format [days.]hours:minutes:seconds.

See RepeatBehavior for details on the string format you use to specify a RepeatBehavior value, either in script or XAML. Creating a RepeatBehavior in XAML is only possible through a type conversion syntax when setting a property that takes a RepeatBehavior as an attribute string. Basically, a RepeatBehavior can be defined as an h:m:s string, a repetitionsx string, or the special value "Forever".

This property applies both to specific animations and to the parent storyboard. Generally for an animation in a storyboard, you should apply the RepeatBehavior to the storyboard, because otherwise the parent storyboard default of "1x" will prevent any child repeat behaviors from being applied. But you might specify repeat behaviors on child animations if they are intended to run fewer seconds or iterations than the parent storyboard.

Applies To

ColorAnimation, ColorAnimationUsingKeyFrames, DoubleAnimation, DoubleAnimationUsingKeyFrames, PointAnimation, PointAnimationUsingKeyFrames, Storyboard

See Also

Animation Overview


Resources Property

Gets or sets a collection of Storyboard objects that you can use to control animations.

XAML
<object>
  <object.Resources>
   <Storyboard ...>
   [<Storyboard ...>]
  </object.Resources>
<object>
Scripting
value = object.resources
object.resources = value

Property Value

ResourceDictionary

A collection of Storyboard objects.

This property is read/write. The default value is an empty collection.

Remarks

Unlike a Storyboard associated with an EventTrigger, a Storyboard defined as a resource does not start automatically. You can retrieve a reference to the Storyboard by assigning it a name and using the FindName method. You can then control the Storyboard by using its interactive methods: Begin, Pause, Resume, and Stop.

The XAML syntax for the Resources property is an example of an implicit collection syntax. For scripting, the property type of the property is ResourceDictionary, but you can omit the ResourceDictionary opening and closing tags in your markup because they are implicit. Instead, you include one or more Storyboard elements as child elements of <object.Resources>. For more information about XAML implicit collection syntax, see XAML Syntax Overview. (Explicitly including a ResourceDictionary object element is permissible XAML syntax.)

Examples

The following example makes a rectangle fade from view when the user presses the left mouse button over it. Because it is defined as a resource, the animation does not start automatically.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Canvas.Resources>
    <Storyboard x:Name="myStoryboard">
      <DoubleAnimation
        Storyboard.TargetName="MyAnimatedRectangle"
        Storyboard.TargetProperty="Opacity"
        From="1.0" To="0.0" Duration="0:0:5"
        AutoReverse="True" />
    </Storyboard>
  </Canvas.Resources>
  <Rectangle
    x:Name="MyAnimatedRectangle"
    Width="100"
    Height="100"
    Fill="Blue"
    MouseLeftButtonDown="startAnimation">
  </Rectangle>
</Canvas>
JavaScript
function startAnimation(sender, mouseEventArgs)
{
    // Retrieve the Storyboard and begin it.
    sender.findName("myStoryboard").begin();

}

Applies To

Canvas, Ellipse, Glyphs, Image, InkPresenter, Line, MediaElement, Path, Polygon, Polyline, Rectangle, TextBlock

See Also

Interactive Animations Overview


ResponseText Property

Silverlight SDK

ResponseText

Gets downloaded data from a successful download request.

XAML | Cannot be used in XAML.
Scripting | value = downloaderObject.ResponseText

Property Value

string

The downloaded data. As in HTML, the return value can be examined and is passed as a string in a packet, but ultimately is interpreted by whatever property you set with this value.

Remarks

You generally only use this property from within the event handler for a Downloader Completed event. Outside of this context, there is no guarantee that a ResponseText value is valid.

When a Downloader object request is completed and successful, the ResponseText property contains a representation of the downloaded content as a string value. The value can represent XAML content, JavaScript content, or a media asset, such as an image.

If you are requesting parts of a package, use GetResponseText.

Note If you are downloading media assets for use by the Source property of Image and MediaElement objects, you should consider using the SetSource (Image) or SetSource (MediaElement) methods rather than setting an object with GetResponseText or ResponseText and then setting the Source properties. This is a more efficient way to transfer large-sized media assets. ImageBrush also has an equivalent SetSource.

Applies To

Downloader

See Also

Completed, SetSource (MediaElement), Status, StatusText, Using a Downloader Object


Root Property

Gets the object that is at the content root for the current Silverlight plug-in.

Scripting (Instantiation)
Not directly set during instantiation, but influenced by instantiation source value.
Scripting (Runtime)
value = silverlightObject.content.Root

Property Value

UIElement

This property is read-only. The default value is null.

Remarks

This property is available on the content sub-object of a Silverlight plug-in instance.

References to the root object are useful when you want to add children to content. The typical root element is a Canvas.

You cannot use this property to reset the content root. You must reset Source instead.

Applies To

Silverlight Plug-in

See Also

Children Source, Using a Silverlight Plug-in, Using CreateSilverlight.js and Silverlight.js,


RotationAngle Property

Gets or sets the amount (in degrees) by which the ellipse is rotated about the x-axis.

XAML
<object RotationAngle="Double" .../>
Scripting
value = object.RotationAngle
object.RotationAngle = value

Property Value

Double

The amount (in degrees) by which the ellipse is rotated about the x-axis.

This property is read/write. The default value is 0.

Remarks

The following illustration shows several elliptical arcs that are identical except for their RotationAngle settings.

ArcSegments with different RotationAngle settings

Applies To

ArcSegment

See Also

Path Markup Syntax


RoutedEvent Property

Gets or sets the owning object type and routed event name that will activate this trigger. Only the Loaded event is supported.

XAML
<object RoutedEvent="parentObjectType.Loaded" .../>
Scripting
value = object.routedEvent
object.RoutedEvent = "parentObjectType.Loaded"

Terms

Term | Definition
parentObjectType | The type of object to which this EventTrigger belongs, such as "Rectangle" or "Canvas."

Property Value

string

The RoutedEvent that will activate this trigger.

This property is read/write. The default value is an empty string.

Remarks

For animations that are intended to trigger from events other than Loaded, create a conventional event handler, which can either be referenced in XAML attribute syntax or by adding it with AddEventListener. Within the event handler code, get a reference to a Storyboard (typically these are stored as Resources) and then call the Begin method on that Storyboard.

Applies To

EventTrigger

See Also

Loaded, Interactive Animations Overview, Animation Overview


ScaleX Property

Gets or sets the x-axis scale factor.

XAML
<object ScaleX="Double" .../>
Scripting
value = object.scaleX
object.scaleX = value

Property Value

Double

The scale factor along the x-axis.

This property is read/write. The default value is 1.

Remarks

The local origin (0,0) for an object can be offset on a Canvas using Canvas.Left and Canvas.Top, but this does not count as a transform; the object retains its own local origin in this case for transformation purposes. For details on this concept, see Object Layout in Silverlight.

Values between 0 and 1 decrease the width of the scaled object; values greater than 1 increase the width of the scaled object. A value of 1 indicates that the object is not scaled in the x-direction.

Negative values flip the scaled object horizontally. Values between 0 and -1 flip the scale object and decrease its width. Values less than -1 flip the object and increase its width. A value of -1 flips the scaled object but does not change its horizontal size.

Applies To

ScaleTransform

See Also

Silverlight Transforms Overview, Object Layout in Silverlight


ScaleY Property

Gets or sets the y-axis scale factor.

XAML
<object ScaleY="Double" .../>
Scripting
value = object.ScaleY
object.ScaleY = value

Property Value

Double

The scale factor along the y-axis.

This property is read/write. The default value is 1.

Remarks

The local origin (0,0) for an object can be offset on a Canvas using Canvas.Left and Canvas.Top, but this does not count as a transform; the object retains its own local origin in this case for transformation purposes. For details on this concept, see Object Layout in Silverlight.

Values between 0 and 1 decrease the height of the scaled object; values greater than 1 increase the height of the scaled object. A value of 1 indicates that the object is not scaled in the y-direction.

Negative values flip the scaled object vertically. Values between 0 and -1 flip the scale object and decrease its height. Values less than -1 flip the object and increase its height. A value of -1 flips the scaled object but does not change its vertical size.

Applies To

ScaleTransform

See Also

Silverlight Transforms Overview, Object Layout in Silverlight


Seconds Property (Duration)

Gets or sets the number of seconds that the Duration represents.

XAML
No direct attribute syntax; see Remarks.
Scripting
value = object.Seconds
object.Seconds = value

Property Value

Double

The number of seconds that the Duration represents.

This property is read/write. The default value is 0.

Remarks

You cannot set the Seconds property as a distinct attribute of a Duration in XAML, because it is not possible to create a Duration element in XAML.

You can set or get the Seconds value in script using object.property syntax, after getting an existing Duration from a property value such as TimeLine.Duration. You can set the value on a running animation, and the value will apply immediately. The new current state of the animation will reflect the progress of the animation that had already run prior to the change, with that same progress applied towards the new Duration. Setting a Seconds value on an animation that previously had Automatic or Forever behavior has this same effect.

If the Duration for an animation is not explicitly set (either through scripting or XAML), then the value of object.Duration will be null. In this case, scripting for object.Duration.Seconds will produce an error, because the Duration is null.

The Seconds value is the converted summation of all the possible unit inputs for a Duration. For instance, a Duration created with an attribute value of "0:01:00.555" will have a Seconds value of 60.555. Only the Seconds property exists for getting the representative value in script; there are no JavaScript object model scripting properties for "Minutes", "Days", "Milliseconds", etc. The Seconds value is 0 for a Duration created with an attribute value of "Automatic" or "Forever".

Applies To

Duration

See Also

Animation Overview


Seconds Property (KeyTime)

Gets or sets the number of seconds that the KeyTime represents.

XAML
No direct attribute syntax; see Remarks.
Scripting
value = object.Seconds
object.Seconds = value

Property Value

Double

The number of seconds that the KeyTime represents.

This property is read/write. The default value is 0.

Remarks

Setting this property is only possible through a type conversion syntax when setting a property that takes a KeyTime as an attribute string. You cannot set the Seconds property as a distinct attribute of a KeyTime in XAML, because it is not possible to create a KeyTime element in XAML.

You can set or get the Seconds value in script using object.property syntax, after getting an existing KeyTime as a property value. You can set the value on a running animation, and the value will apply the next time the same animation is started.

If a property that takes a KeyTime is not explicitly set (either through scripting or XAML), then the value of that property might be null. In this case, scripting for object.Seconds will produce an error, because the object is null.

The Seconds value is the converted summation of all the possible unit inputs for a KeyTime. For instance, a KeyTime created with an attribute value of "0:01:00.555" will have a Seconds value of 60.555. Only the Seconds property exists for getting the representative value; there are no scripting properties for Minutes, Days, Milliseconds, etc.

Applies To

KeyTime

See Also

Animation Overview


Seconds Property (TimeSpan)

Gets or sets the number of seconds that the TimeSpan represents.

XAML
No direct attribute syntax; see Remarks.
Scripting
value = object.Seconds
object.Seconds = value

Property Value

Double

The number of seconds that the TimeSpan represents.

This property is read/write. The default value is 0.

Remarks

Setting this property is only possible through a type conversion syntax when setting a property that takes a TimeSpan as an attribute string. You cannot set the Seconds property as a distinct attribute of a TimeSpan in XAML, because it is not possible to create a TimeSpan object element in XAML.

You can set or get the Seconds value in script using object.property syntax, after getting an existing TimeSpan as a property value. You can set the value on a running animation, and the value will apply the next time the same animation is started.

If a property that takes a TimeSpan is not explicitly set (either through scripting or XAML), then the value of that property might be null. In this case, scripting for object.Seconds will produce an error, because the object is null.

The Seconds value is the converted summation of all the possible unit inputs for a TimeSpan. For instance, a TimeSpan created with an attribute value of "0:01:00.555" will have a Seconds value of 60.555. Only the Seconds property exists for getting the representative value; there are no scripting properties for Minutes, Days, Milliseconds, etc.

Applies To

TimeSpan

See Also

Animation Overview


Seconds Property (RepeatBehavior)

Gets or sets the number of seconds that the RepeatBehavior represents.

XAML
No direct attribute syntax; see Remarks.
Scripting
value = object.Seconds
object.Seconds = value

Property Value

Double

The number of seconds that the RepeatBehavior represents.

This property is read/write. The default value is 0.

Remarks

Setting this property is only possible through a type conversion syntax when setting a property that takes a RepeatBehavior as an attribute string. You cannot set the Seconds property as a distinct attribute of a RepeatBehavior in XAML, because it is not possible to create a RepeatBehavior element in XAML.

You can set or get the Seconds value in script using object.property syntax, after getting an existing RepeatBehavior as a property value. You can set the value on a running animation, and the value will apply the next time the same animation is started.

If a property that takes a RepeatBehavior is not explicitly set (either through scripting or XAML), then the value of that property might be null. In this case, scripting for object.Seconds will produce an error, because the object is null.

The Seconds value is the converted summation of all the possible unit inputs for a RepeatBehavior. For instance, a RepeatBehavior created with an attribute value of "0:01:00.555" will have a Seconds value of 60.555. Only the Seconds property exists for getting the representative value; there are no scripting properties for Minutes, Days, Milliseconds, etc.

If the RepeatBehavior was set as "Forever", or was set using the repetitionsx form (number of repetitions as a string followed by "x"), then the value of Seconds will be 0.

Applies To

RepeatBehavior

See Also

Animation Overview


Segments Property

Gets or sets the collection of segments that define the shape of this PathFigure object.

XAML
<PathFigure ...>
  oneOrMorePathSegments
</PathFigure>
Scripting
value = object.Segments
object.Segments = value

Property Value

PathSegmentsCollection

The collection of segments that define the shape of this PathFigure object.

This property is read/write. The default value is an empty collection.

Remarks

The XAML syntax for Segments is an example of an implicit collection syntax, where you can omit the PathSegmentCollection object element, as well as the <PathFigure.Segments> property element. Instead, you generally include one or more path segment object elements (ArcSegment, BezierSegment, LineSegment, PolyBezierSegment, PolyQuadraticBezierSegment, and QuadraticBezierSegment) as child elements of a PathSegment. For more information about XAML implicit collection syntax, see XAML Syntax Overview. (Explicitly including a PathSegmentCollection object element is permissible XAML syntax, and might be useful if you intend to name the collection in XAML and manipulate its contents through script later. Including the <PathFigure.Segments> property element might also be useful for markup clarity, because of the nested Figures and Segments collections found in a typical complex PathGeometry Object.)

Applies To

PathFigure


Shift Property (KeyboardEventArgs)

Gets a value specifying whether the Shift key was down when the event occurred.

XAML | This property cannot be used in XAML.
Scripting | value = eventargs.Shift

Property Value

Boolean

true if the Shift key was down when the event occurred; otherwise, false.

Remarks

Use this property to detect key combinations involving the Shift key that are otherwise interpreted as commands or gestures in other application programming models.

Applies To

KeyboardEventArgs

See Also

Silverlight Keyboard Support, Silverlight Events


Shift Property (MouseEventArgs)

Gets a value specifying whether the Shift key was down when the event occurred.

XAML | This property cannot be used in XAML.
Scripting | value = eventargs.Shift

Property Value

Boolean

true if the Shift key was down when the event occurred; otherwise, false.

Applies To

MouseEventArgs

See Also

Silverlight Events


Size (ArcSegment) Property

Gets or sets the x- and y-radius of the arc as a pair of values in a string.

XAML
<object Size="string" .../>
Scripting
value = object.Size
object.Size = value

Property Value

string

A string that describes the x- and y-radius of the elliptical arc. See Remarks.

This property is read/write. The default value is null, which is interpreted as width and height of 0.

Applies To

 ArcSegment

See Also

Path Markup Syntax


Source Property (Image)

Gets or sets the source for the image by specifying the URI for its image file location.

XAML
<object Source="string" .../>
Scripting
value = object.Source
object.Source = value

Property Value

string

The source of the drawn image, as a URI.

This property is read/write. The default value is null.

Remarks

The Source property can be used to reference images in the JPEG and PNG file formats.

The string provided for the Source property is interpreted as a Uniform Resource Identifier (URI). This is in contrast to an Internationalized Resource Identifiers (IRI). This distinction means that characters used to identify a Source that are outside of US-ASCII will need to be encoded.

Relative references are permitted. The starting location for the relative reference is the HTML page that contains the current Silverlight plug-in.

Cross-domain URIs are permitted, and specifying the scheme is permitted, but mixing URI schemes (such as accessing an HTTPS image from a Silverlight plug-in hosted on an HTTP-served HTML page) is not permitted. The JPEG and PNG filename extensions are not required to be in the URI, but if the retrieved file is but if the retrieved file is not determined to be either in JPEG or PNG format, a runtime exception is thrown.

If you are not accessing cross-domain sources, you should consider using SetSource rather than setting Source directly. This provides the advantage of being able to track the download. Also, you can download multiple images as a package and access parts from within the package.

In JavaScript, you can set the value to null or empty string at runtime to cause the image to unload and no longer render. Doing so does not fire an ImageFailed event. In contrast, setting Source to a URI value that does not resolve will fire an ImageFailed event. Also, a SetValue error is thrown, even if ImageFailed is handled.

You can specify an initial XAML value of "" (empty string) and then set the value in script at a later time, to create a nonrendering placeholder.

The ImageFailed event can occur if the initial Source attribute value in XAML does not specify a valid source.

Applies To

Image

See Also

ImageFailed, Using a Downloader Object


Source Property (MediaElement)

Gets or sets a media source on the MediaElement.

XAML
<object Source="string" .../>
Scripting
value = object.Source
object.Source = value

Property Value

string

A string that specifies the source of the element.

This property is read/write. The default value is null.

Remarks

Setting the Source will reset the media's Position to 00:00:00.

The string provided for the Source property is interpreted as a Uniform Resource Identifier (URI). This is in contrast to an Internationalized Resource Identifier (IRI). This distinction means that characters used to identify a Source that are outside of US-ASCII will need to be encoded.

Relative references are permitted. The starting location for the relative reference is the HTML page that contains the current Silverlight plug-in.

Cross-domain URIs are permitted (using http). You can also use the monikers mms:, rtsp:, or rtspt: in your URI to point to a media source. In each case the actual protocol and URI scheme falls back to http (with possible further fallbacks in behavior for differentiating streaming from progressive downloads), but the value of Source will retain your moniker.

If you are not accessing cross-domain sources or live streaming media, you should consider using the SetSource method instead of setting Source directly. This method provides the advantage of letting you track the download. Also, you can download content as a package and access parts from within the package.

In JavaScript, you can set the runtime value to null or an empty string to cause the media to unload and no longer render. Doing so does not fire an MediaFailed event. In contrast, setting Source to a URI value that does not resolve will fire a MediaFailed event. Also, a SetValue error is thrown.

You can specify an initial XAML value of "" (empty string) and then set the value in script at a later time, to create a nonplaying placeholder.

The MediaFailed event can occur if the initial Source attribute value in XAML does not specify a valid source.

Setting a cross-domain URI for Source will either succeed or will not return a valid status for any failure. In this case, a MediaFailed event does not occur. Instead, an error is thrown on the SetValue method call for setting "Source."

Backslashes (\) in Source URIs are not permitted; always use forward slashes (/).

Applies To

MediaElement

See Also

MediaFailed Event, Media Overview, Supported Media Formats and Protocols


Source Property (Silverlight Plug-in)

Specifies the XAML content to render.

Scripting (Instantiation)
Silverlight.CreateObject('sourceReference')

-or-

Silverlight.CreateObjectEx({source:'sourceReference'})
Scripting (Runtime)
value = silverlightObject.Source
silverlightObject.Source = value

Property Value

string

The URI of the XAML file or XAML scripting tag that contains the content to load into the Silverlight plug-in. Generally, this is a reference to a XAML file. The URI can also be an inline XAML reference using the "#" prefix; see Remarks.

This property is read/write. The default value is null.

Remarks

For more information on using JavaScript helper files for initializing and creating Silverlight plug-ins on a Web page, see Using CreateSilverlight.js and Silverlight.js.

Changing the Source value at runtime is permitted. In terms of performance in Silverlight version 1.0, this operation is equivalent to unloading and reloading the Silverlight plug-in. In some cases it may be better performance-wise to instead use CreateFromXaml and rebuild the object tree below the original root than it is to reset Source.

The string provided for the Source property is interpreted as a Uniform Resource Identifier (URI). This is in contrast to an Internationalized Resource Identifier (IRI). This distinction means that characters used to identify a Source that are outside of US-ASCII will need to be encoded.

The URI for Source cannot be set to a URI that is not from the site of origin of the HTML page that hosts the Silverlight plug-in instance. In general, this means that you should only use relative references to specify a Source URI.

The prefix '#' in the string is used to identify a Source that references inline XAML. See Using Inline XAML as the XAML Source (that topic includes an example of inline XAML usage).

Examples

The following JavaScript example of a modified CreateSilverlight.js file shows how to load a XAML file by setting the source initialization parameter to the name of the XAML file, "HelloWorld.xaml":

JavaScript
function createSilverlight()
{
    Sys.Silverlight.createObject(
        "HelloWorld.xaml",                  // Source property value.
        parentElement,                      // DOM reference to hosting DIV tag.
        "myPlugin",                        // Unique plug-in id value.
        {                                   // Plug-in properties.
            width:'1024',                   // Width of rectangular region of plug-in in pixels.
            height:'530',                   // Height of rectangular region of plug-in in pixels.
            inplaceInstallPrompt:false,      // Determines whether to display verbose install prompt if invalid version detected.
            background:'OldLace',           // Background color of plug-in.
            isWindowless:'true',            // Determines whether to display plug-in in Windowless mode.
            framerate:'30',                 // MaxFrameRate property value.
            version:'1.0'                   // Plug-in version to use.
        },
        {
            onError:null,                   // OnError property value -- event handler function name.
            onLoad:onLoad                   // OnLoad property value -- event handler function name.
        },
        null);                              // Context value -- event handler function name.
}

Notice that when the Source property or source parameter value refers to a file reference, it is set to the directory location of the XAML file relative to the HTML file.

The following XAML example shows the XAML content that corresponds to the file referenced by the Source property value in the previous HTML example.

XAML
<!-- HelloWorld.xaml -->
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007">
  <TextBlock
    Foreground="Maroon" FontFamily="Verdana" FontSize="24" FontWeight="Bold"
    Text="Hello, world" />
</Canvas>

Loading XAML Using the Source Property at Run Time

You can also use the Source property to load XAML content after the Silverlight plug-in has been created. When you reload XAML content, the existing XAML content is the plug-in is no longer valid. The following JavaScript example shows an event handler function that reloads the XAML content.

JavaScript
// Event handling function for reloading the XAML content on the page.
function reloadContent(plugin)
{
    // Define the XAML content.
    plugin.source = "HelloWorld.xaml";
}

Note The XAML content renders immediately when setting the Source property.

Applies To

Silverlight Plug-in

See Also

Using a Silverlight Plug-in, Using CreateSilverlight.js and Silverlight.js, Using Inline XAML as the XAML Source, Using the createFromXaml Method


SourceName Property (VideoBrush)

Silverlight SDK

SourceName (VideoBrush) Property

Gets or sets the Name of the MediaElement that provides video for this VideoBrush.

XAML
<object SourceName="string" .../>
Scripting
value = object.SourceName
object.SourceName = value

Property Value

string

The Name of the MediaElement that is the source of this VideoBrush.

This property is read/write. The default value is an empty string.

Remarks

For more information about how VideoBrush and MediaElement work together, see the VideoBrush Overview.

Applies To

VideoBrush

See Also

VideoBrush Overview


SpeedRatio Property

Gets or sets the rate, relative to its parent, at which time progresses for this Timeline.

XAML
<object SpeedRatio="Double" .../>
Scripting
value = object.SpeedRatio
object.SpeedRatio = value

Property Value

Double

A finite value greater than 0 that describes the rate at which time progresses for this timeline, relative to the speed of the timeline's parent or, if this is a root timeline, the default timeline speed.

This property is read/write. The default value is 1.

Remarks

Momentary or nonlinear apparent speed changes to animations can be accomplished using spline animations. For details, see Silverlight Key-Frame Animations Overview .

Applies To

ColorAnimation, ColorAnimationUsingKeyFrames, DoubleAnimation, DoubleAnimationUsingKeyFrames, PointAnimation, PointAnimationUsingKeyFrames, Storyboard

See Also

Animation Overview


SpreadMethod Property (LinearGradientBrush)

Gets or sets the type of spread method that specifies how to draw a gradient that starts or ends inside the bounds of the object to be painted.

XAML
<object SpreadMethod="SpreadMethod" .../>
Scripting
value = object.SpreadMethod
object.SpreadMethod = value

Property Value

SpreadMethod

A value of the SpreadMethod enumeration that specifies type of spread method used to paint the gradient.

This property is read/write. The default value is Pad.

Remarks

The following illustration shows the available spread methods and their effect on LinearGradientBrush and RadialGradientBrush. The red line indicates the gradient space. A LinearGradientBrush defines its gradient space with its StartPoint and EndPoint properties. A RadialGradientBrush defines its gradient space with its Center, RadiusX, and RadiusY properties.

Different GradientSpread settings

Applies To

LinearGradientBrush

See Also

Silverlight Brushes Overview


SpreadMethod Property (RadialGradientBrush)

Gets or sets the type of spread method that specifies how to draw a gradient that starts or ends inside the bounds of the object to be painted.

XAML
<object SpreadMethod="SpreadMethod" .../>
Scripting
value = object.SpreadMethod
object.SpreadMethod = value

Property Value

SpreadMethod

A value of the SpreadMethod enumeration that specifies type of spread method used to paint the gradient.

This property is read/write. The default value is Pad.

Remarks

The following illustration shows the available spread methods and their effect on LinearGradientBrush and RadialGradientBrush. The red line indicates the gradient space. A LinearGradientBrush defines its gradient space with its StartPoint and EndPoint properties. A RadialGradientBrush defines its gradient space with its Center, RadiusX, and RadiusY properties.

Different GradientSpread settings

Applies To

RadialGradientBrush

See Also

Silverlight Brushes Overview


StartPoint Property (LinearGradientBrush)

Gets or sets the starting two-dimensional coordinates of the linear gradient.

XAML
<object StartPoint="Point" .../>
Scripting
value = object.StartPoint
object.StartPoint = value

Property Value

Point

The starting two-dimensional coordinates for the linear gradient.

This property is read/write. The default value is 0,0.

Remarks

See remarks in Point for scripting usages of this property.

A LinearGradientBrush paints an area with a linear gradient. A linear gradient defines a gradient along a line. The line's end points are defined by the StartPoint and EndPoint properties of the linear gradient. A LinearGradientBrush brush paints its GradientStops along this line.

The default linear gradient is diagonal, and the default mode for the gradient coordinate system is RelativeToBoundingBox. With these defaults, the StartPoint of a linear gradient the upper-left corner of the area being painted, 0,0. Its EndPoint is the lower-right corner of the area being painted, 1.1. The colors in the resulting gradient are interpolated and applied along vectors that parallel this diagonal axis.

The following illustration shows a diagonal gradient. A line was added to highlight the interpolation path of the gradient from the start point to the end point.

Gradient axis for a diagonal linear gradient

The next illustration shows the same linear gradient, but with highlighted gradient stops.

Gradient stops in a linear gradient

Specifying Relative or Absolute Values

Note that the BrushMappingMode property of a LinearGradientBrush determines whether its StartPoint is interpreted as a relative or absolute value. A MappingMode of RelativeToBoundingBox specifies that the StartPoint and EndPoint values are relative to the size of the painted area. A MappingMode of Absolute specifies that the StartPoint and EndPoint values are expressed in device independent pixels. By default, the MappingMode is set to RelativeToBoundingBox, making the StartPoint a relative value.

Applies To

LinearGradientBrush

See Also

RadialGradientBrush, Silverlight Brushes Overview


StartPoint Property (LineGeometry)

Gets or sets the start point of the line.

XAML
<object StartPoint="Point" .../>
Scripting
value = object.StartPoint
object.StartPoint = value

Property Value

Point

The starting point of the line geometry.

This property is read/write. The default value is 0,0.

Remarks

See remarks in Point for scripting usages of this property.

Applies To

LineGeometry

See Also

Silverlight Geometries Overview


StartPoint Property (PathFigure)

Gets or sets the Point where the PathFigure begins.

XAML
<object StartPoint="Point" .../>
Scripting
value = object.StartPoint
object.StartPoint = value

Property Value

Point

The Point where the PathFigure begins.

This property is read/write. The default value is 0,0.

Remarks

See remarks in Point for scripting usages of this property.

Applies To

PathFigure

See Also

Figures, StartPoint, Silverlight Geometries Overview, Path Markup Syntax


Status Property

Gets the current status of the Downloader object request.

XAML | Cannot be used in XAML.
Scripting | value = downloaderObject.Status

Property Value

integer

Gets the HTTP status code value that represents the current state of the Downloader object request.

This property is read-only. The default value is 0.

Remarks

The HTTP status code reflects the current state of the Downloader request as specified by the verb parameter in the Open method. For example, if the verb parameter is "GET" and the resulting download was successful, the value of Status is 200, and the value of StatusText is "OK".

The following table lists the HTTP status codes that the Downloader reports. For more information, see HTTP Status Codes.

Status code | Status text | Description
200 | OK | The request completed successfully.
204 | No content | The server has not found any content matching the request URI.

Applies To

Downloader

See Also

Completed, GetResponseText, StatusText, Using a Downloader Object


StatusText Property

Gets the current status of the Downloader object request.

XAML | Cannot be used in XAML.
Scripting | value = downloaderObject.StatusText

Property Value

string

Gets a string value that corresponds to the Status property value of a Downloader object request.

This property is read-only. The default value is an empty string.

Remarks

The HTTP status code reflects the current state of the Downloader request as specified by the verb parameter in the Open method. For example, if the verb parameter is "GET" and the resulting download was successful, the value of Status is 200, and the value of StatusText is "OK".

The following table lists the HTTP status codes that the Downloader reports. For more information, see HTTP Status Codes.

Status code | Status text | Description
200 | OK | The request completed successfully.
204 | No content | The server has not found anything matching the request URI.

Applies To

Downloader

See Also

Completed, GetResponseText, ResponseText, Status, Using a Downloader Object


Storyboard Property

Gets or sets the Storyboard that this BeginStoryboard starts.

XAML
<object Storyboard="Storyboard" .../>
Scripting
value = object.Storyboard
object.Storyboard = value

Property Value

Storyboard

The Storyboard that the BeginStoryboard starts.

This property is read/write. The default value is null.

Applies To

BeginStoryboard

See Also

Path Markup Syntax, SweepDirection


Stretch Property (Image)

Gets or sets a value that describes how an Image should be stretched to fill the destination rectangle.

XAML
<object Stretch="Stretch" .../>
Scripting
value = object.Stretch
object.Stretch = value

Property Value

Stretch

A value of the Stretch enumeration that specifies how the source image is applied if the Height and Width of the Image are specified and are different than the source image's height and width.

This property is read/write. The default value is Uniform.

Remarks

A value of Fill will cause your image to stretch to completely fill the output area. When the output area and the image have different aspect ratios, the image is distorted by this stretching. To make an Image preserve the aspect ratio of the image, set this property to Uniform (the default) or UniformToFill. Alternatively, you can leave Height and Width of the Image unset, which will display the image source at its true resolution, although this results in loss of control over the element sizing in XAML.

Applies To

Image

See Also

ImageBrush


Stretch Property (ImageBrush)

Gets or sets a value that specifies how the content of this ImageBrush stretch to the applied brush area.

XAML
<object Stretch="Stretch" .../>
Scripting
value = object.Stretch
object.Stretch = value

Property Value

Stretch

A value that specifies how the content is rendered.

This property is read/write. The default value is Fill.

Remarks

The Stretch property accepts the following values, which the Stretch enumeration defines:

  • None: The content does not stretch to fill the output dimensions, and the applied brush area will come from the matching sized area of the image. If AlignmentX and AlignmentY are at their defaults, this results in only the center area of the image applied to the brush.

  • Uniform: The content is scaled to fit the output dimensions. However, the aspect ratio of the content is preserved.

  • UniformToFill: The content is scaled so that it completely fills the output area but preserves its original aspect ratio.

  • Fill: The content is scaled to fit the output dimensions. Because the content's height and width are scaled independently, the original aspect ratio of the content might not be preserved. That is, the content might be distorted in order to completely fill the output area.

Applies To

ImageBrush

See Also

Silverlight Brushes Overview


Stretch Property (MediaElement)

Gets or sets a Stretch value that describes how a MediaElement fills the destination rectangle.

XAML
<object Stretch="Stretch" .../>
Scripting
value = object.Stretch
object.Stretch = value

Property Value

Stretch

The stretch value for the rendered media.

This property is read/write. The default value is Uniform.

Remarks

The following illustration demonstrates the different Stretch values.

Different Stretch settings

Applies To

MediaElement

See Also

Media Overview, Supported Media Formats and Protocols


Stretch Property (Shape)

Gets or sets a value that describes how the shape fills its allocated space.

XAML
<object Stretch="Stretch" .../>
Scripting
value = object.Stretch
object.Stretch = value

Property Value

Stretch

A value of the Stretch enumeration that specifies the stetch behavior.

This property is read/write. The default value depends on the type of Shape.

Remarks

Generally, you do not set the Stretch value for a Shape. This is because the Stretch is adjusted for each type of Shape in such a way that each Shape type's sizing and positioning properties are interpreted in the most intuitive way.

The concept of a Stretch for a Shape has to do with its natural size and how the Shape is positioned in layout. Ultimately for the layout system, all objects that render to the screen are rectangles with a width and a height. This is reflected in the presence of the properties Width and Height at the UIElement level in the object model. Some types of Shapes (Ellipse, Rectangle) can have natural sizes that are well represented by these Width and Height properties, and as a result these are the only properties you use to provide the size (although the shape that renders within that natural size is still influenced by other properties such as RadiusX). But other types of Shape such as Line or Path have other specific properties that declare the shape, and in this case the appropriate behavior is to have Width and Height be deterministic properties, calculated based on values you provide for the specific sizing properties, such as the X1, Y1, X2, Y2 of a Line. However, even for a shape like Line, Width and Height are still settable. The Stretch for a Shape influences what should happen if Width and Height are deliberately set.

For Ellipse or Rectangle, the default Stretch behavior is Fill, because their entire sizing logic is based on the Width and Height. Setting Stretch to None for a Ellipse or Rectangle effectively makes it nonrendering.

For the other shapes, the the default Stretch behavior is None. Setting Stretch to other values effectively introduces a transform, which could probably be controlled more efficiently with a true transform if that was a desired effect.

Applies To

Ellipse, Line, Path, Polygon, Polyline, Rectangle

See Also

Shapes Overview, Silverlight Brushes Overview, Object Layout in Silverlight


Stretch Property (VideoBrush)

Gets or sets a value that specifies how the video of this brush stretches to fill the painted area.

XAML
<object Stretch="Stretch" .../>
Scripting
value = object.Stretch
object.Stretch = value

Property Value

Stretch

A value that specifies how this brush's video content stretches to fill the painted area.

This property is read/write. The default value is Fill

Remarks

The Stretch property accepts the following values, which the Stretch enumeration defines:

  • None: The video does not stretch to fill the output dimensions.

  • Uniform: The video is scaled to fit the output dimensions. However, the aspect ratio of the content is preserved.

  • UniformToFill: The video is scaled so that it completely fills the output area but preserves its original aspect ratio.

  • Fill: The video is scaled to fit the output dimensions. Because the content's height and width are scaled independently, the original aspect ratio of the video might not be preserved. That is, the video might be distorted in order to completely fill the output area.

The following image illustrates the different Stretch settings.

Different Stretch settings

Applies To

VideoBrush

See Also

VideoBrush Overview


Stroke Property

Gets or sets the Brush that specifies how to paint the Shape outline.

XAML
<object Stroke="Brush" .../>
-or-
<object>
  <object.Stroke>
    <Brush" .../>
  </object.Stroke>
</object>
Scripting
value = object.Stroke
object.Stroke = value

Property Value

Brush

A Brush that specifies how the Shape outline is painted.

This property is read/write. The default value is null.

Remarks

Setting the Stroke for a line (Line or Polyline) defines its entire brush-defined appearance. Setting Fill for a line has no effect.

Some brush types (SolidColorBrush) support a XAML attribute syntax, whereas other brush types (ImageBrush, LinearGradientBrush, RadialGradientBrush) only support an object element syntax. This is why two versions of XAML syntax are shown for this property.

Applies To

Ellipse, Line, Path, Polygon, Polyline, Rectangle, Shape

See Also

Shapes Overview, Silverlight Brushes Overview, Object Layout in Silverlight


StrokeDashArray Property

Gets or sets a string of double values that indicates the pattern of dashes and gaps that is used to outline shapes.

XAML | <object StrokeDashArray="stringOfDoubles" .../>
Scripting | object.StrokeDashArray = "stringOfDoubles"

Property Value

stringOfDoubles

A string composed of double values that specify the pattern of dashes and gaps. See Remarks.

This property is write-only. The default value is null.

Remarks

Each double value in the string specifies the length of a dash or gap relative to the thickness of the pen. For example, a value of 1 creates a dash or gap that has the same length as the thickness of the pen (a square).

The first double entry in the string specifies the length of a dash; the second double entry specifies the length of a gap.

Double entries can be separated by either commas or spaces.

More than one pair of entries can be included in the string, and will repeat in a pattern. Even-numbered entries specify dashes; odd-numbered entries specify gaps. If an odd-numbered total of entries is in the string, then the missing even-numbered entry of a pair will use the gap value specified by the last valid (even-numbered entry) gap value.

Applies To

Ellipse, Line, Path, Polygon, Polyline, Rectangle, Shape

See Also

Shapes Overview


StrokeDashCap Property

Gets or sets a PenLineCap enumeration value that specifies how the ends of a dash are drawn.

XAML
<object StrokeDashCap="PenLineCap" .../>
Scripting
value = object.StrokeDashCap
object.StrokeDashCap = value

Property Value

PenLineCap

A values of the PenLineCap enumeration that specifies the caps.

This property is read/write. The default value is Flat.

Remarks

This setting applies to both ends of each dash.

Applies To

Ellipse, Line, Path, Polygon, Polyline, Rectangle, Shape

See Also

Shapes Overview


StrokeDashOffset Property

Gets or sets a value that specifies the distance within the dash pattern where a dash begins.

XAML
<object StrokeDashOffset="Double" .../>
Scripting
value = object.StrokeDashOffset
object.StrokeDashOffset = value

Property Value

Double

A Double that represents the distance within the dash pattern where a dash begins.

This property is read/write. The default value is 0.

Applies To

Ellipse, Line, Path, Polygon, Polyline, Rectangle, Shape

See Also

Shapes Overview


StrokeEndLineCap Property

Gets or sets a value that describes the Shape at the end of a line.

XAML
<object StrokeEndLineCap="PenLineCap" .../>
Scripting
value = object.StrokeEndLineCap
object.StrokeEndLineCap = value

Property Value

PenLineCap

A value of the PenLineCap enumeration that describes the end cap shape.

This property is read/write. The default value is Flat.

Remarks

This property has no effect if you set it on a shape that has no Stroke or that has no discrete start or end points. For example, this property has no effect if you set it on an Ellipse.

Applies To

Ellipse, Line, Path, Polygon, Polyline, Rectangle, Shape

See Also

Shapes Overview


StrokeLineJoin Property

Gets or sets a value that specifies the type of join used at the vertices of a Shape.

XAML
<object StrokeLineJoin="PenLineJoin" .../>
Scripting
value = object.StrokeLineJoin
object.StrokeLineJoin = value

Property Value

PenLineJoin

A value of the PenLineJoin enumeration that specifies the join appearance.

This property is read/write. The default value is Miter.

Remarks

This property has no effect if you set it on an element that has no vertices, such as a Line element.

Applies To

Ellipse, Line, Path, Polygon, Polyline, Rectangle, Shape

See Also

Shapes Overview


StrokeMiterLimit Property

Gets or sets a limit on the ratio of the miter length to half the StrokeThickness of a Shape element.

XAML
<object StrokeMiterLimit="Double" .../>
Scripting
value = object.StrokeMiterLimit
object.StrokeMiterLimit = value

Property Value

Double

The limit on the ratio of the miter length to the StrokeThickness of a Shape element. This value is always a positive number that is greater than or equal to 1.

This property is read/write.

Remarks

A miter forms a corner by beveling the ends of two joined lines. When two line segments meet at a small angle (sharp angle), the miter may extend beyond the thickness of the line that strokes the path.

Applies To

Ellipse, Line, Path, Polygon, Polyline, Rectangle, Shape

See Also

Shapes Overview


Strokes Property

Gets or sets the collection of ink strokes that corresponds to the InkPresenter.

XAML
<InkPresenter>
  <InkPresenter.Strokes>
    oneOrMoreStrokes
  <InkPresenter.Strokes/>
<InkPresenter/>
Scripting
value = object.Strokes
object.Strokes = value

Property Value

StrokeCollection

The collection of ink strokes that corresponds to the InkPresenter.

This property is read/write.

Remarks

In practical terms, you would generally never replace the entire Strokes collection (by using the "set" aspect of this property). It is also uncommon to prepopulate the Strokes collection in the initially loaded XAML. However, once the collection of strokes is populated by user input, you might add, remove or query items from the existing collection.

Examples

JavaScript
var agCtrl;
var inkPresenter; // Corresponds to InkPresenter element in xaml
var newStroke = null; // The Stroke variable we'll use here in mouse handlers
// DrawingAttributes variables
var daWidth = 2;
var daHeight = 2;
var daColor = "Black";
var daOutlineColor = "Black";

function root_Loaded(sender, args)
{
    // Get the html object which contains the Silverlight plug-in
    agCtrl = sender.GetHost();
    inkPresenter = sender.findname("inkPresenterElement");
}

// Capture mouse movement when the left button is pressed and create the stroke
function InkPresenterMouseDown(sender,args)
{
   inkPresenter.CaptureMouse();

   newStroke = agCtrl.content.createFromXaml('<Stroke/>');

   var da = agCtrl.content.CreateFromXaml('<DrawingAttributes/>');
   newStroke.DrawingAttributes = da;

   // Set the drawing attributes properties
   newStroke.DrawingAttributes.Width = daWidth;
   newStroke.DrawingAttributes.Height = daHeight;
   newStroke.DrawingAttributes.Color = daColor;
   newStroke.DrawingAttributes.OutlineColor = daOutlineColor;

   newStroke.StylusPoints.AddStylusPoints(args.GetStylusPoints(inkPresenter));
   inkPresenter.Strokes.Add(newStroke);
}

// Add the new points to the Stroke we're working with
function InkPresenterMouseMove(sender,args)
{
   if (newStroke != null)
   {
      newStroke.StylusPoints.AddStylusPoints(args.GetStylusPoints(inkPresenter));
   }
}

// Release the mouse
function InkPresenterMouseUp(sender,args)
{
   newStroke = null;
   inkPresenter.ReleaseMouseCapture();
}

// Set the Drawing Attributes for a pen
function SelectPen(sender, args)
{
  daWidth = 1;
  daHeight = 1;
  daColor = "Black";
  daOutlineColor = "Black";
}

// Set the Drawing Attributes for a marker
function SelectMarker(sender, args)
{
  daWidth = 10;
  daHeight = 4;
  daColor = "Blue";
  daOutlineColor = "Blue";
}

// Set the Drawing Attributes for a highlighter
function SelectHighlighter(sender, args)
{
  daWidth = 25;
  daHeight = 5;
  daColor = "Yellow";
  daOutlineColor = "Yellow";
}

// Erase all strokes from the canvas
function EraseCanvas(sender, args)
{
  inkPresenter.Strokes.Clear();
}

Applies To

InkPresenter

See Also


StrokeStartLineCap Property

Gets or sets a PenLineCap enumeration value that describes the Shape at the start of a Stroke.

XAML
<object StrokeStartLineCap="PenLineCap" .../>
Scripting
value = object.strokeStartLineCap
object.strokeStartLineCap = value

Property Value

PenLineCap

One of the PenLineCap enumeration values.

This property is read/write. The default value is Flat.

Remarks

This property has no effect if you set it on a shape that has no Stroke or that has no start or end points. For example, this property has no effect if you set it on an Ellipse.

Applies To

Ellipse, Line, Path, Polygon, Polyline, Rectangle, Shape

See Also


StrokeThickness Property

Gets or sets the width of the Shape outline.

XAML
<object StrokeThickness="Double" .../>
Scripting
value = object.strokeThickness
object.strokeThickness = value

Property Value

Double

The width of the Shape outline.

This property is read/write. The default value is 0.

Remarks

Applies To

Ellipse, Line, Path, Polygon, Polyline, Rectangle, Shape

See Also


StyleSimulations Property

Not implemented.

XAML
<object StyleSimulations="StyleSimulations" .../>
Scripting
value = object.StyleSimulations
object.StyleSimulations = value

Property Value

StyleSimulations

This property is read/write.

Remarks

Silverlight 1.0 does not implement this property; the value is always None.

Applies To

Glyphs

See Also

Text and Fonts Overview, TextBlock,


StylusPoints Property

Gets or sets the collection of StylusPoint objects that make up the Stroke.

XAML
<object ...>
  <object.StylusPoints>
    oneOrMoreStylusPoints
  <object.StylusPoints/>
<object/>
Scripting
value = object.StylusPoints
object.StylusPoints = value

Property Value

StylusPointCollection

The collection of StylusPoint objects that make up the Stroke.

This property is read/write.

Remarks

Setting StylusPoints in XAML is not a typical scenario (usually you use this property to capture user input rather than prepopulating strokes) but it is possible. You could use this technique to place watermarks or guides on the ink canvas as actual strokes.

The XAML syntax for properties that use a StylusPointCollection is an example of an implicit collection syntax, where you can omit the StylusPointCollection object element. The <DoubleAnimationUsingKeyFrames.Strokes> property element is required for this collection syntax; StylusPoints is not the default collection property of a Stroke. You would include one or more StylusPoint object elements as child elements of the <DoubleAnimationUsingKeyFrames.Strokes> property element. For more information about XAML implicit collection syntax, see XAML Syntax Overview. (Explicitly including a StylusPointCollection object element is permissible XAML syntax, and might be useful if you intend to name the collection in XAML and manipulate its contents through script later.)

Examples

JavaScript
var agCtrl;
var inkPresenter; // Corresponds to InkPresenter element in xaml
var newStroke = null; // The Stroke variable we'll use here in mouse handlers
var daWidth;
var daHeight;

function root_Loaded(sender, args)
{
    // Get the html object which contains the Silverlight plug-in
    agCtrl = sender.GetHost();
    inkPresenter = sender.findname("inkPresenterElement");
}

// Capture mouse movement when the left button is pressed then create the stroke.
function InkPresenterMouseDown(sender,args)
{
   inkPresenter.CaptureMouse();
   newStroke = agCtrl.content.createFromXaml('<Stroke/>');

   // Get the DeviceType
   if(args.GetStylusInfo().deviceType == "Stylus")
   {
     var sps = args.GetStylusPoints(inkPresenter);
     SetStylusStrokeSize(sps);
   }
   // If the device type is not a stylus then use the default stroke height and width.
   else
   {
     daWidth = 3;
     daHeight = 3;
   }

   // Set the drawing attributes properties
   newStroke.DrawingAttributes.Width = daWidth;
   newStroke.DrawingAttributes.Height = daHeight;
   newStroke.DrawingAttributes.Color = "Blue";
   newStroke.DrawingAttributes.OutlineColor = "Orange";

   newStroke.StylusPoints.AddStylusPoints(args.GetStylusPoints(inkPresenter));
   inkPresenter.Strokes.Add(newStroke);
}

// Add the new points to the Stroke we're working with
function InkPresenterMouseMove(sender,args)
{
   if (newStroke != null)
   {
      newStroke.StylusPoints.AddStylusPoints(args.GetStylusPoints(inkPresenter));
   }
}

// Release the mouse
function InkPresenterMouseUp(sender,args)
{
   newStroke = null;
}

// Set the size of the stroke based on the initial pressureFactor of the stroke.
function SetStylusStrokeSize(sps)
{
    var p;
    // Set variable p to the first StylusPoint in the Stroke
    p = sps.getItem(0).pressureFactor;
    daWidth = p * 20.0;
    daHeight = p * 20.0;
}

Applies To

Stroke

See Also

StylusPointCollection, DrawingAttributes, Ink Support In Microsoft Silverlight,


SweepDirection Property

Gets or sets a value that specifies whether the arc is drawn in the Clockwise or Counterclockwise direction.

XAML
<object SweepDirection="SweepDirection" .../>
Scripting
value = object.SweepDirection
object.SweepDirection = value

Property Value

SweepDirection

A value that specifies the direction in which the arc is drawn.

This property is read/write. The default value is Counterclockwise.

Remarks

For an ArcSegment with a given Size, RotationAngle, start point, and end Point, four different arcs are possible. Specifying the IsLargeArc property reduces the number of possible arcs to two: an arc drawn from the start point to the end Point in a Clockwise direction and an arc drawn from the start point to the end point in a Counterclockwise direction.

The following illustration shows two elliptical arcs that are identical except for their SweepDirection settings.

ArcSegments with different SweepDirection settings

Applies To

ArcSegment

See Also

Path Markup Syntax


Tag Property

Silverlight SDK

Tag Property (UIElement)

Gets or sets an object that can be used for user storage or information passing.

XAML
<object Tag="objectvalue" .../>
Scripting
value = object.tag
object.tag = value

Property Value

string

An arbitrary user-determined string.

This property is read/write. The default value is null.

This property has a similar purpose to "Tag" in other programming models; it provides a property that can be used to pass information between objects, or can provide a means of customization or differentiation between defined object types.

Applies To

Canvas, Ellipse, Glyphs, Image, InkPresenter, Line, MediaElement, Path, Polygon, Polyline, Rectangle, TextBlock

See Also


Storyboard.TargetName Property

Gets or sets the name of the object to animate.

XAML
<object Storyboard.TargetName="string" .../>
Scripting
value = object["Storyboard.TargetName"]
object["Storyboard.TargetName"] = value

Property Value

string

The name of the object to animate.

This property is read/write. The default value is null.

Remarks

This property is an example of an attached property, whereby non-Storyboard objects can set this Storyboard-specific property.

Notice particularly the script syntax, which resembles an indexer or array syntax. The ["ownerType.propertyName"] form (with no dot separating this property form and the target object for getting or setting) is necessary to get or set an attached property such as Storyboard.TargetName in script.

The value of Storyboard.TargetName must refer to an existing element that has that same string assigned as its Name or x:Name attribute. For details, see the "Part 2: Create a Storyboard" section of Animation Overview.

Attempting to set Storyboard.TargetName on a running animation will raise a runtime SetValue method error. You can however use script to retarget existing animations that are not yet running. If you do so, be cautious because if you retarget an animation to the wrong type of target (one that does not possess the existing Storyboard.TargetProperty) you will get a runtime error.

Applies To

ColorAnimation, ColorAnimationUsingKeyFrames, DoubleAnimation, DoubleAnimationUsingKeyFrames, PointAnimation, PointAnimationUsingKeyFrames, Storyboard

See Also

Animation Overview


Storyboard.TargetProperty Property

Gets or sets the property that should be animated.

XAML
<object Storyboard.TargetProperty="string" .../>
Scripting
value = object["Storyboard.TargetProperty"]
object["Storyboard.TargetProperty"] = value

Property Value

string

The name of the property to animate.

This property is read/write. The default value is null.

Remarks

This property is an example of an attached property, whereby non-Storyboard objects can set this Storyboard-specific property.

Notice particularly the script syntax, which resembles an indexer or array syntax. The ["propertyName"] form (with no dot separating it and the target object) is necessary to get or set an attached property such as Storyboard.TargetProperty in script.

The value of Storyboard.TargetProperty must refer to an existing property of the element referenced by Storyboard.TargetName. For details, see the "Part 2: Create a Storyboard" section of Animation Overview.

Storyboard.TargetProperty supports a concept of indirect property targeting. Indirect property targeting is necessary when the type of the property being animated is itself an object, but the actual animated value is a subproperty of that object rather than the object type itself. This is particularly necessary if there was no means in markup to provide a name for targeting the subobject, perhaps because it was specified originally in XAML attribute form rather than as a XAML object element. For example, to animate the Fill of a Rectangle using a linear interpolation of a SolidColorBrush, you would specify a ColorAnimation and give it a Storyboard.TargetProperty value of "(Rectangle.Fill).(SolidColorBrush.Color)".

Attempting to set Storyboard.TargetProperty on a running animation will raise a runtime SetValue method error. You can however use script to retarget existing animations that are not yet running. If you do so, be cautious because if you retarget an animation to a nonexistent property you will get a runtime error.

Applies To

ColorAnimation, ColorAnimationUsingKeyFrames, DoubleAnimation, DoubleAnimationUsingKeyFrames, PointAnimation, PointAnimationUsingKeyFrames, Storyboard

See Also

Animation Overview


Text Property (TextElement)

Gets or sets the text contents of the text element.

XAML
<object Text="string" .../>
-or-
<object>string<object>
Scripting
value = object.Text
object.Text = value

Property Value

string

A string specifying the text contents of this text element.

This property is read/write. The default value is an empty string.

Remarks

The TextBlock object is the primary text element for displaying text in Silverlight applications. A TextBlock can be thought of as having two simultaneous object models within it:

  • A representation as a Text property, which represents only string content (no formatting other than the formatting declared at the TextBlock level).
  • A representation as an Inlines collection. The collection contains primarily Run objects, each of which can declare its own formatting properties such as FontSize. The Text property still returns a value (the appended text of all Run elements in the Inlines) but does not capture any formatting applied to the Run elements. If created from XAML as inner text of a <TextBlock> tag, or by setting to Text property, the Inlines collection contains a single Run that contains that text.

You can choose to work with either object model. However, you should be aware that if you adjust the text by appending to the Text value, when the text is actually a series of text elements with individual formatting in an Inlines collection, you will flatten the previous Inlines collection content and replace it with a single new unformatted Run with your new text. This generally is not a desired behavior.

There are several interesting items to note about text display if certain properties are left unset:

  • The default value of the FontSize property of the rendered TextBlock is 14.666 pixels, which is exactly 11 points.
  • The default value of the FontFamily property of the rendered TextBlock is "Lucida Sans Unicode, Lucida Grande".
  • No font files on the hosting Web server, or residing in the same directory location as the XAML content, are required to enable the default font.

When setting text in a TextBlock, it is not necessary in XAML to explicitly specify the Text property; you can use the intuitive markup syntax of placing text within the TextBlock container as its content, or inner text:

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007">
  <TextBlock>Hello, world!</TextBlock>
</Canvas>

Note Any leading or trailing whitespace is not preserved when setting the Text property.

For more information on text and fonts, see Text and Fonts Overview.

Examples

The following XAML example shows how to define a TextBlock element and set its Text property to a character string:

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007">
  <TextBlock Text="Hello, world!" />
</Canvas>

The following image displays the result of the previous XAML content example:

Applies To

Run, TextBlock

See Also

Text and Fonts Overview, FontFamily, FontSize, FontStretch, FontStyle, FontWeight


Text Property (TimelineMarker)

Gets or sets the text value of this TimelineMarker.

XAML
<object  Text="string" .../>
Scripting
value = object.Text
object.Text = value

Property Value

string

The text value of this TimelineMarker.

This property is read/write. The default value is an empty string.

Remarks

When this TimelineMarker represents a Windows Media marker, this property contains the value of its "Name" field. When this TimelineMarker represents a script command, this property contains the value of its "Param" field.

The XAML syntax for TimelineMarker is mainly only relevant for a CreateFromXaml scenario. Populating the initial .Markers collection in XAML is permitted by the parser but has no effect because the .Markers collection is specific to a media source rather than to a MediaElement. For details, see TimelineMarker.

Applies To

TimelineMarker

See Also

Media Overview, MediaElement


TextDecorations Property

Gets or sets the text decoration for the content in this element.

XAML
<object TextDecorations="TextDecorations" .../>
Scripting
value = object.TextDecorations
object.TextDecorations = value

Property Value

TextDecorations

A value of teh TextDecorations enumeration that specifies the desired text decoration.

This property is read/write. The default value is None.

Remarks

By using the TextDecorations property, you can create the visual appearance of a hyperlink in a Run or TextBlock object.

Simulating a Hyperlink using the TextDecorations Property

Examples

The following XAML example shows how to define a TextBlock that simulates a hyperlink by displaying an underline in response to the MouseEnter event. The underline is removed in response to the MouseLeave event. Notice that the Cursor property is set to display the Hand cursor when the mouse pointer is over the TextBlock.

XAML
<TextBlock
  Text="Click to Win!"
  TextDecorations="None"
  Cursor="Hand"
  FontSize="14" FontWeight="Bold"
  MouseEnter="onMouseEnter"
  MouseLeave="onMouseLeave"
  MouseLeftButtonUp="onMouseLeftButtonUp" />

The following JavaScript example shows the corresponding event handling functions for the TextBlock defined in the previous XAML example:

JavaScript
function onMouseEnter(sender, mouseEventArgs)
{
    sender.textDecorations = "Underline";
    sender.foreground="Maroon";
}

function onMouseLeave(sender, mouseEventArgs)
{
    sender.textDecorations = "None";
    sender.foreground="Black";
}

function onMouseLeftButtonUp(sender, mouseEventArgs)
{
    alert("Congratulations!");
}

Applies To

Run, TextBlock

See Also

Text and Fonts Overview, FontFamily, FontSize, FontStretch, FontStyle, FontWeight


TextWrapping Property

Gets or sets a value that indicates how the TextBlock should wrap text.

XAML
<object TextWrapping="TextWrapping" .../>
Scripting
value = object.TextWrapping
object.TextWrapping = value

Property Value

TextWrapping

A value of the enumeration that indicates how the TextBlock should wrap text.

This property is read/write. The default value is NoWrap.

Remarks

The TextWrapping property indicates how text should wrap in a TextBlock. The TextWrapping enumeration defines two values: NoWrap, and Wrap.

ActualHeight and ActualWidth are read-only properties that report the rendered height and width of the TextBlock; these properties can be different than the Height and Width properties of the TextBlock. Setting the TextWrapping property affects the ActualHeight and ActualWidth values of the TextBlock. The following diagram shows how the TextWrapping property affects ActualHeight and ActualWidth.

How TextWrapping affects ActualWidth and ActualHeight

Examples

The following XAML example shows how to set the TextWrapping property to NoWrap and Wrap:

XAML
<!-- TextBlock with no text wrapping -->
<TextBlock
  Text="The quick red fox jumped over the lazy brown dog."
  Width="200"
  TextWrapping="NoWrap" />

<!-- TextBlock with text wrapping -->
<TextBlock
  Canvas.Top="40"
  Text="The quick red fox jumped over the lazy brown dog."
  Width="200"
  TextWrapping="Wrap" />

The following image shows the rendered text from the previous XAML example:

TextBlock rendering non-wrapped and wrapped text

Applies To

TextBlock

See Also

Text and Fonts Overview, ActualHeight, ActualWidth


Time Property

Gets or sets the time at which this TimelineMarker is reached.

XAML
<object Time="TimeSpan" .../>
Scripting
value = object.Time
object.Time = value

Property Value

TimeSpan

The time at which this TimelineMarker is reached.

This property is read/write. The default value is null.

Remarks

The string format for specifying a TimeSpan is [days.]hours:minutes:seconds[.fractionalSeconds]. See TimeSpan.

The XAML syntax for TimelineMarker is mainly only relevant for a CreateFromXaml scenario. Populating the initial .Markers collection in XAML is permitted by the parser but has no effect because the .Markers collection is specific to a media source rather than to a MediaElement. For details, see TimelineMarker.

Applies To

TimelineMarker

See Also

Media Overview, MediaElement


Title Property

Silverlight SDK

Title Property (Accessibility)

Gets or sets a string identifier for the Silverlight plug-in instance, which is reported to accessibility clients.

XAML
Cannot be used in XAML.
Scripting
value = object.Title
object.Title = value

Property Value

string

A string that provides a human-readable identifier for the Silverlight plug-in instance and its content.

This property is read-write. The default value is the string "Silverlight Content".

Remarks

The Title should be intuitive so that content viewers understand the Silverlight plug-in instance's meaning or purpose in the context of an HTML page. The string could be as simple as "Silverlight Content" (the default), but might instead summarize the specific visual content that a particular Silverlight plug-in instance is hosting. The Title is reported to accessibility clients with the expectation that it is presented to content viewers, and it is not intended to be merely a programmatic identifier.

Applies To

Accessibility

See Also


To Property (ColorAnimation)

Gets or sets the animation's ending value.

XAML
<object To="Color" .../>
Scripting
value = object.To
object.To = value

Property Value

Color

The ending value of the animation.

This property is read/write. The default value is null.

Remarks

See Color for details on the various string formats that can be used to specify a color either in XAML or script.

The following table summarizes how the From, To, and By properties may be used together or separately to determine an animation's target values.

Properties Specified | Resulting Behavior
From | The animation progresses from the value specified by the From property to the base value of the property being animated.
From and To | The animation progresses from the value specified by the From property to the value specified by the To property.
From and By | The animation progresses from the value specified by the From property to the value specified by the sum of the From and By properties.
To | The animation progresses from the animated property's base value or a previous animation's output value to the value specified by the To property.
By | The animation progresses from the base value of the property being animated or a previous animation's output value to the sum of that value and the value specified by the By property.

Note If you set both the To and By properties, the To property takes precedence and the By property is ignored.

To use other interpolation methods or animate between more than two target values, use a ColorAnimationUsingKeyFrames object.

Applies To

ColorAnimation, ColorAnimationUsingKeyFrames

See Also

Animation Overview


To Property (DoubleAnimation)

Gets or sets the animation's ending value.

XAML
<object To="Double" .../>
Scripting
value = object.To
object.To = value

Property Value

Double

The ending value of the animation.

This property is read/write. The default value is null.

Remarks

The following table summarizes how the From, To, and By properties may be used together or separately to determine an animation's target values.

Properties specified | Resulting behavior
From | The animation progresses from the value specified by the From property to the base value of the property being animated.
From and To | The animation progresses from the value specified by the From property to the value specified by the To property.
From and By | The animation progresses from the value specified by the From property to the value specified by the sum of the From and By properties.
To | The animation progresses from the animated property's base value or a previous animation's output value to the value specified by the To property.
By | The animation progresses from the base value of the property being animated or a previous animation's output value to the sum of that value and the value specified by the By property.

Note If you set both the To and By properties, the To property takes precedence and the By property is ignored.

To use other interpolation methods or animate between more than two target values, use a DoubleAnimationUsingKeyFrames object.

Applies To

DoubleAnimation, DoubleAnimationUsingKeyFrames

See Also

Animation Overview


To Property (PointAnimation)

Gets or sets the animation's ending value.

XAML
<object To="Point" .../>
Scripting
value = object.To
object.To = value

Property Value

Point

The ending value of the animation.

This property is read/write. The default value is null.

Remarks

The Point structure parallels a convention that is supported by a type converter, such that properties that take a Point as their value can specify a Point as a formatted string. The type converter generates a new Point value based on processing the string. The type converter functions both for XAML usages and script usages. In both cases, you supply a quoted string. The format of that string is an X,Y value pair. Alternatively, you can use a space rather than a comma as the delimiter betweeen X and Y in the string.

See remarks in Point for details on scripting usages. The properties of PointAnimation are one of the cases where the object model provides access to an actual Point as a return value if you get this property at runtime. This means that you can potentially use the X and Y properties of the returned Point to adjust the animation either before it runs or while it runs.

The following table summarizes how the From, To, and By properties may be used together or separately to determine an animation's target values.

Properties Specified | Resulting Behavior
From | The animation progresses from the value specified by the From property to the base value of the property being animated.
From and To | The animation progresses from the value specified by the From property to the value specified by the To property.
From and By | The animation progresses from the value specified by the From property to the value specified by the sum of the From and By properties.
To | The animation progresses from the animated property's base value or a previous animation's output value to the value specified by the To property.
By | The animation progresses from the base value of the property being animated or a previous animation's output value to the sum of that value and the value specified by the By property.

Note If you set both the To and By properties, the To property takes precedence and the By property is ignored.

To use other interpolation methods or animate between more than two target values, use a PointAnimationUsingKeyFrames object.

Applies To

PointAnimation, PointAnimationUsingKeyFrames

See Also

Animation Overview, PointAnimation


Transform Property (Brush)

Gets or sets the transformation that is applied to the brush. This transformation is applied after the brush's output has been mapped and positioned.

XAML
<object Transform="Transform" .../>
Scripting
value = object.Transform
object.Transform = value

Property Value

Transform

The transformation to apply to the brush.

This property is read/write. The default value is null.

Remarks

Use this property to rotate, scale, skew, or translate a brush's content.

Applies To

ImageBrush, LinearGradientBrush, RadialGradientBrush, SolidColorBrush, VideoBrush


Transform Property (Geometry)

Gets or sets the Transform object applied to a Geometry.

XAML
<object Transform="Transform" .../>
Scripting
value = object.Transform
object.Transform = value

Property Value

Transform

The transformation applied to the Geometry, provided as a value of type Transform: MatrixTransform, RotateTransform, ScaleTransform, SkewTransform, or TranslateTransform and you can use a TransformGroup to specify multiple transforms.

Remarks

Use this property to rotate, scale, skew, or translate the Geometry.

Applies To

EllipseGeometry, GeometryGroup, LineGeometry, PathGeometry, RectangleGeometry

See Also

Transform, Silverlight Transforms Overview


Triggers Property

Gets the collection of triggers established directly on this element, or in child elements.

XAML
<object .../>
TriggerCollection" .../>
Scripting
value = object.Triggers

Property Value

TriggerCollection

A collection of triggers.

This property is read-only. The default value is null.

Applies To

Canvas, Ellipse, Glyphs, Image, InkPresenter, Line, MediaElement, Path, Polygon, Polyline, Rectangle, TextBlock


Type Property

Gets or sets the type of this TimelineMarker.

XAML
<object Type="string" .../>
Scripting
value = object.Type
object.Type = value

Property Value

string

A string that describes the type of this TimelineMarker.

This property is read/write. The default value is an empty string.

Remarks

When this TimelineMarker represents a Windows Media marker, this property is set to "Name." When this TimelineMarker represents a script command, this property contains the value of its "Type" field.

The string format for specifying a TimeSpan is [days.]hours:minutes:seconds[.fractionalSeconds]. See TimeSpan.

The XAML syntax for TimelineMarker is mainly only relevant for a CreateFromXaml scenario. Populating the initial .Markers collection in XAML is permitted by the parser but has no effect because the .Markers collection is specific to a media source rather than to a MediaElement. For details, see TimelineMarker.

Applies To

TimelineMarker

See Also

Media Overview, MediaElement


UnicodeString Property

Gets or sets the string that represents the Unicode string for the Glyphs object.

XAML
<object UnicodeString="unicodeString" .../>
Scripting
value = object.UnicodeString
object.UnicodeString = value

Property Value

string

A string value that represents the Unicode string with XAML compatible encoding.

This property is read/write. The default value is an empty string.

Remarks

Glyphs does not have a content property (you do not define the glyphs by declaring text as the inner text of a Glyphs object element). Instead, you specify the individual glyphs through either UnicodeString or Indices. Of these, using UnicodeString is probably the most common, because it is the easiest to capture from the output of applications that are used to compose text. You can use UnicodeString to specify the basic glyph information and then can adjust values in Indices to refine the advance and offset spacings within the set of glyphs

Applies To

Glyphs

See Also

Text and Fonts Overview, TextBlock,


Uri Property

Gets the Uniform Resource Identifier (URI) of the download request.

XAML | Cannot be used in XAML.
Scripting | value = downloaderObject.Uri

Property Value

string

Gets a string value that corresponds to the URI of the Downloader object request.

This property is read-only. The default value is an empty string.

Remarks

When you invoke the Send method of the Downloader object, you specify a uri parameter that represents the data to be downloaded. The Uri property corresponds to the value of the uri parameter of the Send method. The Uri property enables you to differentiate downloaded content when you use the share DownloadProgressChanged or Completed event handler functions for multiple Downloader object requests.

Note The Uri value must reference a file that comes from the same site of origin as the instantiated Silverlight plug-in. Usually this is accomplished by specifying a relative URI.

Examples

The following JavaScript example shows how to use the Uri property in a Completed event handler function to determine what actions to take for the returned value of the GetResponseText method invocations. Since the downloaded content does not represent packaged content, the part parameter for GetResponseText must be set to an empty string. Notice that the Status property value is used to determine whether the content was successfully downloaded:

JavaScript
// Event handler for the Completed event.
function onCompleted(sender, eventArgs)
{
    // If HTTP status code indicates "OK", determine action based on URI property.
    if (sender.uri == "OK_button.js")
    {
        // Evaluate JavaScript code -- causes code to be memory-resident.
        eval(sender.ResponseText);
    }

    if (sender.uri == "OK_button.xaml")
    {
        // Retrieve downloaded XAML content.
        var xamlFragment = sender.ResponseText;

        // Create the objects from the XAML content.
        var plugin = sender.getHost();
        var button = plugin.content.createFromXaml(xamlFragment);

        // Add downloaded XAML content to the root Canvas of the plug-in.
        var rootCanvas = sender.findName("rootCanvas");
        rootCanvas.children.add(button);
    }
}

Applies To

Downloader

See Also

Completed, DownloadProgressChanged, Send, Status, Using a Downloader Object


Value Property (ColorKeyFrame)

Gets or sets the key frame's target value.

XAML
<object Value="Color" .../>
Scripting
value = object.Value
object.Value = value

Property Value

Color

The key frame's target value, which is the value of this key frame at its specified KeyTime.

This property is read/write. The default value is null.

Remarks

See Color for details on the various string formats that can be used to specify a color either in XAML or script.

Applies To

DiscreteColorKeyFrame, LinearColorKeyFrame, SplineColorKeyFrame

See Also

Animation Overview


Value Property (DoubleKeyFrame)

Gets or sets the key frame's target value.

XAML
<object Value="Double" .../>
Scripting
value = object.Value
object.Value = value

Property Value

Double

The key frame's target value, which is the value of this key frame at its specified KeyTime.

This property is read/write. The default value is 0.

Remarks

Applies To

DoubleKeyFrame, LinearDoubleKeyFrame, SplineDoubleKeyFrame

See Also

Animation Overview


Value Property (MediaAttribute)

Gets the value of the MediaAttribute.

XAML
Cannot be used in XAML. See ASX documentation for markup information.
Scripting
value = object.Value
object.Value = value

Property Value

string

The value of the MediaAttribute.

This property is read-only.

Remarks

The Name of a MediaAttribute is the name of the xml element in the ASX file that the MediaAttribute corresponds to. The Value of the MediaAttribute is the text value of the xml element. For example, if the ASX tag that the MediaAttribute corresponds to is:

<Title>Clip1</Title>

the Name of the MediaAttribute is "Title" and the Value is "Clip1".

Examples

The following JavaScript example shows how to retrieve the Attributes property of a MediaElement that has a Source property set to an ASX playlist file. The retrieved MediaAttributeCollection is iterated through and the Name and Value properties of each MediaAttribute is displayed.

JavaScript
    // Get the MediaElement name MediaPlayer.
    player = sender.findName("MediaPlayer");

    // The display message.
    var msg;
    msg =  "MediaElement Source: " + player.source + "\n\n";
    msg += "Attributes: \n";

    // Variable to hold the MediaAttribute.
    var attribute;

    // Iterate through the collection of MediaAttributes.
    var loop = 0;
    while(loop < player.Attributes.count)
    {
        // Get the current Attribute.
        attribute = player.Attributes.getItem(loop);

        msg += "Name: "  + attribute.Name + "\n";
        msg += "Value: " + attribute.Value + " \n\n";
        loop++;
    }

    // Display the MediaAttribute information.
    alert(msg);
}

Applies To

MediaAttribute

See Also

MediaElement, MediaAttributeCollection, Attributes


Value Property (PointKeyFrame)

Gets or sets the key frame's target value.

XAML
<object Value="Point" .../>
Scripting
value = object.Value
object.Value = value

Property Value

Point

The key frame's target value, which is the value of this key frame at its specified KeyTime.

This property is read/write. The default value is 0,0.

Remarks

The Point structure parallels a convention that is supported by a type converter, such that properties that take a Point as their value can specify a Point as a formatted string. The type converter generates a new Point value based on processing the string. The type converter functions both for XAML usages and script usages. In both cases, you supply a quoted string. The format of that string is an X,Y value pair. Alternatively, you can use a space rather than a comma as the delimiter betweeen X and Y in the string.

See remarks in Point for details on scripting usages. The Value property of PointAnimationUsingKeyFrames is one of the cases where the object model provides access to an actual Point as a return value if you get this property at runtime. This means that you can potentially use the X and Y properties of the returned Point to adjust the animation either before it runs or while it runs.

Applies To

DiscretePointKeyFrame, LinearPointKeyFrame, SplinePointKeyFrame

See Also

Animation Overview


Visibility Property

Gets or sets the user interface (UI) visibility of this element.

XAML
<object Visibility="Visibility" .../>
Scripting
value = object.Visibility
object.Visibility = value

Property Value

Visibility

A value of the Visibility enumeration.

This property is read/write. The default value is Visible.

Remarks

Elements where Visibility is not Visible do not participate in input events (or commands), are not in a tab sequence, and are excluded during hit testing.

Note The value of IsHitTestVisible is ignored when an object is not set to Visible. IsHitTestVisible is a settable property that enables you to disable hit testing for elements that would otherwise be hit testable by virtue of the Visibility and Background property values.

Examples

The following XAML example shows how to set the Visibility property of a TextBlock to Visible:

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  Background="Wheat">
  <TextBlock
    Text="Click me!"
    Visibility="Visible"
    Canvas.Left="20"
    FontSize="24"
    MouseLeftButtonUp="onMouseLeftButtonUp" />
</Canvas>

The following JavaScript example shows how to set the Visibility property of the TextBlock to Hidden:

JavaScript
function onMouseLeftButtonUp(sender, mouseEventArgs)
{
    // TextBlock collapsed
    sender.visibility = "Collapsed";
    // The IsHitTestVisible property is ignored during hit testing,
    // it is still set to true for an element whose Visibility is Collapsed, has null or Transparent Brush, or Opacity=0.
    alert(sender.isHitTestVisible);
}

Applies To

Canvas, Ellipse, Glyphs, Image, InkPresenter, Line, MediaElement, Path, Polygon, Polyline, Rectangle, TextBlock

See Also

IsHitTestVisible


Volume Property

Gets or sets the media's volume.

XAML
<object Volume="Double" .../>
Scripting
value = object.Volume
object.Volume = value

Property Value

Double

The media's volume represented on a linear scale between 0 and 1.

This property is read/write. The default value is 0.5.

Remarks

Volume can be difficult to quantitate because each media file has a different baseline for its recorded or perceived audio level.

Applies To

MediaElement

See Also

Media Overview, Supported Media Formats and Protocols


Width Property (DrawingAttributes)

Gets or sets the width of the associated stroke.

XAML
<DrawingAttributes Width="Double" .../>
Scripting
value = object.Width
object.Width = value

Property Value

Double

The width of the associated stroke.

This property is read/write. The default value is 3.0.

Examples

The following Javascript example simulates 3 different pen types (pen, marker and highlighter) by setting the Color, Height, OutlineColor and Width DrawingAttributes properties . First a DrawingAttributes object is created, then it is appended to the Stroke object. The DrawingAttributes properties are then set by one of the three events that simulate a pen type. The EraseCanvas event clears all the Strokes from the Canvas.

JavaScript
var agCtrl;
var inkPresenter; // Corresponds to InkPresenter element in xaml
var newStroke = null; // The Stroke variable we'll use here in mouse handlers
// DrawingAttributes variables
var daWidth = 2;
var daHeight = 2;
var daColor = "Black";
var daOutlineColor = "Black";

function root_Loaded(sender, args)
{
    // Get the html object which contains the Silverlight plug-in
    agCtrl = sender.GetHost();
    inkPresenter = sender.findname("inkPresenterElement");
}

// Capture mouse movement when the left button is pressed and create the stroke
function InkPresenterMouseDown(sender,args)
{
   inkPresenter.CaptureMouse();

   newStroke = agCtrl.content.createFromXaml('<Stroke/>');

   var da = agCtrl.content.CreateFromXaml('<DrawingAttributes/>');
   newStroke.DrawingAttributes = da;

   // Set the drawing attributes properties
   newStroke.DrawingAttributes.Width = daWidth;
   newStroke.DrawingAttributes.Height = daHeight;
   newStroke.DrawingAttributes.Color = daColor;
   newStroke.DrawingAttributes.OutlineColor = daOutlineColor;

   newStroke.StylusPoints.AddStylusPoints(args.GetStylusPoints(inkPresenter));
   inkPresenter.Strokes.Add(newStroke);
}

// Add the new points to the Stroke we're working with
function InkPresenterMouseMove(sender,args)
{
   if (newStroke != null)
   {
      newStroke.StylusPoints.AddStylusPoints(args.GetStylusPoints(inkPresenter));
   }
}

// Release the mouse
function InkPresenterMouseUp(sender,args)
{
   newStroke = null;
   inkPresenter.ReleaseMouseCapture();
}

// Set the Drawing Attributes for a pen
function SelectPen(sender, args)
{
  daWidth = 1;
  daHeight = 1;
  daColor = "Black";
  daOutlineColor = "Black";
}

// Set the Drawing Attributes for a marker
function SelectMarker(sender, args)
{
  daWidth = 10;
  daHeight = 4;
  daColor = "Blue";
  daOutlineColor = "Blue";
}

// Set the Drawing Attributes for a highlighter
function SelectHighlighter(sender, args)
{
  daWidth = 25;
  daHeight = 5;
  daColor = "Yellow";
  daOutlineColor = "Yellow";
}

// Erase all strokes from the canvas
function EraseCanvas(sender, args)
{
  inkPresenter.Strokes.Clear();
}

The XAML sample below creates the canvas and 4 buttons that are used to select the different pen types and the erase all feature that is simulated by the Javascript events above.

XAML
<Canvas xmlns="http://schemas.microsoft.com/client/2007"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Loaded="root_Loaded"
        x:Name="root"
        Width="600" Height="400">
  <InkPresenter
         x:Name="inkPresenterElement"
        Background="transparent"
        Width="600" Height="400"
        MouseLeftButtonDown="InkPresenterMouseDown"
        MouseMove="InkPresenterMouseMove"
        MouseLeftButtonUp="InkPresenterMouseUp"/>

<!-- Pen Button -->
    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="40"
      Stroke="Gray" Fill="Black" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>
    <TextBlock
      Height="21" Width="78"
      Canvas.Top="380" Canvas.Left="71"
      Foreground="Gray"
      FontFamily="Verdana" FontSize="12">Select Pen</TextBlock>

    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="40"
      x:Name="selectPen" MouseLeftButtonDown="SelectPen"
      Stroke="Transparent" Fill="Transparent" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>

<!-- Marker Button -->
    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="170"
      Stroke="Gray" Fill="Black" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>

    <TextBlock
      Height="21" Width="78"
      Canvas.Top="380" Canvas.Left="191"
      Foreground="Gray"
      FontFamily="Verdana" FontSize="12">Select Marker</TextBlock>

    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="170"
      x:Name="selectMarker" MouseLeftButtonDown="SelectMarker"
      Stroke="Transparent" Fill="Transparent" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>

<!-- Highlighter Button -->
    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="300"
      Stroke="Gray" Fill="Black" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>

    <TextBlock
      Height="21" Width="78"
      Canvas.Top="380" Canvas.Left="310"
      Foreground="Gray"
      FontFamily="Verdana" FontSize="12">Select Highlighter</TextBlock>

    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="300"
      x:Name="selectHighlighter" MouseLeftButtonDown="SelectHighlighter"
      Stroke="Transparent" Fill="Transparent" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>

<!-- Erase Canvas Button -->
    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="430"
      Stroke="Gray" Fill="Black" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>

    <TextBlock
      Height="21" Width="78"
      Canvas.Top="380" Canvas.Left="463"
      Foreground="Gray"
      FontFamily="Verdana" FontSize="12">Erase All</TextBlock>

    <Rectangle
      Height="30" Width="125"
      Canvas.Top="375" Canvas.Left="430"
      x:Name="eraseCanvas" MouseLeftButtonDown="EraseCanvas"
      Stroke="Transparent" Fill="Transparent" StrokeThickness="1.5"
      RadiusX="2" RadiusY="2"
      Opacity="1.0"/>
</Canvas>

Applies To

DrawingAttributes

See Also

Stroke, Color, Height, OutlineColor, DrawingAttributes, DrawingAttributes (Stroke)


Width Property (Rect)

Gets or sets the X-coordinate value of this Rect.

XAML
See Remarks.
Scripting
value = object.Width
object.Width = value

Property Value

Double

The width value of this Rect structure.

This property is read/write. The default value is 0.

Remarks

Property values for a Rect and an object for Rect are not available for all cases where Rect is used as a property type. See Remarks for Rect.

The properties of a Rect do not have a XAML usage because there is no way to create a Rect in XAML as an object element. Instead, you always specify a Rect as a string that is either provided as a XAML attribute value or set to a property value in script. Each of these cases is supported by a type conversion behavior. If the particular property being set can return a Rect as an object to script, then the value as provided in the original string can be retrieved as the Width value of that Rect object.

Applies To

Rect

See Also

Ink Support In Microsoft Silverlight, Silverlight Geometries Overview, Rect


Width Property (UIElement)

Gets or sets the width of the object.

XAML
<object Width="Double" .../>
Scripting
value = object.Width
object.Width = value

Property Value

Double

The width of the object.

This property is read/write. The default value is 0.

Remarks

Many of the UIElement derived objects are also derived from Shape. Not all of the Shape classes typically use Height or Width to specify their appearance, and instead use specific properties that might define a set of points. In this case a Height or Width is calculated, but is not typically set directly. For details, see Shapes and Drawing in Silverlight Overview.

TextBlock is a container object that displays text within it. The size of that text can influence the size of the rendered TextBlock, so TextBlock supports two additional properties that expose that calculated size, ActualHeight and ActualWidth. For details, see Text and Fonts Overview.

Applies To

Canvas, Ellipse, Glyphs, Image, InkPresenter, Line, MediaElement, Path, Polygon, Polyline, Rectangle, TextBlock

See Also

Object Layout in Silverlight


Windowless Property

Determines whether the Silverlight plug-in (Windows version) displays as a window-less plug-in.

Scripting (Instantiation) | Silverlight.CreateObject(,,,{isWindowless:'value'}) -or- Silverlight.CreateObjectEx({properties:{isWindowless:'value'}})
Scripting (Runtime) | value = silverlightObject.settings.Windowless

Property Value

Boolean

Gets (or sets in initialization only) whether the Silverlight plug-in displays as a window-less or windowed plug-in.

This property is settable only as an initialization parameter, and is read-only for scripting thereafter. The default value is false.

Remarks

This property is available on the settings sub-object of a Silverlight plug-in instance.

For Windows, if the value is set to true as an initialization parameter and the Background property value specifies an alpha value, the window-less mode enables HTML overlay where the HTML on the page blends with the contents of the plug-in, including its background.

For Macintosh, this property has no effect either in initialization or at runtime. The window behavior for Macintosh is to always act as window-less.

Performance Tip Setting an alpha channel value for full or partial transparency has possible performance consequences, particularly on certain client environments. See Performance Tips.

Performance Tip Only set the Windowless property to true when necessary. It is expensive and it can cause tearing during animations. See Performance Tips.

The windowless initialization parameter specifies whether the plug-in displays as a window-less plug-in. Note that the CreateObject/CreateObjectEx functions use a slight name variation, and call this parameter isWindowless. For more information on how this parameter is set during plug-in initialization, see Using CreateSilverlight.js and Silverlight.js.

Examples

The following JavaScript example demonstrates instantiation in which the two Silverlight plug-ins are established through CreateSilverlight.js--the first one with the isWindowless initialization parameter set to false; the second, with isWindowless set to true:

JavaScript
isWindowless:'false',       // Display as windowed plug-in.
background:'#80008080',     // Background color of plug-in (alpha + RGB).

JavaScript
isWindowless:'true',       // Display as window-less plug-in.
background:'#80008080',    // Background color of plug-in (alpha + RGB).

Notice the displayed output of the preceding plug-in initializations. The background of the first Silverlight plug-in is opaque. The background of the second Silverlight plug-in is blended with the background image of the HTML page.

Windowless property set on two Silverlight plug-ins

The following screenshot shows a TextBlock displayed as a window-less plug-in on a Microsoft Virtual Earth mashup. The Background value of the plug-in is "#00000000", which is totally transparent. In addition, the Opacity of the TextBlock is set to 0.7, which allows the map underneath to partially show through the text.

TextBlock displayed as a window-less plug-in

Applies To

Silverlight Plug-in

See Also

Using a Silverlight Plug-in, Using CreateSilverlight.js and Silverlight.js, Background


X Property (Point)

Gets or sets the X-coordinate value of this Point.

XAML
See Remarks.
Scripting
value = object.X
object.X = value

Property Value

Double

The X-coordinate value of this Point structure.

This property is read/write. The default value is 0.

Remarks

Property values for a Point and an object for Point are not available for all cases where Point is used as a property type. See Remarks for Point.

The properties of a Point do not have a XAML usage because there is no way to create a Point in XAML as an object element. Instead, you always specify a Point as a string that is either provided as a XAML attribute value or set to a property value in script. Each of these cases is supported by a type conversion behavior.

Applies To

Point

See Also

PointAnimation, Silverlight Geometries Overview


X Property (Rect)

Gets or sets the X-coordinate value of this Rect.

XAML
See Remarks.
Scripting
value = object.x
object.x = value

Property Value

Double

The X-coordinate value of this Rect structure.

This property is read/write. The default value is 0.

Remarks

Property values for a Rect and an object for Rect are not available for all cases where Rect is used as a property type. See Remarks for Rect.

The properties of a Rect do not have a XAML usage because there is no way to create a Rect in XAML as an object element. Instead, you always specify a Rect as a string that is either provided as a XAML attribute value or set to a property value in script. Each of these cases is supported by a type conversion behavior. If the particular property being set can return a Rect as an object to script, then the value as provided in the original string can be retrieved as the X value of that Rect object.

Applies To

Rect

See Also

Ink Support In Microsoft Silverlight, Silverlight Geometries Overview, Rect


X Property (StylusPoint)

Gets or sets the X coordinate of the StylusPoint in pixels.

XAML
<StylusPoint X="Double" .../>
Scripting
value = object.X
object.X = value

Property Value

Double

The X coordinate of the StylusPoint in pixels.

This property is read/write. The default value is 0.

Remarks

Specifying a StylusPoint in initial XAML is possible, but uncommon.

Examples

In this example the x and y coordinates of each StylusPoint are sent to a text TextBlock as they are added to a stroke.

JavaScript
// Add the new points to the Stroke we're working with and display the StylusPoint coordinates.
function InkPresenterMouseMove(sender,args)
{
   if (newStroke != null)
   {
      newStroke.StylusPoints.AddStylusPoints(args.GetStylusPoints(inkPresenter));
      xCoord.Text = "" + args.GetStylusPoints(inkPresenter).GetItem(0).X;
      yCoord.Text = "" + args.GetStylusPoints(inkPresenter).GetItem(0).Y;
      pressureData.Text = "" + args.GetStylusPoints(inkPresenter).GetItem(0).PressureFactor;
   }
}

Applies To

StylusPoint

See Also

Ink Support In Microsoft Silverlight


X Property (TranslateTransform)

Gets or sets the distance to translate along the x-axis.

XAML
<object X="Double" .../>
Scripting
value = object.X
object.X = value

Property Value

Double

The distance to translate (move) an object along the x-axis.

This property is read/write. The default value is 0.

Remarks

Negative values move an object to the left; positive values move an object to the right.

The local 0,0 for an object can be offset on a Canvas using Canvas.Left and Canvas.Top, but this does not count as a transform; the object retains its own local 0,0 in this case for transform purposes. For details on this concept, see Object Layout in Silverlight.

Applies To

TranslateTransform

See Also

Silverlight Transforms Overview, Object Layout in Silverlight


X1 Property

Gets or sets the x-coordinate of the Line start point.

XAML
<object X1="Double" .../>
Scripting
value = object.X1
object.X1 = value

Property Value

Double

The x-coordinate for the start point of the line.

This property is read/write. The default value is 0.

Applies To

Line

See Also

Shapes and Drawing in Silverlight Overview


X2 Property

Gets or sets the x-coordinate of the Line end point.

XAML
<object X2="Double" .../>
Scripting
value = object.X2
object.X2 = value

Property Value

Double

The x-coordinate for the end point of the line.

This property is read/write. The default value is 0.

Applies To

Line

See Also

Shapes and Drawing in Silverlight Overview


XamlFile Property

Silverlight SDK

XamlFileProperty

Gets the name of the Xaml file that the parser error occurred in.

XAML | Cannot be used in XAML.
Scripting | value = eventargs.XamlFile

Property Value

string

The name of the Xaml file that the parser error occurred in.

This property is read/write.

Remarks

Because you cannot raise your own errors in the Silverlight 1.0 eventing model, the settable aspect of this property does not have a practical usage. Usually, you will only use this property to get its value.

Examples

The following JavaScript example shows the portion of an event handler that displays error information specific to parser errors.

JavaScript
    // errorArgs is an instance of ParserErrorEventArgs
    if(errorArgs.ErrorType == "ParserError")
    {
      var parserErrorMsg = "Silverlight Parser Error  \n\n";

      // Basic error event informaiton.
      parserErrorMsg += "Error Type:    " + errorArgs.errorType     + "\n";
      parserErrorMsg += "Error Message: " + errorArgs.errorMessage  + "\n";
      parserErrorMsg += "Error Code:    " + errorArgs.errorCode  + "\n";

      //Parser specific error event information.
      parserErrorMsg += "XamlFile:      " + errorArgs.xamlFile      + "\n";
      parserErrorMsg += "XmlElement:    " + errorArgs.xmlElement    + "\n";
      parserErrorMsg += "XmlAttribute:  " + errorArgs.xmlAttribute  + "\n";
      parserErrorMsg += "Line:          " + errorArgs.lineNumber    + "\n";
      parserErrorMsg += "Position:      " + errorArgs.charPosition  + "\n";

      // Display the error message.
      alert(parserErrorMsg);
    }

Applies To

ParserErrorEventArgs

See Also

Silverlight Application Scripting Error Handling, ErrorEventArgs, RuntimeErrorEventArgs


XmlAttribute Property

Gets the xml attribute that the parser error occurred in.

XAML | Cannot be used in XAML.
Scripting | value = eventargs.XmlAttribute

Property Value

string

The xml attribute that the parser occurred in.

This property is read-only.

Remarks

Note The current implementation of Silverlight returns an empty string for the XmlAttribute value.

Applies To

ParserErrorEventArgs

See Also

Silverlight Application Scripting Error Handling, ErrorEventArgs, RuntimeErrorEventArgs


XmlElement Property

Gets the xml element that the parser error occurred in.

XAML | Cannot be used in XAML.
Scripting | value = eventargs.XmlElement

Property Value

string

The xml element that the parser error occurred in.

This property is read-only.

Remarks

Note The current implementation of Silverlight returns an empty string for the XmlElement value.

Applies To

ParserErrorEventArgs

See Also

Silverlight Application Scripting Error Handling, ErrorEventArgs, RuntimeErrorEventArgs


Y Property (Point)

Gets or sets the Y-coordinate value of this Point.

XAML
See Remarks.
Scripting
value = object.Y
object.Y = value

Property Value

Double

The Y-coordinate value of this Point structure.

This property is read/write. The default value is 0.

Remarks

Property values for a Point and an object for Point are not available for all cases where Point is used as a property type. See Remarks for Point.

The properties of a Point do not have a XAML usage because there is no way to create a Point in XAML as an object element. Instead, you always specify a Point as a string that is either provided as a XAML attribute value or set to a property value in script. Each of these cases is supported by a type conversion behavior.

Applies To

Point

See Also

PointAnimation, Silverlight Geometries Overview


Y Property (Rect)

Gets or sets the Y-coordinate value of this Rect.

XAML
See Remarks.
Scripting
value = object.y
object.y = value

Property Value

Double

The Y-coordinate value of this Rect structure.

This property is read/write. The default value is 0.

Remarks

Property values for a Rect and an object for Rect are not available for all cases where Rect is used as a property type. See Remarks for Rect.

The properties of a Rect do not have a XAML usage because there is no way to create a Rect in XAML as an object element. Instead, you always specify a Rect as a string that is either provided as a XAML attribute value or set to a property value in script. Each of these cases is supported by a type conversion behavior. If the particular property being set can return a Rect as an object to script, then the value as provided in the original string can be retrieved as the Y value of that Rect object.

Applies To

Rect

See Also

Ink Support In Microsoft Silverlight, Silverlight Geometries Overview, Rect


Y Property (StylusPoint)

Gets or sets the Y coordinate of the StylusPoint in pixels.

XAML
<StylusPoint Y="Double" .../>
Scripting
value = object.Y
object.Y = value

Property Value

Double

The Y coordinate of the StylusPoint in pixels.

This property is read/write. The default value is 0.

Remarks

Specifying a StylusPoint in initial XAML is possible, but uncommon.

Examples

In this example the x and y coordinates of each StylusPoint are sent to a text TextBlock as they are added to a stroke.

JavaScript
// Add the new points to the Stroke we're working with and display the StylusPoint coordinates.
function InkPresenterMouseMove(sender,args)
{
   if (newStroke != null)
   {
      newStroke.StylusPoints.AddStylusPoints(args.GetStylusPoints(inkPresenter));
      xCoord.Text = "" + args.GetStylusPoints(inkPresenter).GetItem(0).X;
      yCoord.Text = "" + args.GetStylusPoints(inkPresenter).GetItem(0).Y;
      pressureData.Text = "" + args.GetStylusPoints(inkPresenter).GetItem(0).PressureFactor;
   }
}

Applies To

StylusPoint

See Also

Ink Support In Microsoft Silverlight


Y Property (TranslateTransform)

Gets or sets the distance to translate (move) an object along the y-axis.

XAML
<object Y="Double" .../>
Scripting
value = object.Y
object.Y = value

Property Value

Double

The distance to translate (move) an object along the y-axis.

This property is read/write. The default value is 0.

Remarks

Negative values move an object up; positive values move an object down.

The local 0,0 for an object can be offset on a Canvas using Canvas.Left and Canvas.Top, but this does not count as a transform; the object retains its own local 0,0 in this case for transform purposes. For details on this concept, see Object Layout in Silverlight.

Applies To

TranslateTransform

See Also

Silverlight Transforms Overview, Object Layout in Silverlight


Y1 Property

Gets or sets the y-coordinate of the Line start point.

XAML
<object Y1="Double" .../>
Scripting
value = object.Y1
object.Y1 = value

Property Value

Double

The y-coordinate for the start point of the line.

This property is read/write. The default value is 0.

Applies To

Line

See Also

Shapes and Drawing in Silverlight Overview


Y2 Property

Gets or sets the y-coordinate of the Line end point.

XAML
<object Y2="Double" .../>
Scripting
value = object.Y2
object.Y2 = value

Property Value

Double

The y-coordinate for the end point of the line.

This property is read/write. The default value is 0.

Applies To

Line

See Also

Shapes and Drawing in Silverlight Overview


Silverlight Events

This section contains a list of the events exposed by the Silverlight Object Model.

Events

BufferingProgressChanged

Completed (Downloader)

Completed (Storyboard)

CurrentStateChanged

DownloadFailed

DownloadProgressChanged (Downloader)

DownloadProgressChanged (Image)

DownloadProgressChanged (ImageBrush)

DownloadProgressChanged (MediaElement)

GotFocus

ImageFailed (Image)

ImageFailed (ImageBrush)

KeyDown

KeyUp

Loaded

LostFocus

MarkerReached

MediaEnded

MediaFailed

MediaOpened

MouseEnter

MouseLeave

MouseLeftButtonDown

MouseLeftButtonUp

MouseMove

OnError

OnFullScreenChange

OnLoad

OnResize

PerformAction

See Also

Silverlight Events, Silverlight Mouse Support, Silverlight Keyboard Support


BufferingProgressChanged Event

Occurs when the BufferingProgress property changes.

XAML | <object BufferingProgressChanged="eventhandlerFunction" .../>
Scripting | [token = ]object.AddEventListener("BufferingProgressChanged", eventhandlerFunction)

AddEventListener Parameters

token | integer A token that is returned from the function, which you can optionally retain as a variable. If you intend to call RemoveEventListener to remove the handler, you will need this token.
eventhandlerFunction | object The name of your event handler function as it is defined in script. When used as an AddEventListener parameter, quotes around the function name are not required. See Remarks.

Event Handler Parameters

sender | object Identifies the object that invoked the event.
eventArgs | object This parameter is always set to null.

Remarks

You can also add handlers in script using a quoted string for the event handler name:

object.AddEventListener("BufferingProgressChanged", "eventhandlerFunction")
This syntax also returns a token; however, the token is not an absolute requirement for removing the handler, in cases where the handler was added by using a quoted string. For details, see RemoveEventListener.

The event will occur when the BufferingProgress changes by 0.05 or more and when it reaches 1.0.

Applies To

MediaElement

See Also

Silverlight Events, BufferingProgress


Completed Event

Occurs when a download request completes with content.

XAML | Cannot be used in XAML.
Scripting | [token = ]downloaderObject.AddEventListener("Completed", eventhandlerFunction)

AddEventListener Parameters

downloaderObject | object A particular Downloader object.
token | integer A token that is returned from the function, which you can optionally retain as a variable. If you intend to call RemoveEventListener to remove the handler, you will need this token.
eventhandlerFunction | object The name of your event handler function as it is defined in script. When used as an AddEventListener parameter, quotes around the function name are not required. See Remarks.

Event Handler Parameters

sender | object Identifies the object that invoked the event.
eventArgs | object This parameter is always set to null.

Event Information

The Completed event occurs after a download request has completed and returned content, asynchonous to a call to the Send method of the Downloader object. The Status and StatusText properties reflect the HTTP status code values for the completed download request.

Remarks

You can also add handlers in script using a quoted string for the event handler name:

downloaderObject.AddEventListener("Completed", "eventhandlerFunction")

This syntax also returns a token; however, the token is not an absolute requirement for removing the handler, in cases where the handler was added by using a quoted string. For details, see RemoveEventListener.

The Completed event occurs after you send a download request, and when a download request returns with content. Typically you use a Completed handler to then access the response text that is now available on the Downloader object, using either the ResponseText property or the GetResponseText method, depending on whether the download represents a package.

Examples

The following JavaScript example shows how to define a Completed event handler function that accesses the downloaded content, in this case a single content item download (not a package):

JavaScript
// Event handler for the Completed event.
function onCompleted(sender, eventArgs)
{
    // Retrieve downloaded XAML content.
    var xamlFragment = sender.ResponseText;

    // Create the objects from the XAML content.
    var plugin = sender.getHost();
    var button = plugin.content.createFromXaml(xamlFragment);

    // Add downloaded XAML content to the root Canvas of the plug-in.
    var rootCanvas = sender.findName("rootCanvas");
    rootCanvas.children.add(button);
}

Applies To

Downloader

See Also

DownloadProgressChanged, Status, StatusText, Using a Downloader Object


Completed Event

Occurs when the Storyboardhas completed playing.

XAML | <object Completed="eventhandlerFunction" .../>
Scripting | [token = ]object.AddEventListener("Completed", eventhandlerFunction)

AddEventListener Parameters

token | integer A token that is returned from the function, which you can optionally retain as a variable. If you intend to call RemoveEventListener to remove the handler, you will need this token.
eventhandlerFunction | object The name of your event handler function as it is defined in script. When used as an AddEventListener parameter, quotes around the function name are not required. See Remarks.

Event Handler Parameters

sender | object Identifies the object that invoked the event.
eventArgs | object This parameter is always set to null.

Remarks

A Storyboard has completed playing after it reaches the end of its active period (which includes repeats) and all its children have reached the end of their active periods. Interactively stopping a Storyboard does not trigger its completed event.

You can also add handlers in script using a quoted string for the event handler name:

object.AddEventListener("Completed", "eventhandlerFunction")
This syntax also returns a token; however, the token is not an absolute requirement for removing the handler, in cases where the handler was added by using a quoted string. For details, see RemoveEventListener.

Applies To

Storyboard

See Also

Silverlight Events


CurrentStateChanged Event

Occurs when the value of the CurrentState property changes.

XAML | <object CurrentStateChanged="eventhandlerFunction" .../>
Scripting | [token = ]object.AddEventListener("CurrentStateChanged", eventhandlerFunction)

AddEventListener Parameters

token | integer A token that is returned from the function, which you can optionally retain as a variable. If you intend to call RemoveEventListener to remove the handler, you will need this token.
eventhandlerFunction | object The name of your event handler function as it is defined in script. When used as an AddEventListener parameter, quotes around the function name are not required. See Remarks.

Event Handler Parameters

sender | object Identifies the object that invoked the event.
eventArgs | object This parameter is always set to null.

Remarks

You can also add handlers in script using a quoted string for the event handler name:

object.AddEventListener("CurrentStateChanged", "eventhandlerFunction")
This syntax also returns a token; however, the token is not an absolute requirement for removing the handler, in cases where the handler was added by using a quoted string. For details, see RemoveEventListener.

It is possible for this event to be raised multiple times before its event handlers are executed.

Although this event occurs when the CurrentState becomes invalid, that does not necessarily mean that the CurrentState property has a new value. For example, the CurrentState property might have switched from Playing to Buffering and back to Playing so rapidly that only a single CurrentStateChanged event was raised, in which case the property will not appear to have changed values. Also, your application should not assume an order in which the events occur, particularly for the transient states such as "Buffering". One of the transient states may have been skipped over in event reporting because it happened so rapidly.

Examples

The following example demonstrates one way to display the CurrentState of a MediaElement. It creates a MediaElement and several buttons for controlling media playback. To display the current state of the MediaElement, the example registers for the CurrentStateChanged event and uses an event handler to update a TextBlock.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Width="300" Height="300">

  <MediaElement
    x:Name="media"
    Source="xbox.wmv"
    CurrentStateChanged="media_state_changed"
    Width="300" Height="300"/>

  <!-- Stops media playback.-->
  <Canvas MouseLeftButtonDown="media_stop"
    Canvas.Left="10" Canvas.Top="265">
    <Rectangle Stroke="Black"
      Height="30" Width="55" RadiusX="5" RadiusY="5">
      <Rectangle.Fill>
        <RadialGradientBrush GradientOrigin="0.75,0.25">
          <GradientStop Color="Orange" Offset="0.0" />
          <GradientStop Color="Red" Offset="1.0" />
        </RadialGradientBrush>
      </Rectangle.Fill>
    </Rectangle>
    <TextBlock Canvas.Left="5" Canvas.Top="5">stop</TextBlock>
  </Canvas>

  <!-- Pauses media playback. -->
  <Canvas MouseLeftButtonDown="media_pause"
    Canvas.Left="70" Canvas.Top="265">
    <Rectangle Stroke="Black"
      Height="30" Width="55" RadiusX="5" RadiusY="5">
      <Rectangle.Fill>
        <RadialGradientBrush GradientOrigin="0.75,0.25">
          <GradientStop Color="Yellow" Offset="0.0" />
          <GradientStop Color="Orange" Offset="1.0" />
        </RadialGradientBrush>
      </Rectangle.Fill>
    </Rectangle>
    <TextBlock Canvas.Left="5" Canvas.Top="5">pause</TextBlock>
  </Canvas>

  <!-- Begins media playback. -->
  <Canvas MouseLeftButtonDown="media_begin"
    Canvas.Left="130" Canvas.Top="265">
    <Rectangle Stroke="Black" RadiusX="5" RadiusY="5"
      Height="30" Width="55">
      <Rectangle.Fill>
        <RadialGradientBrush GradientOrigin="0.75,0.25">
          <GradientStop Color="LimeGreen" Offset="0.0" />
          <GradientStop Color="Green" Offset="1.0" />
        </RadialGradientBrush>
      </Rectangle.Fill>
    </Rectangle>
    <TextBlock Canvas.Left="5" Canvas.Top="5">play</TextBlock>
  </Canvas>

  <TextBlock
    Canvas.Left="190" Canvas.Top="265"
    FontSize="12">CurrentState:</TextBlock>

  <TextBlock
    x:Name="mediaStateTextBlock"
    Canvas.Left="190" Canvas.Top="280"
    FontSize="12"></TextBlock>

</Canvas>
JavaScript
function media_stop(sender, args)
{
    sender.findName("media").stop();
}

function media_pause(sender, args)
{
    sender.findName("media").pause();
}

function media_begin(sender, args)
{
    sender.findName("media").play();
}

function media_state_changed(sender, args)
{
    var mediaStateTextBlock =
    sender.findName("mediaStateTextBlock");
    var media = sender.findName("media");
    mediaStateTextBlock.Text = media.CurrentState;
}

Applies To

MediaElement

See Also

Silverlight Events


DownloadFailed Event

Occurs when an attempted download request completes with no content.

XAML | Cannot be used in XAML.
Scripting | [token = ]downloaderObject.AddEventListener("DownloadFailed", eventhandlerFunction)

AddEventListener Parameters

downloaderObject | object A particular Downloader object.
token | integer A token that is returned from the function, which you can optionally retain as a variable. If you intend to call RemoveEventListener to remove the handler, you will need this token.
eventhandlerFunction | object The name of your event handler function as it is defined in script. When used as an AddEventListener parameter, quotes around the function name are not required. See Remarks.

Event Handler Parameters

sender | object Identifies the object that invoked the event.
eventArgs | object This parameter is always set to null.

Event Information

The DownloadFailed event occurs after a download request has completed and returned no content, asynchonous to a call to the Send method of the Downloader object. The Status and StatusText properties reflect the HTTP status code values for the failed download request.

Remarks

You can also add handlers in script using a quoted string for the event handler name:

downloaderObject.AddEventListener("DownloadFailed", "eventhandlerFunction")
This syntax also returns a token; however, the token is not an absolute requirement for removing the handler, in cases where the handler was added by using a quoted string. For details, see RemoveEventListener.

The DownloadFailed event occurs after you send a download request, and when a download request returns with no content. Typically you use a Completed event handler to access the response text that is available on the Downloader object. If you are downloading from a URI that has a chance of failing, you would then also add an event handler for the DownloadFailed event to your application and write the appropriate code steps that might be necessary to account for the content not being available.

Applies To

Downloader

See Also

DownloadProgressChanged, Status, Completed, StatusText, Using a Downloader Object


DownloadProgressChanged Event (Downloader)

Occurs while content is being downloaded during a download request.

XAML | Cannot be used in XAML.
Scripting | [token = ]downloaderObject.AddEventListener("DownloadProgressChanged", eventhandlerFunction)

AddEventListener Parameters

downloaderObject | object A particular Downloader object.
token | integer A token that is returned from the function, which you can optionally retain as a variable. If you intend to call RemoveEventListener to remove the handler, you will need this token.
eventhandlerFunction | object The name of your event handler function as it is defined in script. When used as an AddEventListener parameter, quotes around the function name are not required. See Remarks.

Event Handler Parameters

sender | object Identifies the object that invoked the event.
eventArgs | object This parameter is always set to null.

Event Information

The DownloadProgressChanged event can be used monitor the progress of a download request. The DownloadProgressChanged event occurs whenever the percentage of total content downloaded increases by 0.05 or more, or reaches 1.0. The Completed event occurs when the state of the download request has changed.

Remarks

You can also add handlers in script using a quoted string for the event handler name:

downloaderObject.AddEventListener("DownloadProgressChanged", "eventhandlerFunction")

This syntax also returns a token; however, the token is not an absolute requirement for removing the handler, in cases where the handler was added by using a quoted string. For details, see RemoveEventListener.

The progress factor is not carried in event arguments. Instead it is available as a property of the Downloader object that fired the event. That object is always the sender of the event.

Examples

The following JavaScript example shows how to use the DownloadProgress property in a DownloadProgressChanged event handler function:

JavaScript
// Event handler for updating visual progress indicator
function onDownloadProgressChanged(sender, eventArgs)
{
    // Calculate the downloaded percentage.
    var percentage = Math.floor(sender.downloadProgress * 100);

    // Update the Rectangle and TextBlock objects of the visual progress indicator.
    progressText.text = percentage + "%";
    progressRectangle.width = percentage * 2;
}

The following image shows the visual progress indicator at the starting, middle, and ending position of the download:

Visual progress indicator

A visual progress indicator can be constructed from a wide variety of XAML content, including animated objects.

Applies To

Downloader

See Also

DownloadProgress, Completed, Using a Downloader Object


DownloadProgressChanged Event (Image)

Occurs when the DownloadProgress property has changed.

XAML | <object DownloadProgressChanged="eventhandlerFunction" .../>
Scripting | [token = ]object.AddEventListener("DownloadProgressChanged", eventhandlerFunction)

AddEventListener Parameters

token | integer A token that is returned from the function, which you can optionally retain as a variable. If you intend to call RemoveEventListener to remove the handler, you will need this token.
eventhandlerFunction | object The name of your event handler function as it is defined in script. When used as an AddEventListener parameter, quotes around the function name are not required. See Remarks.

Event Handler Parameters

sender | object Identifies the object that invoked the event.
eventArgs | object This parameter is always set to null.

Remarks

You can also add handlers in script using a quoted string for the event handler name:

object.AddEventListener("DownloadProgressChanged", "eventhandlerFunction")
This syntax also returns a token; however, the token is not an absolute requirement for removing the handler, in cases where the handler was added by using a quoted string. For details, see RemoveEventListener.

This event occurs for progressive downloads only.

Applies To

Image

See Also

Silverlight Events, DownloadProgress, DownloadProgressChanged (Downloader)


DownloadProgressChanged Event (ImageBrush)

Occurs when the DownloadProgress property has changed.

XAML | <object DownloadProgressChanged="eventhandlerFunction" .../>
Scripting | [token = ]object.AddEventListener("DownloadProgressChanged", eventhandlerFunction)

AddEventListener Parameters

token | integer A token that is returned from the function, which you can optionally retain as a variable. If you intend to call RemoveEventListener to remove the handler, you will need this token.
eventhandlerFunction | object The name of your event handler function as it is defined in script. When used as an AddEventListener parameter, quotes around the function name are not required. See Remarks.

Event Handler Parameters

sender | object Identifies the object that invoked the event.
eventArgs | object This parameter is always set to null.

Remarks

You can also add handlers in script using a quoted string for the event handler name:

object.AddEventListener("DownloadProgressChanged", "eventhandlerFunction")
This syntax also returns a token; however, the token is not an absolute requirement for removing the handler, in cases where the handler was added by using a quoted string. For details, see RemoveEventListener.

This event occurs for progressive downloads only.

Applies To

ImageBrush

See Also

Silverlight Events, DownloadProgress, DownloadProgressChanged (Downloader)


DownloadProgressChanged Event (MediaElement)

Occurs when the DownloadProgress property has changed.

XAML | <object DownloadProgressChanged="eventhandlerFunction" .../>
Scripting | [token = ]object.AddEventListener("DownloadProgressChanged", eventhandlerFunction)

AddEventListener Parameters

token | integer A token that is returned from the function, which you can optionally retain as a variable. If you intend to call RemoveEventListener to remove the handler, you will need this token.
eventhandlerFunction | object The name of your event handler function as it is defined in script. When used as an AddEventListener parameter, quotes around the function name are not required. See Remarks.

Event Handler Parameters

sender | object Identifies the object that invoked the event.
eventArgs | object This parameter is always set to null.

Remarks

You can also add handlers in script using a quoted string for the event handler name:

object.AddEventListener("DownloadProgressChanged", "eventhandlerFunction")
This syntax also returns a token; however, the token is not an absolute requirement for removing the handler, in cases where the handler was added by using a quoted string. For details, see RemoveEventListener.

This event occurs for progressive downloads, typically occuring more than once.

Applies To

MediaElement

See Also

Silverlight Events, DownloadProgress, DownloadProgressChanged (Downloader)


GotFocus Event

Occurs when an object receives focus.

XAML | <object GotFocus="eventhandlerFunction" .../>
Scripting | [token = ]object.AddEventListener("GotFocus", eventhandlerFunction)

AddEventListener Parameters

token | integer A token that is returned from the function, which you can optionally retain as a variable. If you intend to call RemoveEventListener to remove the handler, you will need this token.
eventhandlerFunction | object The name of your event handler function as it is defined in script. When used as an AddEventListener parameter, quotes around the function name are not required. See Remarks.

Event Handler Parameters

sender | object Identifies the object that invoked the event.
eventArgs | object This parameter is always set to null.

Remarks

Use the GotFocus event to specify actions when an object receives focus.

Note The GotFocus event can only be defined for the root Canvas object.

You can also add handlers in script using a quoted string for the event handler name:

object.AddEventListener("GotFocus", "eventhandlerFunction")

This syntax also returns a token; however, the token is not an absolute requirement for removing the handler, in cases where the handler was added by using a quoted string. For details, see RemoveEventListener.

In some browsers, the GotFocus event is fired during the initial Silverlight plug-in loading into the HTML page, because of how the particular browser treats focus setting upon initiation in its control or plug-in model.

Examples

The following XAML example shows GotFocus and LostFocus events defined for the root Canvas object:

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  GotFocus="onGotFocus"
  LostFocus="onLostFocus">

  <TextBlock x:Name="myTextBlock" />

</Canvas>

The following JavaScript example shows to implement GotFocus and LostFocus event handler functions. In this case, the text in the TextBlock changes when focus is received or lost:

JavaScript
function onGotFocus(sender, eventArgs)
{
    sender.findName("myTextBlock").Text = "got focus";
}

function onLostFocus(sender, eventArgs)
{
    sender.findName("myTextBlock").Text = "lost focus";
}

Applies To

Canvas, Ellipse, Glyphs, Image, InkPresenter, Line, MediaElement, Path, Polygon, Polyline, Rectangle, TextBlock

See Also

LostFocus, Silverlight Events


ImageFailed Event (Image)

Occurs when there is a media related error.

XAML | <object ImageFailed="eventhandlerFunction" .../>
Scripting | [token = ]object.AddEventListener("ImageFailed", eventhandlerFunction)

AddEventListener Parameters

token | integer A token that is returned from the function, which you can optionally retain as a variable. If you intend to call RemoveEventListener to remove the handler, you will need this token.
eventhandlerFunction | object The name of your event handler function as it is defined in script. When used as an AddEventListener parameter, quotes around the function name are not required. See Remarks.

Event Handler Parameters

sender | object Identifies the object that invoked the event.
eventArgs | object This parameter is always set to null.

Remarks

Conditions in which this event can occur include:

  • File not found.
  • Invalid file format - unrecognized or unsupported format.
  • Unknown file format decoding error after upload.

The event can occur if the initial Source attribute value in XAML does not specify a valid source, or can occur if the Source value of an existing image is subsequently set to an invalid source in JavaScript.

You can also add handlers in script using a quoted string for the event handler name:

object.AddEventListener("ImageFailed", "eventhandlerFunction")
This syntax also returns a token; however, the token is not an absolute requirement for removing the handler, in cases where the handler was added by using a quoted string. For details, see RemoveEventListener.

Applies To

Image

See Also

Silverlight Events, Source, ImageFailed (ImageBrush)


ImageFailed Event (ImageBrush)

Occurs when there is a media related error.

XAML | <object ImageFailed="eventhandlerFunction" .../>
Scripting | [token = ]object.AddEventListener("ImageFailed", eventhandlerFunction)

AddEventListener Parameters

token | integer A token that is returned from the function, which you can optionally retain as a variable. If you intend to call RemoveEventListener to remove the handler, you will need this token.
eventhandlerFunction | object The name of your event handler function as it is defined in script. When used as an AddEventListener parameter, quotes around the function name are not required. See Remarks.

Event Handler Parameters

sender | object Identifies the object that invoked the event.
eventArgs | object This parameter is always set to null.

Remarks

Conditions in which this event can occur include:

  • File not found.
  • Invalid file format - unrecognized or unsupported format.
  • Unknown file format decoding error after upload.

The event can occur if the initial ImageSource attribute value in XAML does not specify a valid source, or can occur if the ImageSource value of an existing image is subsequently set to an invalid source in JavaScript.

You can also add handlers in script using a quoted string for the event handler name:

object.AddEventListener("ImageFailed", "eventhandlerFunction")
This syntax also returns a token; however, the token is not an absolute requirement for removing the handler, in cases where the handler was added by using a quoted string. For details, see RemoveEventListener.

Applies To

ImageBrush

See Also

Silverlight Events, Source, ImageFailed (ImageBrush)


KeyDown Event

Occurs when the key is pressed while the content has focus.

XAML | object KeyDown="eventhandlerFunction" .../>
Scripting | [token = ]object.AddEventListener("KeyDown", eventhandlerFunction)

AddEventListener Parameters

token | integer A token that is returned from the function, which you can optionally retain as a variable. If you intend to call RemoveEventListener to remove the handler, you will need this token.
eventhandlerFunction | object The name of your event handler function as it is defined in script. When used as an AddEventListener parameter, quotes around the function name are not required. See Remarks.

Event Handler Parameters

sender | object Identifies the object that invoked the event.
keyEventArgs | object keyEventArgs.key - an integer value that represents the key that is down. This value is the portable Key code, which is not operating system-specific. keyEventArgs.platformKeyCode - an integer value that represents the key that is down. This value is the non-portable key code, which is operating system-specific. keyEventArgs.shift - a boolean value that determines whether the SHIFT key is down. keyEventArgs.ctrl - a boolean value that determines whether the CTRL key is down.

Remarks

The KeyDown event can only be defined for the root Canvas object of a Silverlight plug-in.

Note For information on portability issues and which keystrokes the Web browser passes on the Silverlight content, see Silverlight Keyboard Support.

Note Handling keyboard events might vary between browsers. When you create an application that uses keyboard input, make sure to test the application in your target browsers.

Remarks

You can also add handlers in script using a quoted string for the event handler name:

object.AddEventListener("KeyDown", "eventhandlerFunction")

This syntax also returns a token; however, the token is not an absolute requirement for removing the handler, in cases where the handler was added by using a quoted string. For details, see RemoveEventListener.

In order for a keyboard event to be received, the Silverlight plug-in needs to have focus; otherwise, the events are not generated. A Silverlight plug-in can gain focus by user actions, such as clicking on the plug-in, or by tabbing to it.

Examples

The following XAML example shows a KeyDown event defined for the root Canvas object:

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  KeyDown="onKeyDown">

  <TextBlock
    x:Name="myTextBlock"
    Text="Display KeyDown event arguments" />

</Canvas>

The following JavaScript example shows to implement a KeyDown event handler function. In this case, the values of the keyEventArgs parameter are displayed for each KeyDown event:

JavaScript
// Set the TextBlock to display the key values.
function onKeyDown(sender, keyEventArgs)
{
    var textBlock = sender.findName("myTextBlock");

    // Concatenate the values of the KeyEventArgs parameter.
    var msg  = "key: " + keyEventArgs.key;
        msg += " platformKeycode: " + keyEventArgs.platformKeyCode;
        msg += " shift: " + keyEventArgs.shift;
        msg += " ctrl: " + keyEventArgs.ctrl;

    textBlock.text = msg;
}

Applies To

Canvas, Ellipse, Glyphs, Image, InkPresenter, Line, MediaElement, Path, Polygon, Polyline, Rectangle, TextBlock

See Also

Key, KeyUp, Silverlight Keyboard Support, Silverlight Events


KeyUp Event

Occurs when the key is released while the plug-in has focus.

XAML | object KeyUp="eventhandlerFunction" .../>
Scripting | [token = ]object.AddEventListener("KeyUp", eventhandlerFunction)

AddEventListener Parameters

token | integer A token that is returned from the function, which you can optionally retain as a variable. If you intend to call RemoveEventListener to remove the handler, you will need this token.
eventhandlerFunction | object The name of your event handler function as it is defined in script. When used as an AddEventListener parameter, quotes around the function name are not required. See Remarks.

Event Handler Parameters

sender | object Identifies the object that invoked the event.
keyEventArgs | object keyEventArgs.key - an integer value that represents the key that is down. This value is the portable Key code, which is not operating system-specific. keyEventArgs.platformKeyCode - an integer value that represents the key that is down. This value is the non-portable key code, which is operating system-specific. keyEventArgs.shift - a boolean value that determines whether the SHIFT key is down. keyEventArgs.ctrl - a boolean value that determines whether the CTRL key is down.

Event Information

The KeyUp event can only be defined for the root Canvas object of a Silverlight plug-in.

Note For information on portability issues and which keystrokes the Web browser passes on the Silverlight content, see Silverlight Keyboard Support.

Note Handling keyboard events might vary between browsers. When you create an application that uses keyboard input, make sure to test the application in your target browsers.

Remarks

You can also add handlers in script using a quoted string for the event handler name:

object.AddEventListener("KeyUp", "eventhandlerFunction")
This syntax also returns a token; however, the token is not an absolute requirement for removing the handler, in cases where the handler was added by using a quoted string. For details, see RemoveEventListener.

In order for a keyboard event to be received, the Silverlight plug-in needs to have focus; otherwise, the events are not generated. A Silverlight plug-in can gain focus by user actions, such as clicking on content in the plug-in, or by tabbing to it.

The keyDown event always precedes a KeyUp event.

Examples

The following XAML example shows a KeyUp event defined for the root Canvas object:

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  KeyUp="onKeyUp">

  <TextBlock
    x:Name="myTextBlock"
    Text="Display KeyUp event arguments" />

</Canvas>

The following JavaScript example shows to implement a KeyUp event handler function. In this case, the Silverlight version is displayed when the keystroke combination CTRL+V was detected:

JavaScript
// Set the TextBlock to display the key values.
function onKeyUp(sender, keyEventArgs)
{
    // Determine whether the keystroke combination CTRL+V was detected.
    if ((keyEventArgs.key == 51) && (keyEventArgs.ctrl == true))
    {
       // Retrieve a reference to the plug-in.
       var plugin = sender.getHost();

       // Display whether the 1.0 version of Silverlight is supported.
       alert("Silverlight version: " + plugin.IsVersionSupported);
    }
}

Applies To

Canvas, Ellipse, Glyphs, Image, InkPresenter, Line, MediaElement, Path, Polygon, Polyline, Rectangle, TextBlock

See Also

Key, KeyDown, Silverlight Keyboard Support, Silverlight Events


Loaded Event

Fired when the Silverlight content is loaded into the host Silverlight plug-in and parsed, but before the content is rendered.

XAML | <object Loaded="eventhandlerFunction" .../>
Scripting | [token = ]object.AddEventListener("Loaded", eventhandlerFunction)

AddEventListener Parameters

token | integer A token that is returned from the function, which you can optionally retain as a variable. If you intend to call RemoveEventListener to remove the handler, you will need this token.
eventhandlerFunction | object The name of your event handler function as it is defined in script. When used as an AddEventListener parameter, quotes around the function name are not required. See Remarks.

Event Handler Parameters

sender | object Identifies the object that invoked the event.
eventArgs | object This parameter is always set to null.

Event Information

The Loaded event can be defined for any UIElement-derived class, such as Canvas, TextBlock, or Rectangle.

Remarks

You can also add handlers in script using a quoted string for the event handler name:

object.AddEventListener("Loaded", "eventhandlerFunction")

This syntax also returns a token; however, the token is not an absolute requirement for removing the handler, in cases where the handler was added by using a quoted string. For details, see RemoveEventListener.

You can define multiple Loaded events for objects in XAML content. However, if a child object and its parent object both define a Loaded event, the child object's Loaded event is fired before the parent object's Loaded event.

Caution The alert() mechanism that is provided in JavaScript on browsers is not a reliable way to examine the order in which events are fired. Frequently the alerts will fall out of the true order of the events. Instead of using alert(), use the technique shown here and write out log messages to a plug-in on the page, or something similar.

Examples

The following XAML example shows Loaded events defined for a Canvas and TextBlock object. In this case, the TextBlock object's event handler function is invoked before the Canvas object's event handler function.

XAML
<!-- TextBlock Loaded event fires first, then Canvas Loaded event -->
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Loaded="rootCanvasLoaded">

  <TextBlock
   x:Name="myTextBlock"
   Loaded="textBlockLoaded"
   Text="Test order of Loaded events" />

</Canvas>

The following JavaScript example shows to implement a Loaded event handler function. Notice that the eventArgs parameter is omitted, since it is not referenced by the function:

JavaScript
function rootCanvasLoaded(sender)
{
    // Set the TextBlock to display the current date and time.
    sender.findName("myTextBlock").text = Date();
}

The Silverlight plug-in provides an OnLoad event that occurs after the XAML content in the Silverlight plug-in has completely loaded. This means that the Onload event always occurs after any Loaded events occur.

JavaScript provides a set of events that you can use to respond to changes in the Web page, including the onload event. You can use the onload event and the Silverlight Loaded event on the same page. The following HTML example shows how to use the onload event:

JavaScript
<body onload='javascript:alert("onload event generated")'>

In this example, JavaScript code is used directly instead of referencing an event handler function--this is not possible with Silverlight events. By definition, the JavaScript onload event is not fired until the entire Web page is loaded. This means that any Silverlight plug-in contained within the page will fire its Loaded event before the JavaScript onload event.

Applies To

UIElement

See Also

OnLoad, Silverlight Events


LostFocus Event

Occurs when an object loses focus.

XAML | <object LostFocus="eventhandlerFunction" .../>
Scripting | [token = ]object.AddEventListener("LostFocus", eventhandlerFunction)

AddEventListener Parameters

token | integer A token that is returned from the function, which you can optionally retain as a variable. If you intend to call RemoveEventListener to remove the handler, you will need this token.
eventhandlerFunction | object The name of your event handler function as it is defined in script. When used as an AddEventListener parameter, quotes around the function name are not required. See Remarks.

Event Handler Parameters

sender | object Identifies the object that invoked the event.
eventArgs | object This parameter is always set to null.

Event Information

Use the LostFocus event to specify actions when an object loses focus.

Note The LostFocus event can only be defined for the root Canvas object in a Silverlight plug-in.

Remarks

You can also add handlers in script using a quoted string for the event handler name:

object.AddEventListener("LostFocus", "eventhandlerFunction")

This syntax also returns a token; however, the token is not an absolute requirement for removing the handler, in cases where the handler was added by using a quoted string. For details, see RemoveEventListener.

Examples

The following XAML example shows GotFocus and LostFocus events defined for the root Canvas object:

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  GotFocus="onGotFocus"
  LostFocus="onLostFocus">

  <TextBlock x:Name="myTextBlock" />

</Canvas>

The following JavaScript example shows to implement GotFocus and LostFocus event handler functions. In this case, the text in the TextBlock changes opacity when focus is received or lost:

JavaScript
function onGotFocus(sender, eventArgs)
{
    sender.findName("myTextBlock").Text = "got focus";
}

function onLostFocus(sender, eventArgs)
{
    sender.findName("myTextBlock").Text = "lost focus";
}

Applies To

Canvas, Ellipse, Glyphs, Image, InkPresenter, Line, MediaElement, Path, Polygon, Polyline, Rectangle, TextBlock

See Also

GotFocus, Silverlight Events


MarkerReached Event

Occurs when a timeline marker is encountered during media playback.

XAML | <object MarkerReached="eventhandlerFunction" .../>
Scripting | [token = ]object.AddEventListener("MarkerReached", eventhandlerFunction)

AddEventListener Parameters

token | integer A token that is returned from the function, which you can optionally retain as a variable. If you intend to call RemoveEventListener to remove the handler, you will need this token.
eventhandlerFunction | object The name of your event handler function as it is defined in script. When used as an AddEventListener parameter, quotes around the function name are not required. See Remarks.

Event Handler Parameters

sender | object The MediaElement that invoked the event.
markerEventArgs | object markerEventArgs.Marker gets the TimelineMarker that triggered this event.

Remarks

You can also add handlers in script using a quoted string for the event handler name:

object.AddEventListener("MarkerReached", "eventhandlerFunction")
This syntax also returns a token; however, the token is not an absolute requirement for removing the handler, in cases where the handler was added by using a quoted string. For details, see RemoveEventListener.

This event is not raised when the MediaElement seeks past a timeline marker.

This event is raised whenever a marker associated with the media is reached. The marker might come from one of three locations:

  • A marker that is stored in the metadata of the currently opened media.
  • A marker that is associated with the currently opened media and comes from a separate stream.
  • A marker that was explicitly added to the Markers collection for the currently opened media, using script.

Examples

The following example creates a MediaElement object and responds to its MarkerReached event. Each time a timeline marker is reached, the example displays the timeline marker's Time, Type, and Text values.

XAML
<Canvas
   xmlns="http://schemas.microsoft.com/client/2007"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 Width="300" Height="300">

  <MediaElement x:Name="media"
    Canvas.Top="50"
    MediaOpened="onMediaOpened"
    MarkerReached="onMarkerReached" Source="thebutterflyandthebear.wmv"
    Width="300" Height="200" />

  <Canvas Canvas.Left="10" Canvas.Top="5">

    <TextBlock
      FontSize="12" Foreground="DarkGray">Time:</TextBlock>

    <TextBlock x:Name="timeTextBlock"
      Canvas.Left="40"
      FontSize="12" />

    <TextBlock Canvas.Top="12"
      FontSize="12" Foreground="DarkGray">Type:</TextBlock>

    <TextBlock x:Name="typeTextBlock"
      Canvas.Left="40" Canvas.Top="12"
      FontSize="12" />

    <TextBlock
      Canvas.Top="24"
      FontSize="12" Foreground="DarkGray">Value:</TextBlock>

    <TextBlock x:Name="valueTextBlock"
      Canvas.Left="40" Canvas.Top="24"
      FontSize="12" />

  </Canvas>

  <!-- Stops media playback.-->
  <Canvas MouseLeftButtonDown="media_stop"
    Canvas.Left="10" Canvas.Top="265">
    <Rectangle Stroke="Black"
       Height="30" Width="55" RadiusX="5" RadiusY="5">
      <Rectangle.Fill>
        <RadialGradientBrush GradientOrigin="0.75,0.25">
          <GradientStop Color="Orange" Offset="0.0" />
          <GradientStop Color="Red" Offset="1.0" />
        </RadialGradientBrush>
      </Rectangle.Fill>
    </Rectangle>
    <TextBlock Canvas.Left="5" Canvas.Top="5">stop</TextBlock>
  </Canvas>

  <!-- Pauses media playback. -->
  <Canvas MouseLeftButtonDown="media_pause"
     Canvas.Left="70" Canvas.Top="265">
    <Rectangle Stroke="Black"
       Height="30" Width="55" RadiusX="5" RadiusY="5">
      <Rectangle.Fill>
        <RadialGradientBrush GradientOrigin="0.75,0.25">
          <GradientStop Color="Yellow" Offset="0.0" />
          <GradientStop Color="Orange" Offset="1.0" />
        </RadialGradientBrush>
      </Rectangle.Fill>
    </Rectangle>
    <TextBlock Canvas.Left="5" Canvas.Top="5">pause</TextBlock>
  </Canvas>

  <!-- Begins media playback. -->
  <Canvas MouseLeftButtonDown="media_begin"
    Canvas.Left="130" Canvas.Top="265">
    <Rectangle Stroke="Black" RadiusX="5" RadiusY="5"
       Height="30" Width="55">
      <Rectangle.Fill>
        <RadialGradientBrush GradientOrigin="0.75,0.25">
          <GradientStop Color="LimeGreen" Offset="0.0" />
          <GradientStop Color="Green" Offset="1.0" />
        </RadialGradientBrush>
      </Rectangle.Fill>
    </Rectangle>
    <TextBlock Canvas.Left="5" Canvas.Top="5">play</TextBlock>
  </Canvas>

</Canvas>
JavaScript
function media_stop(sender, args) {
    sender.findName("media").stop();
}

function media_pause(sender, args) {
    sender.findName("media").pause();
    alert(sender.findName("media").name);
}

function media_begin(sender, args) {
    sender.findName("media").play();

}

function onMarkerReached(sender, markerEventArgs)
{

  sender.findName("timeTextBlock").Text =
      markerEventArgs.marker.time.seconds.toString();

  sender.findName("typeTextBlock").Text =
       markerEventArgs.marker.type;

  sender.findName("valueTextBlock").Text =
       markerEventArgs.marker.text;

}

Applies To

MediaElement

See Also

Silverlight Events, TimelineMarker, Media Overview


MediaEnded Event

Occurs when the MediaElement is no longer playing audio or video.

XAML | <object MediaEnded="eventhandlerFunction" .../>
Scripting | [token = ]object.AddEventListener("MediaEnded", eventhandlerFunction)

AddEventListener Parameters

token | integer A token that is returned from the function, which you can optionally retain as a variable. If you intend to call RemoveEventListener to remove the handler, you will need this token.
eventhandlerFunction | object The name of your event handler function as it is defined in script. When used as an AddEventListener parameter, quotes around the function name are not required. See Remarks.

Event Handler Parameters

sender | object Identifies the object that invoked the event.
eventArgs | object This parameter is always set to null.

Remarks

You can also add handlers in script using a quoted string for the event handler name:

object.AddEventListener("MediaEnded", "eventhandlerFunction")
This syntax also returns a token; however, the token is not an absolute requirement for removing the handler, in cases where the handler was added by using a quoted string. For details, see RemoveEventListener.

If the media file contains multiple streams, this event will occur after the last stream has ended.

The MediaEnded event does not occur if media playback is controlled interactively. The event that calls the Stop method can be used for end of media tasks.

Applies To

MediaElement

See Also

Silverlight Events


MediaFailed Event

Occurs when there is a media related error.

XAML | <object MediaFailed="eventhandlerFunction" .../>
Scripting | [token = ]object.AddEventListener("MediaFailed", eventhandlerFunction)

AddEventListener Parameters

token | integer A token that is returned from the function, which you can optionally retain as a variable. If you intend to call RemoveEventListener to remove the handler, you will need this token.
eventhandlerFunction | object The name of your event handler function as it is defined in script. When used as an AddEventListener parameter, quotes around the function name are not required. See Remarks.

Event Handler Parameters

sender | object Identifies the object that invoked the event.
eventArgs | object This parameter is always set to null.

Remarks

Conditions in which this event can occur include:

  • File not found.
  • Invalid file format - unrecognized or unsupported media format.
  • Unknown media error during playback.

Setting a cross-domain URI for Source will either succeed, or will not return a valid status for any failure. An error is thrown on the SetValue method call for setting "Source" in this case.

You can also add handlers in script using a quoted string for the event handler name:

object.AddEventListener("MediaFailed", "eventhandlerFunction")
This syntax also returns a token; however, the token is not an absolute requirement for removing the handler, in cases where the handler was added by using a quoted string. For details, see RemoveEventListener.

Applies To

MediaElement

See Also

Silverlight Events


MediaOpened Event

Occurs when the media stream has been validated, opened, and the file headers have been read.

XAML | <object MediaOpened="eventhandlerFunction" .../>
Scripting | [token = ]object.AddEventListener("MediaOpened", eventhandlerFunction)

AddEventListener Parameters

token | integer A token that is returned from the function, which you can optionally retain as a variable. If you intend to call RemoveEventListener to remove the handler, you will need this token.
eventhandlerFunction | object The name of your event handler function as it is defined in script. When used as an AddEventListener parameter, quotes around the function name are not required. See Remarks.

Event Handler Parameters

sender | object Identifies the object that invoked the event.
eventArgs | object This parameter is always set to null.

Remarks

A MediaElement generally possesses two types of properties: properties that are settable and that declare appearance or behavior of the MediaElement , and read-only properties that report on characteristics of the current Source file that is loaded by the MediaElement. Properties in this second category will not contain valid values until the MediaElement raises the MediaOpened event. The following is a list of MediaElement properties that will not be valid until after MediaOpened is raised by that element.

  • Attributes
  • AudioStreamCount
  • AudioStreamIndex
  • BufferingProgress
  • DownloadProgress
  • Markers
  • NaturalDuration
  • NaturalVideoHeight
  • NaturalVideoWidth

Also, Position will be null prior to MediaOpened, but Position is slightly different because it is settable. You should not attempt to set Position until MediaOpened is raised. You also should not set an initial Position value in XAML.

If the AutoPlay property is set to false, the media will be paused when the MediaOpened event occurs.

You can also add handlers in script using a quoted string for the event handler name:

object.AddEventListener("MediaOpened", "eventhandlerFunction")
This syntax also returns a token; however, the token is not an absolute requirement for removing the handler, in cases where the handler was added by using a quoted string. For details, see RemoveEventListener.

Applies To

MediaElement

See Also

Silverlight Events


MouseEnter Event

Occurs when the mouse enters the bounding area of an object.

XAML | object MouseEnter="eventhandlerFunction" .../>
Scripting | [token = ]object.AddEventListener("MouseEnter", eventhandlerFunction)

AddEventListener Parameters

token | integer A token that is returned from the function, which you can optionally retain as a variable. If you intend to call RemoveEventListener to remove the handler, you will need this token.
eventhandlerFunction | object The name of your event handler function as it is defined in script. When used as an AddEventListener parameter, quotes around the function name are not required. See Remarks.

Event Handler Parameters

sender | object Identifies the object that invoked the event.
mouseEventArgs | object mouseEventArgs.getPosition(element).x identifies the x-coordinate position of the mouse. mouseEventArgs.getPosition(element).y identifies the y-coordinate position of the mouse. mouseEventArgs.shift determines whether the SHIFT key is down. mouseEventArgs.ctrl determines whether the CTRL key is down.

Event Information

The MouseEnter event can be defined for any UIElement-derived class, such as Canvas, TextBlock, or Rectangle.

Remarks

The MouseEnter event is typically fired in response to the mouse into the object's bounding area. In this case, the MouseEnter event precedes the MouseMove event for the object. However, it is possible to receive a MouseEnter event without a MouseMove event:

  • The object, rather than the mouse, is moved under the cursor position.
  • The object is capturing mouse events. When an object captures the mouse, it receives mouse input whether or not the cursor is within its borders. The mouse is typically captured in this manner only during drag-and-drop operations, and retains capture until the drop action of the drag-and-drop operation occurs.

You can also add handlers in script using a quoted string for the event handler name:

object.AddEventListener("MouseEnter", "eventhandlerFunction")

This syntax also returns a token; however, the token is not an absolute requirement for removing the handler, in cases where the handler was added by using a quoted string. For details, see RemoveEventListener.

You can define multiple MouseEnter events for objects in XAML content. However, if a child object and its parent object both define a MouseEnter event, the parent object's MouseEnter event is fired before the child object's MouseEnter event.

The mouse position reported in the mouseEventArgs parameter value may not be exactly on the boundary of the object, due to the coalescing of mouse movements.

Examples

The following XAML example shows MouseEnter events defined for a Canvas and TextBlock object. In this case, the Canvas object's event handler function is invoked before the TextBlock object's event handler function.

XAML
<!-- Canvas MouseEnter event fires first, then TextBlock MouseEnter event -->
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  MouseEnter="rootCanvasMouseEnter">

  <TextBlock
    x:Name="myTextBlock"
    MouseEnter="textBlockMouseEnter"
    Text="Test order of MouseEnter events" />

</Canvas>

The following JavaScript example shows to implement a MouseEnter event handler function:

JavaScript
function rootCanvasMouseEnter(sender, mouseEventArgs)
{
    // Concatenate the values of the MouseEventArgs parameter.
    var msg  = "x = " + mouseEventArgs.getPosition(null).x;
        msg += "  y = " + mouseEventArgs.getPosition(null).y;
        msg += "  shift = " + mouseEventArgs.shift;
        msg += "  ctrl = " + mouseEventArgs.ctrl;

    // Display the values of the MouseEventArgs parameter.
    sender.findName("myTextBlock").text = msg;
}

Applies To

Canvas, Ellipse, Glyphs, Image, InkPresenter, Line, MediaElement, Path, Polygon, Polyline, Rectangle, TextBlock

See Also

Silverlight Events, Silverlight Mouse Support, MouseLeave, MouseLeftButtonDown, MouseLeftButtonUp, MouseMove, GetPosition


MouseLeave Event

Occurs when the mouse leaves the bounding area of an object.

XAML | object MouseLeave="eventhandlerFunction" .../>
Scripting | [token = ]object.AddEventListener("MouseLeave", eventhandlerFunction)

AddEventListener Parameters

token | integer A token that is returned from the function, which you can optionally retain as a variable. If you intend to call RemoveEventListener to remove the handler, you will need this token.
eventhandlerFunction | object The name of your event handler function as it is defined in script. When used as an AddEventListener parameter, quotes around the function name are not required. See Remarks.

Event Handler Parameters

sender | object Identifies the object that invoked the event.
mouseEventArgs | object This parameter is always set to null.

Event Information

The MouseLeave event can be defined for any UIElement-derived class, such as Canvas, TextBlock, or Rectangle.

Remarks

The MouseLeave event is typically fired in response to the mouse leaving the object's bounding area. However, it is possible for an object to continue receiving mouse events after receiving a MouseLeave event:

  • The object is capturing mouse events. When an object captures the mouse, it receives mouse input whether or not the cursor is within its borders. The mouse is typically captured in this manner only during drag-and-drop operations, and retains capture until the drop action of the drag-and-drop operation occurs.

You can also add handlers in script using a quoted string for the event handler name:

object.AddEventListener("MouseLeave", "eventhandlerFunction")

This syntax also returns a token; however, the token is not an absolute requirement for removing the handler, in cases where the handler was added by using a quoted string. For details, see RemoveEventListener.

You can define multiple MouseLeave events for objects in XAML content. However, if a child object and its parent object both define a MouseLeave event, the parent object's MouseLeave event is fired before the child object's MouseLeave event.

Unlike the MouseEnter event, the MouseLeave event does not provide the mouse position as an event argument, since the location of the mouse position relative to the object is unknown. This means you can omit the mouseEventArgs parameter for the MouseLeave event handler function.

Examples

The following XAML example shows MouseLeave events defined for a Canvas and TextBlock object. In this case, the Canvas object's event handler function is invoked before the TextBlock object's event handler function.

XAML
<!-- The Canvas MouseLeave event fires first, then the TextBlock MouseLeave event -->
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  MouseLeave="rootCanvasMouseLeave">

  <TextBlock
   x:Name="captionTextBlock"
   MouseLeave="textBlockMouseLeave"
   Text="Test order of MouseLeave events" />

</Canvas>

The following JavaScript example shows to implement a MouseLeave event handler function:

JavaScript
function rootCanvasMouseLeave(sender)
{
    // Remove the visibility of the caption TextBlock.
    sender.findName("captionTextBlock").opacity = 0;
}

Applies To

Canvas, Ellipse, Glyphs, Image, InkPresenter, Line, MediaElement, Path, Polygon, Polyline, Rectangle, TextBlock

See Also

Silverlight Events, Silverlight Mouse Support, MouseEnter, MouseLeftButtonDown, MouseLeftButtonUp, MouseMove


MouseLeftButtonDown Event

Occurs when the left mouse button is depressed.

XAML | object MouseLeftButtonDown="eventhandlerFunction" .../>
Scripting | [token = ]object.AddEventListener("MouseLeftButtonDown", eventhandlerFunction)

AddEventListener Parameters

token | integer A token that is returned from the function, which you can optionally retain as a variable. If you intend to call RemoveEventListener to remove the handler, you will need this token.
eventhandlerFunction | object The name of your event handler function as it is defined in script. When used as an AddEventListener parameter, quotes around the function name are not required. See Remarks.

Event Handler Parameters

sender | object Identifies the object that invoked the event.
mouseEventArgs | object mouseEventArgs.getPosition(element).x identifies the x-coordinate position of the mouse. mouseEventArgs.getPosition(element).y identifies the y-coordinate position of the mouse. mouseEventArgs.shift determines whether the SHIFTkey is down. mouseEventArgs.ctrl determines whether the CTRL key is down.

Event Information

The MouseLeftButtonDown event can be defined for any UIElement-derived class, such as Canvas, TextBlock, or Rectangle.

Remarks

The MouseLeftButtonDown event is fired when the left mouse button is depressed when the mouse is over the object. When the mouse is released, the MouseLeftButtonUp event is fired. However, if the mouse if moved over another object when it is released, the object that received the MouseLeftButtonDown event will not receive the MouseLeftButtonUp event. There is no discrete double click event. A double click is simply two sequences of MouseLeftButtonDown and MouseLeftButtonUp events.

Examples

The MouseLeftButtonDown event is a bubbled event. This means that if there multiple MouseLeftButtonDown events defined for an object and its ancestors, the event is received by each object in the ancestor hierarchy, starting with the object that directly receives the event. Consider the following XAML example in which shows MouseLeftButtonDown events defined for a two Canvas and one TextBlock objects. In this case, if you depress the mouse over the TextBlock object, it receives the MouseLeftButtonDown. The event is then bubbled upward to the parent Canvas, and finally to the top-level Canvas object.

You can also add handlers in script using a quoted string for the event handler name:

object.AddEventListener("MouseLeftButtonDown", "eventhandlerFunction")

This syntax also returns a token; however, the token is not an absolute requirement for removing the handler, in cases where the handler was added by using a quoted string. For details, see RemoveEventListener.

XAML
<!-- The TextBlock event occurs first. -->
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  MouseLeftButtonDown="rootCanvasMouseLeftButtonDown">

  <Canvas
    Canvas.Left="20" Canvas.Top="20"
    MouseLeftButtonDown="canvasMouseLeftButtonDown">

    <TextBlock
      x:Name="myTextBlock"
      Canvas.Left="25" Canvas.Top="5"
      MouseLeftButtonDown="textMouseLeftButtonDown"
      FontSize="24"
      Text="Click me" />

  </Canvas>
</Canvas>

The following JavaScript example shows to implement a MouseLeftButtonDown event handler function:

JavaScript
function rootCanvasMouseLeftButtonDown(sender, mouseEventArgs)
{
    // Set the TextBlock to display the mouse position.
    sender.findName("myTextBlock").text = "x = " + mouseEventArgs.getPosition(null).x + "  y = " + mouseEventArgs.getPosition(null).y;
}

Applies To

Canvas, Ellipse, Glyphs, Image, InkPresenter, Line, MediaElement, Path, Polygon, Polyline, Rectangle, TextBlock

See Also

Silverlight Events, Silverlight Mouse Support, MouseEnter, MouseLeave, MouseLeftButtonUp, MouseMove, GetPosition


MouseLeftButtonUp Event

Occurs when the left mouse button is released.

XAML | object MouseLeftButtonUp="eventhandlerFunction" .../>
Scripting | [token = ]object.AddEventListener("MouseLeftButtonUp", eventhandlerFunction)

AddEventListener Parameters

token | integer A token that is returned from the function, which you can optionally retain as a variable. If you intend to call RemoveEventListener to remove the handler, you will need this token.
eventhandlerFunction | object The name of your event handler function as it is defined in script. When used as an AddEventListener parameter, quotes around the function name are not required. See Remarks.

Event Handler Parameters

sender | object Identifies the object that invoked the event.
mouseEventArgs | object mouseEventArgs.getPosition(element).x identifies the x-coordinate position of the mouse. mouseEventArgs.getPosition(element).y identifies the y-coordinate position of the mouse. mouseEventArgs.shift determines whether the SHIFT key is down. mouseEventArgs.ctrl determines whether the CTRL key is down.

Event Information

The MouseLeftButtonUp event can be defined for any UIElement-derived class, such as Canvas, TextBlock, or Rectangle.

Remarks

The MouseLeftButtonUp event is fired when the left mouse button is released when the mouse is over the object. When the mouse is depressed, the MouseLeftButtonDown event is fired. However, if the mouse if moved over another object when it is released, the object that received the MouseLeftButtonDown event will not receive the MouseLeftButtonUp event. There is no discrete double click event. A double click is simply two sequences of MouseLeftButtonDown and MouseLeftButtonUp events.

Examples

The MouseLeftButtonUp event is a bubbled event. This means that if there multiple MouseLeftButtonUp events defined for an object and its ancestors, the event is received by each object in the ancestor hierarchy, starting with the object that directly receives the event. Consider the following XAML example in which shows MouseLeftButtonUp events defined for a two Canvas and one TextBlock objects. In this case, if you release the mouse over the TextBlock object, it receives the MouseLeftButtonUp event. The event is then bubbled upward to the parent Canvas, and finally to the top-level Canvas object.

You can also add handlers in script using a quoted string for the event handler name:

object.AddEventListener("MouseLeftButtonUp", "eventhandlerFunction")
This syntax also returns a token; however, the token is not an absolute requirement for removing the handler, in cases where the handler was added by using a quoted string. For details, see RemoveEventListener.

XAML
<!-- The TextBlock event occurs first. -->
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  MouseLeftButtonUp="rootCanvasMouseLeftButtonUp">

  <Canvas Canvas.Left="20" Canvas.Top="20"
    MouseLeftButtonUp="canvasMouseLeftButtonUp">

    <TextBlock
      x:Name="myTextBlock"
      Canvas.Left="25" Canvas.Top="5"
      MouseLeftButtonDown="textMouseLeftButtonDown"
      FontSize="24"
      Text="Click me" />

  </Canvas>
</Canvas>

The following JavaScript example shows to implement a MouseLeftButtonUp event handler function:

JavaScript
function rootCanvasMouseLeftButtonUp(sender, mouseEventArgs)
{
    // Set the TextBlock to display the mouse position.
    sender.findName("myTextBlock").text = "x = " + mouseEventArgs.getPosition(null).x + "  y = " + mouseEventArgs.getPosition(null).y ;
}

Applies To

Canvas, Ellipse, Glyphs, Image, InkPresenter, Line, MediaElement, Path, Polygon, Polyline, Rectangle, TextBlock

See Also

Silverlight Events, Silverlight Mouse Support, MouseEnter, MouseLeave, MouseLeftButtonDown, MouseMove, GetPosition


MouseMove Event

Occurs when the coordinate position of the mouse changes.

XAML | object MouseMove="eventhandlerFunction" .../>
Scripting | [token = ]object.AddEventListener("MouseMove", eventhandlerFunction)

AddEventListener Parameters

token | integer A token that is returned from the function, which you can optionally retain as a variable. If you intend to call RemoveEventListener to remove the handler, you will need this token.
eventhandlerFunction | object The name of your event handler function as it is defined in script. When used as an AddEventListener parameter, quotes around the function name are not required. See Remarks.

Event Handler Parameters

sender | object Identifies the object that invoked the event.
mouseEventArgs | object mouseEventArgs.getPosition(element).x identifies the x-coordinate position of the mouse. mouseEventArgs.getPosition(element).y identifies the y-coordinate position of the mouse. mouseEventArgs.shift determines whether the SHIFT key is down. mouseEventArgs.ctrl determines whether the CTRL key is down.

Event Information

The MouseMove event can be defined for any UIElement-derived class, such as Canvas, TextBlock, or Rectangle.

Remarks

The MouseMove event is typically fired in response to the mouse moving over the object's bounding area. If the mouse enters the object's bounding area, the MouseEnter event precedes the MouseMove event for the object. However, it is possible to receive a MouseMove event without the mouse moving:

  • The object, rather than the mouse, is moved under the cursor position.

Examples

The MouseMove event is a bubbled event. This means that if there multiple MouseMove events defined for an object and its ancestors, the event is received by each object in the ancestor hierarchy, starting with the object that directly receives the event. Consider the following XAML example in which shows MouseMove events defined for a Canvas and two Rectangle objects. In this case, if you move the mouse over either Rectangle object, it receives the MouseMove event. The event is then bubbled upward to the parent Canvas.

You can also add handlers in script using a quoted string for the event handler name:

object.AddEventListener("MouseMove", "eventhandlerFunction")
This syntax also returns a token; however, the token is not an absolute requirement for removing the handler, in cases where the handler was added by using a quoted string. For details, see RemoveEventListener.

XAML
<!-- The Rectangle MouseMove events occur first, then the Canvas MouseMove event. -->
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Loaded="onLoaded"
  MouseMove="rootCanvasMouseMove">

  <Rectangle
    MouseMove="rect1MouseMove"
    Width="100" Height="100"
    Fill="PowderBlue" />

  <Rectangle
    MouseMove="rect2MouseMove"
    Canvas.Top="50" Canvas.Left="50"
    Width="100" Height="100"
    Fill="Gold" Opacity="0.5" />

  <TextBlock
    x:Name="statusTextBlock"
    Canvas.Top="180" />

</Canvas>

The following JavaScript example shows how to implement the MouseMove event handler functions for the corresponding XAML content in the previous example:

JavaScript
var statusTextBlock;

function onLoaded(sender, eventArgs)
{
    statusTextBlock = sender.findName("statusTextBlock");
}

function rootCanvasMouseMove(sender, mouseEventArgs)
{
    var msg = "x:y = " + mouseEventArgs.getPosition(null).x + ", " + mouseEventArgs.getPosition(null).y;
    // Uncomment the next line to show MouseMove event bubbling.
    // statusTextBlock.text = "rootCanvas: " + msg;
}

function rect1MouseMove(sender, mouseEventArgs)
{
    var msg = "x:y = " + mouseEventArgs.getPosition(null).x + ", " + mouseEventArgs.getPosition(null).y;
    statusTextBlock.text = "rect1: " + msg;
}

function rect2MouseMove(sender, mouseEventArgs)
{
    var msg = "x:y = " + mouseEventArgs.getPosition(null).x + ", " + mouseEventArgs.getPosition(null).y;
    statusTextBlock.text = "rect2: " + msg;
}

The following screenshot shows the displayed XAML content. When the mouse moves over the Rectangle objects, the event handlers display the x:y coordinate position of the mouse. Notice that when the mouse is over the overlapping area of the Rectangle objects, the top-most object blocks the MouseMove events from the obscured object--events do not bubble to siblings, only ancestors. Also notice that if you were to uncomment the line in the rootCanvasMouseMove event handler function in the JavaScript code, the function would correctly display the position of the mouse for both its child objects.

In this case, where the Canvas object has a Height or Width property set to 0 and a Background property set to null, the MouseMove event is only generated for the child objects. This is because the Canvas object has no visibility as far as MouseMove events are concerned.

The mouse position reported in the mouseEventArgs parameter value may not be exactly on the boundary of the object, due to the coalescing of mouse movements.

Applies To

Canvas, Ellipse, Glyphs, Image, InkPresenter, Line, MediaElement, Path, Polygon, Polyline, Rectangle, TextBlock

See Also

Silverlight Events, Silverlight Mouse Support, MouseEnter, MouseLeave, MouseLeftButtonDown, MouseLeftButtonUp, GetPosition


OnError Event

Occurs when the Silverlight plug-in generates a runtime error.

Scripting (Instantiation) | Silverlight.CreateObject(,,,,{onError:functionName}) -or- Silverlight.CreateObjectEx({,,,events:{onError:functionName}})
Scripting (Runtime) | silverlightObject.onError = functionName

Event Handler Parameters

sender | object Identifies the Silverlight plug-in that invoked the event.
errorEventArgs | object Identifies the error and provides information about its source location. For more information, see ErrorEventArgs.

Remarks

The OnError event allows you to specify a user-defined JavaScript error handling function that is invoked when an error is generated in the Silverlight runtime components. The default value is null. If you are using the JavaScript helper file, Silverlight.js, and do not set the OnError property to an error handling function, the default error handling function, default_error_handler, is used. For more information on setting this event during plug-in initialization, see Using CreateSilverlight.js and Silverlight.js.

For more information on Silverlight errors and error handling, see Silverlight Error Handling.

Applies To

Silverlight Plug-in

See Also

Using a Silverlight Plug-in, Using CreateSilverlight.js and Silverlight.js, Silverlight Error Handling


OnFullScreenChange Event

Occurs whenever the FullScreen property of the Silverlight plug-in changes.

Scripting (Instantiation) | Cannot add handlers during instantiation
Scripting (Runtime) | silverlightObject.onFullScreenChange = functionName

Event Handler Parameters

sender | object Identifies the object that invoked the event (the Silverlight plug-in).
eventArgs | object This parameter is always set to null.

Event Information

The OnFullScreenChange event occurs whenever the Silverlight plug-in changes between embedded mode and full-screen mode:

  • embedded mode: plug-in displays within the Web browser.
  • full-screen mode: plug-in displays on top of all other applications.

Remarks

When the Silverlight plug-in displays in embedded mode, the plug-in is contained within the browser window. When the Silverlight plug-in displays in full-screen mode, the plug-in resizes to the current resolution of the display and overlays all other applications, including the browser. The following images show the differences between embedded mode and full-screen mode:

Embedded mode and full-screen mode

Silverlight plug-in displaying as embedded and full-screen mode

Note Silverlight does not support automatic layout of elements. This means that applications have to provide logic to resize themselves appropriately when the plugin's size changes.

Examples

The following JavaScript example shows how to define a OnFullScreenChange event for a Silverlight plug-in.

JavaScript
var plugin;

function onLoaded(sender, args)
{
    // Retrieve a reference to the plug-in.
    plugin = sender.getHost();

    // Set the event handler function for the OnFullScreenChange event.
    plugin.content.onFullScreenChange = onFullScreenChanged;

    // Do initial layout of the app based on initial size.
    updateLayout(plugin.content.actualWidth, plugin.content.actualHeight);
}

function onFullScreenChanged(sender, eventArgs)
{
    // Do layout resizing of the app whenever the FullScreen property changes.
    updateLayout(plugin.content.actualWidth, plugin.content.actualHeight);
}

// Resize and reposition application elements.
function updateLayout(width, height)
{
    // Perform layout tasks based on width and height.
}

Applies To

Silverlight Plug-in

See Also

ActualHeight, ActualWidth, OnResize, Silverlight Full Screen Support, Resizing a Silverlight Plug-in


OnLoad Event

Occurs when the Silverlight plug-in has loaded.

Scripting (Instantiation) | Silverlight.CreateObject(,,,,{onLoad:functionName}) -or- Silverlight.CreateObjectEx({events:{onLoad:functionName}})
Scripting (Runtime) | Cannot be raised in scripting, and cannot attach handlers for this event after initialization.

Event Handler Parameters (for Silverlight.js function onLoad parameters)

sender | object Identifies the Silverlight plug-in that invoked the event.
context | object User-specified context object, can be used to distinguish which instance of a Silverlight plug-in raised the event.
source | object Root element of XAML content that was loaded.

Event Information

The OnLoad event occurs after the XAML content in the Silverlight plug-in has completely loaded. The OnLoad event cannot have handlers attached after plug-in initialization.

Remarks

Note Generally, it is not advisable to attempt to make sizing decisions within the event handler of this event. This is because the actualHeight/actualWidth values of the Silverlight plug-in are not guaranteed to be set at the time the OnLoad event fires. Instead, you should use OnResize. OnResize fires whenever the ActualHeight or ActualWidth properties change including when the plug-in first loads.

The OnLoad event occurs after any Loaded event for a UIElement-derived class, such as Canvas, TextBlock, or Rectangle. The read-only IsLoaded property, which is set before the Onload event occurs, indicates whether the Silverlight plug-in is loaded.

The onLoad event that you can add handlers for within the Silverlight.js file (e.g. when using Silverlight.createObject), wraps an underlying onLoad event that is defined at the level of the plug-in object model. The plug-in exposed event uses a different event handler signature, passing only the sender. You generally do not deal with the plug-in version of the onLoad event. The signature shown in the Event Handler Parameters section is the Silverlight.js version, which is how you generally attach handlers for this event. The Silverlight.js version of onLoad event handling expands on the plug-in exposed onLoad event handling in the following ways:

  • If there are several plug-in instances hosted in an HTML page, there is potential for confusion in event handlers about which instance was loaded. The CreateObject/CreateObjectEx functions in Silverlight.js add an optional context parameter for initialization. Typically this is set to a unique string. That context value is passed back as an event handler parameter, making it much simpler to write handler logic that can detect which plug-in's onLoad event is being handled at that time.
  • Rather than the generic sender object, the Silverlight.js version of onLoad passes the actual Silverlight plug-in instance as the first event handler parameter value. This saves you a call to sender.GetHost(), and you can store the return value as a variable in script for easy access to the Silverlight plug-in instance.

See Using the OnLoad Event for more information.

Applies To

Silverlight Plug-in

See Also

Using CreateSilverlight.js and Silverlight.js, IsLoaded, Loaded


OnResize Event

Occurs whenever the ActualHeight or ActualWidth property of the Silverlight plug-in changes.

Scripting (Instantiation) | Cannot add handlers during instantiation
Scripting (Runtime) | silverlightObject.onResize = functionName

Event Handler Parameters

sender | object Identifies the object that invoked the event (the Silverlight plug-in).
eventArgs | object This parameter is always set to null.

Event Information

The OnResize event occurs whenever the Silverlight plug-in changes its ActualHeight or ActualWidth property when in embedded mode. When the Silverlight plug-in is in full-screen mode, the OnResize event does not occur:

  • embedded mode: plugin displays within the Web browser.
  • full-screen mode: plugin displays on top of all other applications.

Remarks

If a change in size of the Silverlight plug-in triggers the OnFullScreenChange event, the OnResize event does not occur. In addition, the OnResize event does not occur when the Silverlight plug-in is in full-screen mode.

Note Silverlight does not support automatic layout of elements. This means that applications have to provide logic to resize themselves appropriately when the plug-in's size changes.

Note Use this event to make sizing decisions rather than OnLoad. This is because the actualHeight/actualWidth values of the Silverlight plug-in are not guaranteed to be set at the time the OnLoad event fires. OnResize fires whenever the ActualHeight or ActualWidth properties change including when the plug-in first loads.

Examples

The following JavaScript example shows how to define a OnResize event for a Silverlight plug-in.

JavaScript
var plugin;

function onLoaded(sender, args)
{
    // Retrieve a reference to the plug-in.
    var slPlugin = sender.getHost();
    // Set the event handler function to the OnResize event.
    slPlugin.content.onResize = onResized;

    // Do initial layout of the app based on initial size.
    updateLayout(slPlugin.content.actualWidth, slPlugin.content.actualHeight);
}

function onResized(sender, eventArgs)
{
    // Do layout resizing of the app whenever the plug-in actualwidth or actualheight changes.
    updateLayout(slPlugin.content.actualWidth, slPlugin.content.actualHeight);
}

// Resize and reposition application elements.
function updateLayout(width, height)
{
    // Perform layout tasks based on width and height.
}

Applies To

Silverlight Plug-in

See Also

ActualHeight, ActualWidth, OnFullScreenChange, Resizing a Silverlight Plug-in, Silverlight Full-screen Support


PerformAction Event

Occurs when the accessibility technology invokes an action.

XAML | Cannot be used in XAML.
Scripting | [token = ]object.AddEventListener("PerformAction", eventhandlerFunction)

AddEventListener Parameters

token | integer A token that is returned from the function, which you can optionally retain as a variable. If you intend to call RemoveEventListener to remove the handler, you will need this token.
eventhandlerFunction | object The name of your event handler function as it is defined in script. Quotes around the function name are not required. See Remarks.

Event Handler Parameters

sender | object Identifies the object that invoked the event.
eventArgs | object This parameter is always set to null.

Remarks

You can also add handlers in script using a quoted string for the event handler name:

object.addEventListener("PerformAction", "eventhandlerFunction")
This syntax also returns a token; however, the token is not an absolute requirement for removing the handler, in cases where the handler was added by using a quoted string. For details, see RemoveEventListener.

Applies To

Accessibility

See Also


Silverlight Enumerations

This section contains a list of the enumerations exposed by the Silverlight Object Model.

Enumerations

AlignmentX

AlignmentY

BrushMappingMode

ColorInterpolationMode

DeviceType

ErrorType

FillBehavior

FillRule

FontStretch

FontStyle

FontWeight

GradientSpreadMethod

Key

MediaState

MouseCursor

PenLineCap

PenLineJoin

Stretch

StyleSimulations

SweepDirection

TextDecorations

TextWrapping

Visibility

See Also

Silverlight Reference, Silverlight Conceptual Topics


AlignmentX Enumeration

Describes how content is positioned horizontally in a container.

XAML | <object property="EnumerationValue" .../>
Scripting | value = "EnumerationValue"

Enumeration Values

Value | Description
Left | Content is horizontally aligned with the left side of the container.
Center | Content is centered horizontally in the container.
Right | Content is horizontally aligned with the right side of the container.

Remarks

AlignmentX specifies the horizontal alignment of the object.

Applies To

AlignmentX (ImageBrush)


AlignmentY Enumeration

Describes how content is positioned vertically in a container.

XAML | <object property="EnumerationValue" .../>
Scripting | value = "EnumerationValue"

Enumeration Values

Value | Description
Top | Content is vertically aligned with the top of the container.
Center | Content is centered vertically in the container.
Bottom | Content is vertically aligned with the bottom of the container.

Remarks

AlignmentY specifies the vertical alignment of the object in a container.

Applies To

AlignmentY (ImageBrush)


BrushMappingMode Enumeration

Specifies the coordinate system used by a Brush.

XAML | <object property="EnumerationValue" .../>
Scripting | value = "EnumerationValue"

Enumeration Values

Value | Description
Absolute | The coordinate system is not relative to a bounding box. Values are interpreted directly in local space.
RelativeToBoundingBox | The coordinate system is relative to a bounding box: 0 indicates 0 percent of the bounding box and 1 indicates 100 percent of the bounding box. For example, (0.5, 0.5) describes a point in the middle of the bounding box, and (1, 1) describes a point at the bottom right of the bounding box.

Remarks

Note that the bounding box for the RelativeToBoundingBox value depends on the property with which this enumeration is used.

Applies To

MappingMode (LinearGradientBrush), MappingMode (RadialGradientBrush)


ColorInterpolationMode Enumeration

Determines how the colors in a gradient are interpolated.

XAML | <object property="EnumerationValue" .../>
Scripting | value = "EnumerationValue"

Enumeration Values

Value | Description
ScRgbLinearInterpolation | Colors are interpolated in the scRGB color space.
SRgbLinearInterpolation | Colors are interpolated in the sRGB color space.

Applies To

ColorInterpolationMode (LinearGradientBrush), ColorInterpolationMode (RadialGradientBrush)


DeviceType Enumeration

Specifies the basic classes of pointing devices supported.

XAML | Cannot be used in XAML.
Scripting | value = "EnumerationValue"

Enumeration Values

Value | Description
Mouse | The device is being represented as a mouse. The device is a mouse or stylus that's not using the pen service (wisptis.exe).
Stylus | The device is a stylus that is hooked up to the pen service (wisptis.exe).
Touch | The device is a touch digitizer that is hooked up to the pen service (wisptis.exe).

Examples

The following JavaScript example demonstrates how to display the type of device that was used to create the current StylusPoint.

JavaScript
// Capture mouse movement when the left button is pressed and create the stroke
function InkPresenterMouseDown(sender,args)
{
  // Display the Type of input device in a TextBlock
  device.Text = args.GetStylusInfo().deviceType;

  inkPresenter.CaptureMouse();
  newStroke = agCtrl.content.createFromXaml('<Stroke/>');

  newStroke.StylusPoints.AddStylusPoints(args.GetStylusPoints(inkPresenter));
  inkPresenter.Strokes.Add(newStroke);
}

Applies To

DeviceType (StylusInfo)

See Also

Ink Support In Microsoft Silverlight


ErrorType Enumeration

Describes the possible types of errors.

XAML | <objectproperty="EnumerationValue" .../>
Scripting | value = "EnumerationValue"

Enumeration Values

Value | Description
NoError | No error.
UnknownError | Error is unknwon.
InitializeError | Error occurred during initalization.
ParserError | Error occurred during the parsing of XAML content, at a level before the object model was incorporated. For example, tag mismatches in XML.
ObjectModelError | Error occurred during the object model mapping of XAML content. For example, a name collision, or a required attribute was missing a value.
RuntimeError | Error occurred in a synchronous method call inside a JavaScript function.
DownloadError | Error occurred during package downloading.
MediaError | Error occurred after a media file failed to load.
ImageError | Error occurred after an image file failed to load.

Examples

The following JavaScript example shows how to create an onError event handler that displays error information specific to the type of error that occurred. The ErrorType property on the ErrorEventArgs is used to determine the type of error.

JavaScript
function OnErrorEventHandler(sender, errorArgs)
{
    // The error message to display.
    var errorMsg = "Silverlight Error: \n\n";

    // Error information common to all errors.
    errorMsg += "Error Type:    " + errorArgs.errorType + "\n";
    errorMsg += "Error Message: " + errorArgs.errorMessage + "\n";
    errorMsg += "Error Code:    " + errorArgs.errorCode + "\n";

    // Determine the type of error and add specific error information.
    switch(errorArgs.errorType)
    {
        case "RuntimeError":
            // Display properties specific to RuntimeErrorEventArgs.
            if (errorArgs.lineNumber != 0)
            {
                errorMsg += "Line: " + errorArgs.lineNumber + "\n";
                errorMsg += "Position: " +  errorArgs.charPosition + "\n";
            }
            errorMsg += "MethodName: " + errorArgs.methodName + "\n";
            break;
        case "ParserError":
            // Display properties specific to ParserErrorEventArgs.
            errorMsg += "Xaml File:      " + errorArgs.xamlFile      + "\n";
            errorMsg += "Xml Element:    " + errorArgs.xmlElement    + "\n";
            errorMsg += "Xml Attribute:  " + errorArgs.xmlAttribute  + "\n";
            errorMsg += "Line:           " + errorArgs.lineNumber    + "\n";
            errorMsg += "Position:       " + errorArgs.charPosition  + "\n";
            break;
        default:
            break;
    }
    // Display the error message.
    alert(errorMsg);
}

Applies To

ErrorType

See Also

Silverlight Application Scripting Error Handling, ErrorEventArgs, ParserErrorEventArgs, RuntimeErrorEventArgs


FillBehavior Enumeration

Specifies how a Timeline behaves when it is outside its active period but its parent is inside its active or hold period.

XAML | <object property="EnumerationValue" .../>
Scripting | value = "EnumerationValue"

Enumeration Values

Value | Description
HoldEnd | After it reaches the end of its active period, the timeline holds its progress until the end of its parent's active and hold periods.
Stop | The timeline stops if it is outside its active period while its parent is inside its active period.

Applies To

FillBehavior Property

See Also

Animation Overview


FillRule Enumeration

Specifies how the intersecting areas of PathFigure objects contained in a Geometry are combined to form the area of the Geometry.

XAML | <object property="EnumerationValue" .../>
Scripting | value = FillRule.EnumerationValue

Enumeration Values

Value | Description
EvenOdd | Rule that determines whether a point is in the fill region by drawing a ray from that point to infinity in any direction and counting the number of path segments within the given shape that the ray crosses. If this number is odd, the point is inside; if even, the point is outside.
Nonzero | Rule that determines whether a point is in the fill region of the path by drawing a ray from that point to infinity in any direction and then examining the places where a segment of the shape crosses the ray. Starting with a count of zero, add one each time a segment crosses the ray from left to right and subtract one each time a path segment crosses the ray from right to left. After counting the crossings, if the result is zero then the point is outside the path. Otherwise, it is inside.

Applies To

FillRule (Geometry), FillRule (Polygon), FillRule (Polyline)


FontStretch Enumeration

Describes the degree to which a font has been stretched compared to the normal aspect ratio of that font.

XAML | <object property="EnumerationValue" .../>
Scripting | value = "EnumerationValue"

Enumeration Values

Value | usWidthClass | % of normal
UltraCondensed | 1 | 50.0%
ExtraCondensed | 2 | 62.5%
Condensed | 3 | 75.0%
SemiCondensed | 4 | 87.5%
Normal | 5 | 100.0%
Medium | 5 | 100.0%
SemiExpanded | 6 | 112.5%
Expanded | 7 | 125.0%
ExtraExpanded | 8 | 150.0%
UltraExpanded | 9 | 200.0%

For more information on the OpenType usWidthClass value, see the "Font File Tables" section of the OpenType specification.

Applies To

FontStretch Property

See Also

FontFamily, FontSize, FontStyle, FontStyle, LineBreak, Run, TextBlock


FontStyle Enumeration

Decscribes the possible font styles.

XAML | <object property="EnumerationValue" .../>
Scripting | value = "EnumerationValue"

Enumeration Values

Value | Description
Normal | The characters in a normal, or roman font, are upright.
Italic | The characters in an italic font are truly slanted and appear as they were designed.

Applies To

FontStyle Property

See Also

FontFamily, FontSize FontWeight, LineBreak, Run, TextBlock


FontWeight Enumeration

Defines the possible densities of a typeface, in terms of the lightness or heaviness of the strokes.

XAML | <object property="EnumerationValue" .../>
Scripting | value = "EnumerationValue"

Enumeration Values

Value | usWeightClass
Thin | 100
ExtraLight | 200
Light | 300
Normal | 400
Medium | 500
SemiBold | 600
Bold | 700
ExtraBold | 800
Black | 900
ExtraBlack | 950

Applies To

FontWeight Property

See Also

FontFamily, FontSize, FontStyle, LineBreak, Run, TextBlock


GradientSpreadMethod Enumeration

Specifies how to draw the gradient outside a gradient brush's gradient vector or space.

XAML | <object property="EnumerationValue" .../>
Scripting | value = "EnumerationValue"

Enumeration Values

Value | Description
Pad | The color values at the ends of the gradient vector fill the remaining space.
Reflect | The gradient is repeated in the reverse direction until the space is filled.
Repeat | The gradient is repeated in the original direction until the space is filled.

Remarks

The following illustration shows the available spread methods and their effect on LinearGradientBrush and RadialGradientBrush. The red line indicates the gradient space. A LinearGradientBrush defines its gradient space with its StartPoint and EndPoint properties. A RadialGradientBrush defines its gradient space with its Center, RadiusX, and RadiusY properties.

Different GradientSpread settings

Applies To

SpreadMethod (LinearGradientBrush), SpreadMethod (RadialGradientBrush)

See Also

LinearGradientBrush, RadialGradientBrush


Key Enumeration

Specifies the portable key code that is not specific to an operating system.

XAML | Cannot be used in XAML.
Scripting | value = "EnumerationValue"

Enumeration Values

Key | Decimal Value | Hexadecimal Value
KEYNONE | 0 | 0
BACKSPACE | 1 | 1
TAB | 2 | 2
ENTER | 3 | 3
SHIFT | 4 | 4
CTRL | 5 | 5
ALT | 6 | 6
CAPSLOCK | 7 | 7
ESCAPE | 8 | 8
SPACE | 9 | 9
PAGEUP | 10 | A
PAGEDOWN | 11 | B
END | 12 | C
HOME | 13 | D
LEFT | 14 | E
UP | 15 | F
RIGHT | 16 | 10
DOWN | 17 | 11
INSERT | 18 | 12
DELETE | 19 | 13
DIGIT0 | 20 | 14
DIGIT1 | 21 | 15
DIGIT2 | 22 | 16
DIGIT3 | 23 | 17
DIGIT4 | 24 | 18
DIGIT5 | 25 | 19
DIGIT6 | 26 | 1A
DIGIT7 | 27 | 1B
DIGIT8 | 28 | 1C
DIGIT9 | 29 | 1D
A | 30 | 1E
B | 31 | 1F
C | 32 | 20
D | 33 | 21
E | 34 | 22
F | 35 | 23
G | 36 | 24
H | 37 | 25
I | 38 | 26
J | 39 | 27
K | 40 | 28
L | 41 | 29
M | 42 | 2A
N | 43 | 2B
O | 44 | 2C
P | 45 | 2D
Q | 46 | 2E
R | 47 | 2F
S | 48 | 30
T | 49 | 31
U | 50 | 32
V | 51 | 33
W | 52 | 34
X | 53 | 35
Y | 54 | 36
Z | 55 | 37
F1 | 56 | 38
F2 | 57 | 39
F3 | 58 | 3A
F4 | 59 | 3B
F5 | 60 | 3C
F6 | 61 | 3D
F7 | 62 | 3E
F8 | 63 | 3F
F9 | 64 | 40
F10 | 65 | 41
F11 | 66 | 42
F12 | 67 | 43
NUMPAD0 | 68 | 44
NUMPAD1 | 69 | 45
NUMPAD2 | 70 | 46
NUMPAD3 | 71 | 47
NUMPAD4 | 72 | 48
NUMPAD5 | 73 | 49
NUMPAD6 | 74 | 4A
NUMPAD7 | 75 | 4B
NUMPAD8 | 76 | 4C
NUMPAD9 | 77 | 4D
MULTIPLY | 78 | 4E
ADD | 79 | 4F
SUBTRACT | 80 | 50
DECIMAL | 81 | 51
DIVIDE | 82 | 52
KEYUNKNOWN | 255 | FF

Remarks

The keyEventArgs parameter of the KeyDown and KeyUp events provides both a Key value and a PlatformKeyCode value:

  • Key: a portable key code that is not operating system-specific.
  • PlatformKeyCode: a non-portable key code that is operating system-specific.

The portable key codes are a common subset of all the possible key codes of the supported operating systems, in this case, Macintosh and Microsoft Windows. For example, the keystroke 'v' is represented as a Key value of 51, and a PlatformKeyCode value of 86. Certain keystrokes, however, are not portable, such as the Windows SCROLL LOCK key. In this case, the Key value is 255, which is the value for an unknown key, and the PlatformKeyCode is 145 on a Windows platform. For information on Windows-specific key codes, see Virtual Key Codes. For information on Macintosh-specific key codes, see Keyboard Layout Services Reference.

Applies To

Key, PlatformKeyCode

See Also

KeyDown, KeyUp, Silverlight Keyboard Support


MediaState Enumeration

Defines the potential states of a MediaElement.

XAML | <objectproperty="EnumerationValue" .../>
Scripting | value = "EnumerationValue"

Enumeration Values

Value | Description
Buffering | The MediaElement is loading the media for playback. Its Position does not advance during this state. If the MediaElement was already playing video, it continues to display the last displayed frame.
Closed | The MediaElement contains no media. The MediaElement displays a transparent frame.
Error | The MediaElement encountered an error during media playback. If the MediaElement was playing video, it continues to display the last displayed frame. This MediaElement changes to this state after raising the MediaFailed event.
Opening | The MediaElement is validating and attempting to open the Uri specified by its Source property. While in this state, the MediaElement queues any Play, Pause, or Stop commands it receives and processes them if the media is successfully opened.
Paused | The MediaElement does not advance its Position. If the MediaElement was playing video, it continues to display the current frame.
Playing | The MediaElement is playing the media specified by its source property. Its Position advances forward.
Stopped | The MediaElement contains media but is not playing or paused. Its Position is 0 and does not advance. If the loaded media is video, the MediaElement displays the first frame.

Examples

The following example demonstrates one way to display the CurrentState of a MediaElement. It creates a MediaElement and several buttons for controlling media playback. To display the current state of the MediaElement, the example registers for the CurrentStateChanged event and uses an event handler to update a TextBlock.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Width="300" Height="300">

  <MediaElement
    x:Name="media"
    Source="xbox.wmv"
    CurrentStateChanged="media_state_changed"
    Width="300" Height="300"/>

  <!-- Stops media playback.-->
  <Canvas MouseLeftButtonDown="media_stop"
    Canvas.Left="10" Canvas.Top="265">
    <Rectangle Stroke="Black"
      Height="30" Width="55" RadiusX="5" RadiusY="5">
      <Rectangle.Fill>
        <RadialGradientBrush GradientOrigin="0.75,0.25">
          <GradientStop Color="Orange" Offset="0.0" />
          <GradientStop Color="Red" Offset="1.0" />
        </RadialGradientBrush>
      </Rectangle.Fill>
    </Rectangle>
    <TextBlock Canvas.Left="5" Canvas.Top="5">stop</TextBlock>
  </Canvas>

  <!-- Pauses media playback. -->
  <Canvas MouseLeftButtonDown="media_pause"
    Canvas.Left="70" Canvas.Top="265">
    <Rectangle Stroke="Black"
      Height="30" Width="55" RadiusX="5" RadiusY="5">
      <Rectangle.Fill>
        <RadialGradientBrush GradientOrigin="0.75,0.25">
          <GradientStop Color="Yellow" Offset="0.0" />
          <GradientStop Color="Orange" Offset="1.0" />
        </RadialGradientBrush>
      </Rectangle.Fill>
    </Rectangle>
    <TextBlock Canvas.Left="5" Canvas.Top="5">pause</TextBlock>
  </Canvas>

  <!-- Begins media playback. -->
  <Canvas MouseLeftButtonDown="media_begin"
    Canvas.Left="130" Canvas.Top="265">
    <Rectangle Stroke="Black" RadiusX="5" RadiusY="5"
      Height="30" Width="55">
      <Rectangle.Fill>
        <RadialGradientBrush GradientOrigin="0.75,0.25">
          <GradientStop Color="LimeGreen" Offset="0.0" />
          <GradientStop Color="Green" Offset="1.0" />
        </RadialGradientBrush>
      </Rectangle.Fill>
    </Rectangle>
    <TextBlock Canvas.Left="5" Canvas.Top="5">play</TextBlock>
  </Canvas>

  <TextBlock
    Canvas.Left="190" Canvas.Top="265"
    FontSize="12">CurrentState:</TextBlock>

  <TextBlock
    x:Name="mediaStateTextBlock"
    Canvas.Left="190" Canvas.Top="280"
    FontSize="12"></TextBlock>

</Canvas>
JavaScript
function media_stop(sender, args)
{
    sender.findName("media").stop();
}

function media_pause(sender, args)
{
    sender.findName("media").pause();
}

function media_begin(sender, args)
{
    sender.findName("media").play();
}

function media_state_changed(sender, args)
{
    var mediaStateTextBlock =
    sender.findName("mediaStateTextBlock");
    var media = sender.findName("media");
    mediaStateTextBlock.Text = media.CurrentState;
}

Applies To

CurrentState

See Also

CurrentState, CurrentStateChanged


MouseCursor Enumeration

Specifies the image used to represent the mouse pointer.

XAML | <object property="EnumerationValue" .../>
Scripting | value = "EnumerationValue"

Enumeration Values

Value | Description
Default | Specifies that an element expresses no cursor preference. If the element's parent specifies a cursor, that cursor is displayed.
Arrow | An arrow cursor. This is typically the default cursor. The Arrow cursor
Hand | A hand cursor. This cursor typically indicates that the pointer is over a link. The Hand cursor.
Wait | A wait (or hourglass) cursor. This cursor typically indicates that the runtime is busy performing an operation. The Wait cursor.
IBeam | An I-beam cursor. This cursor typically indicates that text can be manipulated or selected. The I-beam cursor.
Stylus | A stylus cursor. This cursor typically indicates that pen input is being captured. The Stylus cursor.
Eraser | An eraser cursor. This cursor typically indicates that previous pen input is being deliberately erased. The eraser cursor.
None | No cursor. No cursor.

Applies To

Cursor Property


PenlineCap Enumeration

Describes the shape at the end of a line or segment.

XAML | <object property="EnumerationValue" .../>
Scripting | value = "EnumerationValue"

Enumeration Values

Value | Description
Flat | A cap that does not extend past the last point of the line. Comparable to no line cap.
Square | A rectangle that has a height equal to the line thickness and a length equal to half the line thickness.
Round | A semicircle that has a diameter equal to the line thickness.
Triangle | An isosceles right triangle whose base length is equal to the thickness of the line.

Remarks

The following illustration shows the available cap styles for lines or segments. The red portion of the line shows the extra area added by the line cap setting.

Applies To

StrokeDashCap, StrokeEndLineCap, StrokeStartLineCap

See Also

Shape, Ellipse, Line, Path, Polygon, Polyline, Rectangle


PenLineJoin Enumeration

Describes the shape that joins two lines or segments.

XAML | <object property="EnumerationValue" .../>
Scripting | value = "EnumerationValue"

Enumeration Values

Value | Description
Miter | Regular angular vertices.
Bevel | Beveled vertices.
Round | Rounded vertices.

Remarks

The following illustration shows the different line joins.

Applies To

StrokeLineJoin

See Also

Shape, Ellipse, Line, Path, Polygon, Polyline, Rectangle


SytleSimulations Enumeration

Describes the simulation style of a font.

XAML | <object property="EnumerationValue" .../>
Scripting | value = "EnumerationValue"

Enumeration Values

Value | Description
None | No font style simulation.

Applies To

StyleSimulations

See Also

Glyphs


SweepDirection Enumeration

Defines the direction an elliptical arc is drawn.

XAML | <object property="EnumerationValue" .../>
Scripting | value = "EnumerationValue"

Enumeration Values

Value | Description
Clockwise | Specifies that arcs are drawn in a clockwise (positive-angle) direction.
CounterClockwise | Specifies that arcs are drawn in a counter clockwise (negative-angle) direction.

Applies To

SweepDirection Property

See Also

ArcSegment


TextDecorations Enumeration

Describes the possible text decorations.

XAML | <object property="EnumerationValue" .../>
Scripting | value = "EnumerationValue"

Enumeration Values

Value | Description
None | No text decoration is specified.
Underline | The characters are displayed with an underline.

Applies To

TextDecorations Property

See Also

TextBlock, Run


TextWrapping Enumeration

Specifies whether text wraps when it reaches the edge of the containing box.

XAML | <object property="EnumerationValue" .../>
Scripting | value = "EnumerationValue"

Enumeration Values

Value | Description
NoWrap | No line wrapping is performed.
Wrap | Line-breaking occurs if the line overflows beyond the available block width, even if the standard line breaking algorithm cannot determine any line break opportunity, as in the case of a very long word constrained in a fixed-width container with no scrolling allowed.

Applies To

TextWrapping Property

See Also

TextBlock


Visibility Enumeration

Specifies the display state of an element.

XAML | <object property="EnumerationValue" .../>
Scripting | value = "EnumerationValue"

Enumeration Values

Value | Description
Collapsed | Do not display the element, and do not reserve space for it in layout.
Visible | Display the element.

Remarks

Elements that have a Visibility value of Collapsed do not occupy any layout space. By default, elements are Visible.

Applies To

UIElement

See Also

Silverlight Enumerations


Host Interfaces for Silverlight ActiveX Control for Windows Version 1.0

Structures and Enumerations

XcpHostOptions

XcpHostOptions

Specifies runtime options that are applied against the hosted Silverlight control when an instance is created.

Syntax

typedef enum XcpHostOptions{
  XcpHostOption_FreezeOnInitialFrame  =0x01,
  XcpHostOption_DisableFullScreen  =0x02,
  XcpHostOption_DisableManagedExecution  =0x08,
  XcpHostOption_EnableCrossDomainDownloads  =0x10
};

Members

XcpHostOption_FreezeOnInitialFrame
Animation timelines do not progress even if triggered (this implicitly stops AutoPlay videos also). Normal UI painting, initial downloads, and other time-dependent client operations will still proceed as normal.
XcpHostOption_DisableFullScreen
Calls to APIs that attempt to run the Silverlight plugin in full-screen mode will silently fail.
XcpHostOption_DisableManagedExecution
Not implemented, do not use.
XcpHostOption_EnableCrossDomainDownloads
Hosts are generally operating from an assumed full trust, whereas the browser-hosted trust is more restricted. Setting this option allows a host to enable downloads using paths that are normally blocked by a browser-hosted plugin, such as FILE, mixed HTTP/HTTPS, etc.

Visual C++ Reference

IXcpControl
IXcpControlDownloadCallback
IXcpControlEvents
IXcpControlHost
IXcpObject Interface

IXcpControl Interface

Creates a Silverlight control, and exposes the parameters that are available to its HTML scripting CreateObject method.
In addition to the methods inherited from IDispatch, the IXcpControl interface exposes the following methods.
CreateObject
get_Content
get_InitParams
get_IsLoaded
get_OnError
get_OnLoad
get_Settings
get_Source
put_InitParams
put_OnError
put_OnLoad
put_Source

Remarks

All methods of this interface are exposed to scripting, and specific implementation details are often documented in the equivalent script reference.

IXcpControl::CreateObject

Creates a new instance of a Silverlight helper object.

Syntax

HRESULT CreateObject(
  BSTR  id,
  IXcpObject**  ppDisp
);

Parameters

id
[in] Specifies the type of control to create.
ppDisp
[out] Pointer to a pointer to the resulting control.

Return Values

The method returns an HRESULT.

Remarks

See CreateObject. The only supported control is Downloader.

See Also

  • IXcpControl Interface

IXcpControl::get_Content

Gets the content sub-object.

Syntax

HRESULT get_Content(
  IDispatch**  pContent
);

Parameters

pContent
[out] Pointer to the content sub-object.

Return Values

The method returns an HRESULT.

Remarks

See documentation for OnFullScreenChange, OnResize, CreateFromXaml, CreateFromXamlDownloader, FindName, ActualHeight, ActualWidth, FullScreen.

See Also

  • IXcpControl Interface

IXcpControl::get_InitParams

Retrieves any previously specified user-defined initialization parameters.

Syntax

HRESULT get_InitParams(
  BSTR*  initparams
);

Parameters

initparams
[out] A comma delimited string of initialization tokens.

Return Values

The method returns an HRESULT.

See Also

  • IXcpControl Interface
  • put_InitParams
  • InitParams

IXcpControl::get_IsLoaded

Retrieves a Boolean that declares whether the control's onLoad event has been raised.

Syntax

HRESULT get_IsLoaded(
  VARIANT_BOOL*  pb
);

Parameters

pb
[out] true if the control has raised its onLoad event; otherwise, false.

Return Values

The method returns an HRESULT.

See Also

  • IXcpControl Interface

IXcpControl::get_OnError

Retrieves the name of a specified scripting handler method that can process any control-specific script level errors raised by the control.

Syntax

HRESULT get_OnError(
  BSTR*  phandler
);

Parameters

phandler
[out] The name of the user-defined script handler.

Return Values

The method returns an HRESULT.

See Also

  • IXcpControl Interface
  • put_OnError

IXcpControl::get_OnLoad

Retrieves the name of a specified scripting handler method that will execute when the onLoad event is raised by the control.

Syntax

HRESULT get_OnLoad(
  BSTR*  phandler
);

Parameters

phandler
[out] The name of the user-defined script handler.

Return Values

The method returns an HRESULT.

See Also

  • IXcpControl Interface
  • put_OnLoad

IXcpControl::get_Settings

Retrieves settings from the browser.

Syntax

HRESULT get_Settings(
  IDispatch**  pSettings
);

Parameters

pSettings
[out] Pointer to a sub-object containing the plugin settings. See documentation for Background, EnableFramerateCounter, EnableHtmlAccess, EnableRedrawRegions, MaxFrameRate, Windowless.

Return Values

The method returns an HRESULT.

See Also

  • IXcpControl Interface
  • Using CreateSilverlight.js and Silverlight.js

IXcpControl::get_Source

Retrieves the URI specified for the source XAML.

Syntax

HRESULT get_Source(
  BSTR*  pstr
);

Parameters

pstr
[out] The URI specified for the source XAML.

Return Values

The method returns an HRESULT.

See Also

  • IXcpControl Interface
  • put_Source
  • put_Source
  • Source

IXcpControl::put_InitParams

Specifies user-defined initialization parameters.

Syntax

HRESULT put_InitParams(
  BSTR  initparams
);

Parameters

initparams
[in] A comma delimited string of initialization parameters.

Return Values

The method returns an HRESULT.

See Also

  • get_InitParams
  • IXcpControl Interface
  • InitParams

IXcpControl::put_OnError

Specifies the name of a scripting handler method that can process any control-specific script level errors raised by the control.

Syntax

HRESULT put_OnError(
  BSTR  handler
);

Parameters

handler
[in] The name of a scripting handler method.

Return Values

The method returns an HRESULT.

See Also

  • get_OnError
  • IXcpControl Interface
  • OnError

IXcpControl::put_OnLoad

Specifies the name of a scripting handler method that will execute when the onLoad event is raised by the control.

Syntax

HRESULT put_OnLoad(
  BSTR  handler
);

Parameters

handler
[in] The name of a scripting handler method.

Return Values

The method returns an HRESULT.

See Also

  • get_OnLoad
  • IXcpControl Interface
  • OnLoad

IXcpControl::put_Source

Specifies the URI to use for the source XAML.

Syntax

HRESULT put_Source(
  BSTR  str
);

Parameters

str
[in] The URI to use for the source XAML.

Return Values

The method returns an HRESULT.

See Also

  • get_Source
  • IXcpControl Interface

IXcpControlDownloadCallback Interface

Implemented by the hosted control to provide a particular DownloadUrl behavior.
In addition to the methods inherited from IUnknown, the IXcpControlDownloadCallback interface exposes the following methods.
OnUrlDownloaded

IXcpControlDownloadCallback::OnUrlDownloaded

Provides a control-implemented callback that should be used for cases where the host wants to process download requests.

Syntax

HRESULT OnUrlDownloaded(
  HRESULT  hr,
  IStream*  pStream
);

Parameters

hr
The HRESULT from DownloadURL.
pStream
Pointer to a stream object.

Return Values

The method returns an HRESULT.

Remarks

For cases where the host's DownloadURL implementation returns E_PENDING, call this method from the retrieved interface and pass the end result download stream to pStream to complete the download cycle..

See Also

  • IXcpControlDownloadCallback Interface

IXcpControlEvents Interface

Provides a method that returns error results to the host. Other methods are deprecated.
In addition to the methods inherited from IDispatch, the IXcpControlEvents interface exposes the following methods.
Error
Pause
Resume
Start
Stop

IXcpControlEvents::Error

Reports error results that originate from the host plugin to the host.

Syntax

HRESULT Error(
  long  line,
  long  column,
  long  HResult,
  BSTR  ErrorString
);

Parameters

line
[in] Line of the error.
column
[in] Column of the error.
HResult
[in] HRESULT from the error.
ErrorString
[in] Descriptive error string.

Return Values

The method returns an HRESULT.

See Also

  • IXcpControlEvents Interface

IXcpControlEvents::Pause

Deprecated, do not use.

Syntax

HRESULT Pause();

IXcpControlEvents::Resume

Deprecated, do not use.

Syntax

HRESULT Resume();

IXcpControlEvents::Start

Deprecated, do not use.

Syntax

HRESULT Start();

IXcpControlEvents::Stop

Deprecated, do not use.

Syntax

HRESULT Stop();

IXcpControlHost Interface

The hosted control queries for the IXcpControlHost interface whenever it is created. Hosts should implement the IXcpControlHost interface to provide hooks that the hosted control will use to modify its behavior when it is hosted by that particular host.
In addition to the methods inherited from IUnknown, the IXcpControlHost interface exposes the following methods.
DownloadUrl
GetBaseUrl
GetHostOptions
GetNamedSource
InvokeHandler
NotifyError
NotifyLoaded

IXcpControlHost::DownloadUrl

Called by the hosted control whenever a download is requested. Hosts should implement this method to provide specialized download behavior for cases where the download might request cross-domain URLs.

Syntax

HRESULT DownloadUrl(
  BSTR  bstrUrl,
  IXcpControlDownloadCallback*  pCallback,
  IStream**  ppStream
);

Parameters

bstrUrl
[in] The url to download.
pCallback
[in] Pointer to the downloader callback implementation.
ppStream
[out] Pointer to a pointer to a stream object.

Return Values

The method returns an HRESULT. HRESULTs have the following meaning to the hosted control:
S_OK
The method succeeded. Content is returned in the stream.
S_FALSE
Always use the hosted control's inherent downloader.
E_FAIL
Do not download any content. The hosted control will raise appropriate errors and events in response to a failed download.
E_PENDING
The host holds on to the callback passed as pCallback, and calls the OnUrlDownloaded method on the callback interface.

Remarks

For the E_PENDING case you should keep a reference to the callback, obtain the stream through your own means (which can be asynchronous), call OnUrlDownloaded on the callback passing that stream, and then release the callback.

See Also

  • IXcpControlHost Interface

IXcpControlHost::GetBaseUrl

Retrieves the URL that the hosted control should use as the base for any relative requests made for Source, to the downloader, etc.

Syntax

HRESULT GetBaseUrl(
  BSTR*  pbstrUrl
);

Parameters

pbstrUrl
[out] Pointer to a string containing the intended base URL.

Return Values

The method returns an HRESULT.

Remarks

Typically, Silverlight URIs are given as relative URIs, because only the MediaElement Source property supports cross-domain references (and that does not involve the downloader directly, only indirectly). This property enables you to change what is considered the base URI from which relative URIs are considered.

See Also

  • IXcpControlHost Interface

IXcpControlHost::GetHostOptions

Retrieves the XcpHostOptions specified by the host.

Syntax

HRESULT GetHostOptions(
  DWORD*  pdwOptions
);

Parameters

pdwOptions
[out] Pointer to a double word containing the XcpHostOptions.

Return Values

The method returns an HRESULT.

See Also

  • IXcpControlHost Interface

IXcpControlHost::GetNamedSource

Retrieves the XAML source for cases where the control uses a Source value specified by ID rather than by file.

Syntax

HRESULT GetNamedSource(
  BSTR  bstrSourceName,
  BSTR*  pbstrSource
);

Parameters

bstrSourceName
[in] The source ID.
pbstrSource
[out] A string containing the complete XAML source.

Return Values

The method returns an HRESULT.

See Also

  • IXcpControlHost Interface

IXcpControlHost::InvokeHandler

Invoked whenever events occur within the XAML DOM of the hosted control.

Syntax

HRESULT InvokeHandler(
  BSTR  bstrName,
  VARIANT  varArg1,
  VARIANT  varArg2,
  VARIANT*  pvarResult
);

Parameters

bstrName
[in] Name of the event.
varArg1
[in] Sender of the event.
varArg2
[in] Arguments of the event.
pvarResult
[out] Return value of the event.

Return Values

The method returns an HRESULT.

Remarks

Silverlight does not perform any inherent event handler hookup, and instead leaves that aspect to the browser script engines. Therefore the control exposes this deliberately language agnostic approach towards event handler invocation. Hosts can use this facility to react to Silverlight-originated events in their own code.

See Also

  • IXcpControlHost Interface

IXcpControlHost::NotifyError

Invoked whenever errors are raised from within the XAML DOM of the hosted control.

Syntax

HRESULT NotifyError(
  BSTR  bstrError,
  BSTR  bstrSource,
  long  nLine,
  long  nColumn
);

Parameters

bstrError
[in] The name of the error (see Silverlight Application Scripting Error Handling).
bstrSource
[in] Name of the source XAML file.
nLine
[in] The line number.
nColumn
[in] The column number.

Return Values

The method returns an HRESULT.

See Also

  • IXcpControlHost Interface

IXcpControlHost::NotifyLoaded

Invoked whenever the XAML DOM has successfully loaded.

Syntax

HRESULT NotifyLoaded();

Parameters

This method takes no parameters.

Return Values

The method returns an HRESULT.

See Also

  • IXcpControlHost Interface

IXcpObject Interface

Provides a common return type used by CreateObject. This interface defines no additional methods beyond IUnknown and IDispatch.


Client Development Quickstart Tasks

Introduction

The QuickStart topics in this section will show you how to quickly get started creating Microsoft Silverlight 1.0 applications.

  • Silverlight 1.0 Quickstart introduces basic features such as drawing objects on the screen, interacting with objects, animating objects, working with images, and embedding video.
  • Silverlight QuickStart Using Microsoft Expression Blend introduces using the design tool, Microsoft Expression Blend, to create Silverlight applications. A free trial version of Blend is available.
  • Getting Started with Silverlight offers a brief, hands-on introduction to creating Silverlight applications.


Sample Applications

The Silverlight 1.0 samples can be downloaded at the following location: Silverlight Samples. In addition, you can see larger, showcase samples here: Silverlight Showcase.


Silverlight

Silverlight SDK

Silverlight Overviews and Reference

Introduction

You can use JavaScript to create Microsoft Silverlight-based applications that deliver rich, engaging user experiences with 2-D graphics, animation, images, media, and video. The following topics provide detailed information about these features:

  • Overviews provide information about working with the object model, using XAML, and adding multimedia, animation, and graphics.
  • Reference provides information about the objects, methods, properties, events, and enumerations you can use.

See Also

Other Resources

Windows Presentation Foundation SDK