Customized ToolTips

If you want to supply more ambitious tooltip content, such as a combination of nested elements, you need to break the ToolTipService.ToolTip property out into a separate element. Here's an example that sets the ToolTip property of a button using more complex nested content lt Button Content I have a fancy tooltip gt lt ToolTipService.ToolTip gt lt StackPanel gt lt TextBlock Margin 3 Text Image and text gt lt TextBlock gt lt Image lt TextBlock Margin 3 Text Image and text gt lt TextBlock gt lt...

The DispatcherTimer

In some cases, you can avoid threading concerns altogether using the DispatcherTimer class from the System.Windows.Threading namespace. The DispatcherTimer was used in Chapter 9 to power the bomb-dropping animations in a simple arcade game. The DispatcherTimer doesn't offer true multithreaded execution. Instead, it triggers a periodic Tick event on the main application thread. This event interrupts whatever else is taking place in your application, giving you a chance to perform some work....

The ImageBrush

The ImageBrush allows you to fill an area with a bitmap image using any file type that Silver-light supports BMP, PNG, and JPEG files . You identify the image you want to use by setting the ImageSource property. For example, this brush paints the background of a Grid using an image named logo.jpg that's included in your project as a resource and therefore embedded in your application's XAP file lt Grid gt lt Grid.Background gt lt ImageBrush lt Grid.Background gt lt Grid gt The ImageSource...

Sizing the MediaPlayer

Although the MediaPlayer's standard skins seem quite self-sufficient at first glance, you may need to customize the ones you want to use. That's because all the included skins hard-code two important details the size of the video window, and the size of the root Canvas that holds the entire user interface. When you set the Width and Height properties of the MediaPlayer web control which you must , the entire skin will be scaled up or down to match. This doesn't necessarily represent a problem...

The MediaPlayer Control

The MediaPlayer web control gives you a server-side abstraction over the MediaElement class from Silverlight, which you used in Chapter 10. The obvious question is whether you should use the MediaElement or prefer the serverside MediaPlayer web control. They both amount to the same thing after all, the server-side MediaPlayer web control renders a MediaElement, although it requires slightly more work on the server to do so. There are two key advantages to using the MediaPlayer web control You...

Consuming a Web Service

You consume a web service in a Silverlight application in much the same way that you consume one in a full-fledged.NET application. The first step is to create a proxy class by adding a Visual Studio web reference. Note Before you begin, you need to know the correct URL for your web service. When testing your application, Visual Studio loads the test web server at a randomly chosen port. To add a web reference, you need to know this port. To find out what it is, run your website just before you...

The Wipe Transition

To actually use a page transition, you need at least one derived class that creates animations. In this section, you'll consider one example a WipeTransition class that wipes away the old page, revealing the new one underneath. The trick to creating a wipe effect is animating a brush that uses an opacity mask. As you learned in Chapter 8, an opacity mask determines what portions of an image or element should be visible, and which ones should be transparent. To use an animation as a page...

Downloading Assemblies on Demand

In some situations, the code in a class library is used infrequently, or perhaps not at all for certain users. However, if the class library contains a significant amount of code or more likely has large embedded resources like graphics, including it with your application will increase the size of your XAP file and lengthen download times needlessly. In this case, you might want to create a separate component assembly one that isn't downloaded until you need it. This scenario is similar to...

The GridSplitter

Every Windows user has seen splitter bars draggable dividers that separate one section of a window from another. For example, when you use Windows Explorer, you're presented with a list of folders on the left and a list of files on the right . You can drag the splitter bar in between to determine what proportion of the window is given to each pane. In Silverlight, you can create a similar design and give the user the ability to resize rows or columns by adding a splitter bar to a Grid. Figure...

A Mouse Event Example

Vb6 Moving Shapes Example

You can put all these mouse input concepts together and learn a bit about dynamic control creation by reviewing a simple example. Figure 4-5 shows a Silverlight application that allows you to draw small circles on a Canvas and move them around. Every time you click the Canvas, a red circle appears. To move a circle, you simply click and drag it to a new position. When you click a circle, it changes color from red to green. Finally, when you release your circle, it changes color to orange....

Full Screen

Silverlight applications also have the capability to enter a full-screen mode, which allows them to break out of the browser window altogether. In full-screen mode, the Silverlight plug-in fills the whole display area, and is shown overtop of all other applications, including the browser. Full-screen mode has some serious limitations You can only switch into full-screen mode when responding to a user input event. In other words, you can switch into full-screen mode when the user clicks a button...

Page Transitions

In Chapter 6, you saw how to support page navigation in a Silverlight application. The basic technique is to use some sort of layout container as your application's root element. You can then add user controls to this container and remove them when needed. Navigating from one page to another consists of removing the user control for the current page and adding the user control for the next page. With this framework in place, it takes just a bit more work to use an animation that switches...

Paths and Geometries

So far, you've taken a look at a number of classes that derive from Shape, including Rectangle, Ellipse, Polygon, and Polyline. However, there's one Shape-derived class that you haven't considered yet, and it's the most powerful by far. The Path class has the ability to encompass any simple shape, groups of shapes, and more complex ingredients such as curves. The Path class includes a single property, named Data, that accepts a Geometry object that defines the shape or shapes the path includes....

Tooltips and PopUps

Silverlight has a flexible model for tooltips those infamous yellow boxes that pop up when you hover over something interesting . Because tooltips in Silverlight are content controls, you can place virtually anything inside a tooltip. You can also tweak various timing settings to control how quickly tooltips appear and disappear. Tooltips are represented by the ToolTip content control. However, you don't add the ToolTip element to your markup directly. Instead, you use the ToolTipService to...

The Popup

The Popup control has a great deal in common with the ToolTip control, although neither one derives from the other. Like the ToolTip, the Popup can hold a single piece of content, which can include any Silverlight element. This content is stored in the Popup.Child property, rather than the Tool-Tip.Content property. Also, like the ToolTip, the content in the Popup can extend beyond the bounds of the page. Lastly, the Popup can be placed using the same placement properties and shown or hidden...

Save or Print to XPS

The XML Paper Specification XPS is a Microsoft standard for creating fixed, print-ready documents. It's similar to the Adobe PDF standard, and support is included in Office 2007 and Windows Vista. However, the XPS standard is based on XAML, which makes it possible to transfer content from an XPS document to a Silverlight page. If you're using Windows Vista, this gives you a back door to get graphic output from virtually any application. For example, Figure 7-20 shows a document in Word 2007,...

F

F value command, 214 FadeElementEffect class, 280 feeds, 558 file management, 493 FileDialogFilelnfo object, 503 FileExists method, 493 FileNotFoundException object, 186 FileStream class, 11 Fill property, 191, 196 Fill value, 136, 194, 230 FillBehavior property, 254, 256 FillRule property, 199, 207, 214 Filter property, 503 Find Primes button, 516 findName method, 174 FindPrimesCompletedEventArgs class, 514 FindPrimesThreadWrapper class, 513-516 FocusStates group, 347-348, 351-352, 368...

The HyperlinkButton

The ordinary Button control is simple enough you click it and it fires a Click event that you handle in code. But what about the other variants that Silverlight offers One of the simplest is the HyperlinkButton. When clicked, it directs the browser to another web page, effectively ending the current Silverlight application. The HyperlinkButton class adds two properties NavigateUri a relative or absolute path that points to a web page and TargetName which, optionally, identifies a bookmark in...

Static Text

Silverlight doesn't include a Label control. The linchpin for text display is the TextBlock element, which you've seen at work in many of the examples over the past four chapters. The TextBlock element is refreshingly straightforward. It provides a Text property, which accepts a string with the text you want to display. lt TextBlock Text This is the Alternatively, you can supply the text as nested content lt TextBlock gt This is the content. lt TextBlock gt The chief advantage of this approach...

Note To see a dependency property that uses the PropertyMetadata object to set

With these details in place, you're able to register a new dependency property so that it's available for use. However, whereas typical property procedures retrieve or set the value of a private field, the property procedures for a Silverlight property use the GetValue and Set-Value methods that are defined in the base DependencyObject class. Here's an example Public Property Margin As Thickness Get Return CType GetValue MarginProperty , Thickness End Get SetValue MarginProperty, value End Set...

Line Rectangle and Ellipse Geometries

The LineGeometry, RectangleGeometry, and EllipseGeometry classes map directly to the Line, Rectangle, and Ellipse shapes that you learned about in the first half of this chapter. For example, you can convert this markup that uses the Rectangle element lt Rectangle Fill Yellow Stroke Blue Width 100 Height 50 gt lt Rectangle gt to this markup that uses the Path element lt Path Fill Yellow Stroke Blue gt lt Path.Data gt lt RectangleGeometry Rect 0,0 lt Path.Data gt lt Path gt The only real...

The ComboBox

The ComboBox is similar to the ListBox control. It holds a collection of ComboBoxItem objects, which are created either implicitly or explicitly. As with the ListBoxItem, the ComboBoxItem is a content control that can contain any nested element. Unlike combo boxes in the Windows world, you can't type in the Silverlight ComboBox control to select an item or edit the selected value. Instead, you must use the arrow keys or the mouse to pick from the list. The key difference between the ComboBox...

The HTML Window

Silverlight also gives you limited ability to control the browser through the HtmlWindow class. It provides two methods that allow you to trigger navigation Navigate and NavigateTo-Bookmark . Navigate sends the browser to another page. You can use an overloaded version of the Navigate method to specify a target frame. When you use Navigate , you abandon the current Silverlight application. It's the same as if the user had typed in a new URL in the browser's address bar. NavigateToBookmark...

Event Bubbling

Bubbling events are events that travel up the containment hierarchy. For example, MouseLeft-ButtonDown is a bubbling event. It's raised first by the element that is clicked. Next, it's raised by that element's parent, and then by that element's parent, and so on, until Silverlight reaches the top of the element tree. Event bubbling is designed to support composition in other words, to let you build more complex controls out of simpler ingredients. One example is Silverlight's content controls,...

The WrapPanel Example

Now that you understand the theory behind dependency properties, it's time to ground your knowledge in a realistic example. In Chapter 3, you saw how to create a custom layout container called the WrapPanel, which flows elements over multiple lines to fit the available space. By adding properties to the WrapPanel, you can customize the way it works. Because the WrapPanel is a Silverlight element, its properties should almost always be dependency properties, which gives them the flexibility to...

CrossDomain Access

If you've ever created a web page using Ajax techniques, you've no doubt used the XMLHttp-Request object, which allows you to perform web requests in the background. However, the XMLHttpRequest object imposes a significant limitation namely, the web page can only access web resources HTML documents, web services, files, and so on that are on the same web server. There's no direct way to perform a cross-domain call to fetch information from another website. Silverlight imposes almost exactly the...

MediaPlayer Skins

With virtually no effort, you can transform the MediaRlayer's standard look. The trick is using MediaRlayer skins. Technically, a MediaRlayer skin is a XAML file that defines the layout of the MediaElement and playback controls, complete with a full complement of animations that make the playback controls feel responsive and professional. The skin doesn't include any code. Instead, the MediaRlayer looks for elements that have predefined names like RlayRauseButton and VolumeSlider and wires up...

Creating a Web Service

To create a WCF service in Visual Studio, right-click your ASRNET website in the Solution Explorer and choose Add New Item. Choose the Silverlight-enabled WCF Service template, enter a file name, and click Add. When adding a new WCF service, Visual Studio creates two files see Figure 13-5 The service endpoint. The service endpoint has the extension .svc, and is placed in your root website folder. For example, if you create a web service named TestService, you'll get a file named...

Creating the BackgroundWorker

To use the BackgroundWorker, you begin by creating an instance in your code and attaching the event handlers programmatically. If you need to perform multiple asynchronous tasks, you can create your BackgroundWorker objects when needed and store them in some sort of collection for tracking. In the example described here, just one BackgroundWorker is used, and it's created in code when the page is first instantiated. Here's the initialization code that enables support for progress notification...

The TabControl

Silverlight Tab Items Header

You're no doubt familiar with the TabControl, a handy container that condenses a large amount of user interface into a set of tabbed pages. In Silverlight, the TabControl is an items control that holds one or more TabItem elements. Like several of Silverlight's more specialized controls, the TabControl is defined in a separate assembly. When you add it to a page, Visual Studio will add a reference to the System.Windows.Controls.dll assembly, and map a new XML namespace, like this one lt...

The Last Word Wds

In this chapter, you saw how to use styles to reuse formatting and control templates to make more radical changes. You used the parts and states model to customize a Silverlight control, and saw how you could create a respectable button without being forced to reimplement any core button functionality. These custom buttons support all the normal button behavior you can tab from one to the next, you can click them to fire an event, and so on. Best of all, you can reuse your button template...

Formatting Rows

By setting the properties of the DataGrid column objects, you can control how entire columns are formatted. However, in many cases it's more useful to flag rows that contain specific data. For example, you might want to draw attention to high-priced products or expired shipments. You can apply this sort of formatting programmatically by handling the DataGrid.LoadingRow event. The LoadingRow event is a powerful tool for row formatting. It gives you access to the data object for the current row,...

HorizontalTrackLargeChangeDecreaseRepeatButton

Figure 11-7. The named parts in the HorizontalTemplate for the Slider The TemplatePart attribute indicates the name that the element must have, which is critical because the control code will search for that element by name. It also indicates the element type, which may be something very specific such as Thumb, in the case of the HorizontalThumb part or something much more general for example, FrameworkElement, in the case of the HorizontalTemplate part, which allows you to use any element ....

The LinearGradientBrush

The LinearGradientBrush allows you to create a blended fill that changes from one color to another. Here's the simplest possible gradient. It shades a rectangle diagonally from blue in the top-left corner to white in the bottom-right corner lt Rectangle Width 150 Height 100 gt lt Rectangle.Fill gt lt LinearGradientBrush gt lt GradientStop Color Blue Offset 0 gt lt GradientStop Color White Offset 1 gt lt LinearGradientBrush gt lt Rectangle.Fill gt lt Rectangle gt The top gradient in Figure 8-1...

Animating Brushes

Animating brushes is another common technique in Silverlight animations, and it's just as easy as animating transforms. Once again, the technique is to dig into the particular subprop-erty you want to change, using the appropriate animation type. Figure 9-4 shows an example that tweaks a RadialGradientBrush. As the animation runs, the center point of the radial gradient drifts along the ellipse, giving it a three-dimensional effect. At the same time, the outer color of the gradient changes from...

Line Caps and Line Joins

When drawing with the Line and Polyline shapes, you can choose how the starting and ending edge of the line is drawn using the StartLineCap and EndLineCap properties. These properties have no effect on other shapes because they're closed. Ordinarily, both StartLineCap and EndLineCap are set to Flat, which means the line ends immediately at its final coordinate. Your other choices are Round which rounds the corner off gently , Triangle which draws the two sides of the line together in a point ,...

Template Basics

Styles allow you to change the appearance of an element. However, styles are limited to setting properties that are defined in the element class. For example, there are various visual details about a button that you can't change because they aren't exposed through properties. Examples include the shading in a button's background to the way it highlights itself when you click down on it with the mouse. However, Silverlight has another, much more radical customization tool called templates. While...

The PasswordBox

Silverlight includes a separate control called the PasswordBox to deal with password entry. The PasswordBox looks like a TextBox, but it displays a string of circle symbols to mask the characters inside. You can choose a different mask character by setting the PasswordChar property, and you can set or retrieve the text inside through the Password property. The PasswordBox does not provide a Text property. Additionally, the PasswordBox does not support the clipboard. This means the user can't...

Combining Shapes with GeometryGroup

The simplest way to combine geometries is to use the GeometryGroup and nest the other Geometry-derived objects inside. Here's an example that places an ellipse next to a square lt Path Fill Yellow Stroke Blue Margin 5 Canvas.Top 10 Canvas.Left 10 gt lt Path.Data gt lt GeometryGroup gt lt RectangleGeometry Rect 0,0 lt EllipseGeometry Center 150,50 RadiusX 35 lt GeometryGroup gt lt Path.Data gt lt Path gt The effect of this markup is the same as if you supplied two Path elements, one with the...

Polygon

The Polygon is virtually the same as the Polyline. Like the Polyline class, the Polygon class has a Points collection that takes a list of coordinates. The only difference is that the Polygon adds a final line segment that connects the final point to the starting point. If your final point is already the same as the first point, the Polygon class has no difference. You can fill the interior of this shape using the Fill brush. Figure 7-7 shows the previous Polyline as a Polygon with a yellow...

The Expand or Collapse Button

The control template shown in the previous example includes a ToggleButton. However, it uses the ToggleButton's default appearance, which makes the ToggleButton look like an ordinary button, complete with the traditional shaded background. This just isn't suitable for the Expander. Although you can place any content you want inside the ToggleButton, the Expander requires a bit more. It needs to do away with the standard background, and change the appearance of the elements inside depending on...

The CheckBox

Both the CheckBox and the RadioButton are buttons of a different sort. They derive from ToggleButton, which means they can be switched on or off by the user, hence their toggle behavior. In the case of the CheckBox, switching the control on means placing a checkmark in it. The CheckBox class doesn't add any members, so the basic CheckBox interface is defined in the ToggleButton class. Most important, ToggleButton adds an IsChecked property. IsChecked is a nullable Boolean, which means it can be...

Understanding Parts with the Slider Control

In the parts and states model, the states dominate. Many controls, like the Button, use templates that define multiple state groups but no parts. But in other controls, like the Slider, parts allow you to wire up elements in the control template to key pieces of control functionality. To understand how parts work, you need to consider a control that uses them. Often parts are found in controls that contain small working parts. For example, the DatePicker uses parts to identify the drop-down...

Choosing Parts and States

Now that you have the basic structure in place, you're ready to identify the parts and states that you'll use in the control template. Clearly, the Expander requires two states Collapsed. This is the storyboard that collapses the content region out of sight. Expanded. This is the storyboard that expands the content region back into view. ExpandCollapseButton. This is the button that, when clicked, expands or collapses the content region. The Expander provides this service by handling the events...

The Content Property

Whereas the Panel class adds the Children collection to hold nested elements, the Content-Control class adds a Content property, which accepts a single object. The Content property supports any type of object. It gives you three ways to show content Elements. If you use an object that derives from UIElement for the content of a content control, that element will be rendered. Other objects. If you place a non-element object into a content control, the control will simply call ToString to get the...

Dashes

Strokedasharray

Instead of drawing boring solid lines for the borders of your shape, you can draw dashed lines lines that are broken with spaces according to a pattern you specify. When creating a dashed line in Silverlight, you aren't limited to specific presets. Instead, you choose the length of the solid segment of the line and the length of the broken blank segment by setting the StrokeDashArray property. For example, consider this line lt Polyline Stroke Blue StrokeThickness 14 StrokeDashArray 1 2 Points...

The Default Transition

Transitions apply to state groups. When defining a transition, you must add it to the Visual-StateGroup.Transitions collection. The simplest type of transition is a default transition, which applies to all the state changes for that group. To create the default transition, you simply need to add a VisualTransition element and set the GeneratedDuration property to set the length of the transition effect. Here's an example lt VisualStateGroup x Name CommonStates gt lt VisualTransition...

Defining and Registering a Dependency Property

You'll spend much more time using dependency properties than creating them. However, there are still many reasons that you'll need to create your own dependency properties. Obviously, they're a key ingredient if you're designing a custom Silverlight element. They're also required in some cases if you want to add data binding, animation, or another Silverlight feature to a portion of code that wouldn't otherwise support it. Creating a dependency property isn't difficult, but the syntax takes a...