Practical Silverlight Programming
About this Book
Silverlight is a cross-browser, cross-platform plug-in that delivers the next generation of .NET-based media experiences and rich interactive applications (RIAs) for the Web. With Silverlight, your Web development experience will much more closely resemble the development of desktop applications in WPF. Ultimately, the goal of Silverlight is to create Web applications that are indistinguishable from desktop applications.
Practical Silverlight Programming provides everything you need to create advanced graphics and user interfaces in your Web applications using Silverlight 2. The book uses code examples to clearly explain every step it takes to build a variety of Silverlight applications, from simple user interfaces and 2D shapes to complex custom user controls, game physics, and 3D graphics objects. You will learn how to use Silverlight to develop impressive graphics effects and high-fidelity user interfaces.
This book and its sample code listings, which are available for download at this website, provide you with:
- A complete, in-depth instruction on practical Silverlight programming. After reading this book and running the example programs, you will be able to add various sophisticated graphics and interactive user interfaces to your Web applications.
- About 100 ready-to-run example programs that allow you to explore the graphics techniques described in the book. These examples can be used to better understand how graphics algorithms work. You can modify the code examples or add new features to them to form the basis of your own projects. Some of the example code listings provided in this book are already sophisticated graphics packages that can be used directly in your own real-world Silverlight applications.
- Many classes in the sample code listings that you will find useful in your Silverlight programming. These classes include matrix manipulation, coordinate transformation, color maps, and other useful utility classes. You can extract these classes and plug them into your own applications.
Table of Contents
Introduction
Overview
What this Book includes
Is This Book for You
What Do You Need to Use This Book
How This Book Is Organized
Using Code Examples
Customer Support
Chapter 1: Overview of Silverlight Programming
XAML Basics
Why XAML Needed?
Creating XAML Files
Code-Behind Files
Your First Silverlight Program
Properties in XAML
Event Handlers in Code-Behind Files
Code-Only Example
Hosting Silverlight Controls
Chapter 2: Graphics Basics in Silverlight
2D Coordinate Systems in WPF
Default Coordinates
Custom Coordinates
Custom Coordinates for 2D Charts
2D Viewport
Zooming and Panning
Basic 2D Graphics Shapes
Lines
Rectangles and Ellipses
Polylines
Polygons
Chapter 3: 2D Transformations
Basics of Matrices and Transforms
Scaling
Reflection
Rotation
Translation
Homogeneous Coordinates
Translation in Homogeneous Coordinates
Scaling in Homegeneous Coordinates
Rotation in Homegeneous Coordinates
Combining Transforms
Vector and Matrix in Silverlight
Vector Class
Basic Definition
Mathematical Operators
Matrix Structure
Creating Perpendicular Lines
Object Transforms in Silverlight
MatrixTransform Class
ScaleTransform Class
TranslateTransform Class
RotateTransform Class
SkewTransform Class
Combining Transforms
Chapter 4: Geometry and 2D Drawing
Path and Geometry Classes
Line, Rectangle, and Ellipse Geometries
GeometryGroup Class
PathGeometry Class
Lines and Polylines
Arcs
Bezier Curves
Path Mini-Language
Interactive 2D Drawing
Mouse Events
Creating Shapes
Dragging and Moving Shapes
Zooming and Panning
Hit Testing in Silverlight
Chapter 5: Colors and Brushes
Colors
System Colors
Custom Brushes Class
Brushes
SolidColorBrush
LinearGradientBrush
Custom Colormap Brush
RadialGradientBrush
Custom Radial Colormap Brush
ImageBrush
Opacit Masks
Brush Transforms
LinearGradientBrush Transform
RadialGradientBrush Transform
ImageBrush Transform
Chapter 6: Animation
Silverlight Animation Basics
Property-Based Animation
A Simple Animation Example
Animation in Code
Animation and Timing Behavior
Duration
RepeatBehavior
AutoReverse
BeginTime
Speed Controls
Interactive Control
Animation and Transform
Animating Translation
Rolling Balls
Combining Transform Animation
Frame-Based Animation
Key-Frame Animation
Spline Key-Frame Animation
Path Animation
Path Animation Using Timer
Path Animation Using Key-Frames
Chapter 7: Physics and Games in Silverlight
Ordinary Differiential Equations
Fourth-Order Runge-Kutta Method
Higher-Order ODEs
ODE Solver
Pendulum
Equation of Motion
Pendulum Simulator
Couple-Spring System
Equations of Motion
Coupled-Spring Simulator
Projectiles
Aerodynamic Drag Force
Projectile Equations of Motion
Golf Game
Collission
Bouncing Ball Physics
Bouncing Ball Simulator
Chapter 8: Charts in Silverlight
Simple Line Charts
Creating Simple Line Chart
How It Works?
Line Charts with Data Collection
Chart Style
Data Collection
Data Series
Creating Charts
Gridlines and Labels
XAML Layout
ChartStyleGridlines Class
Testing Project
Legend
Legend Class
Testing Project
Chapter 9: 3D Transformations
Basic 3D Transformations
3D Points, Vector, and Matrix
Point in 3D
Vector in 3D
Matrix in 3D
Scaling
Translation
Rotation and Quaternion
Projections
Orthographic Projections
Multi-View Projections
Axonometric Projections
Perspective Projections
One-Point Perspective Projections
Two-Point Perspective Projections
Three-Point Perspective Projections
Perspective Projection Matrix
Projection Matrices in Silverlight
3D Objects in Silverlight
Backface Removal
Creating Cube in Silverlight
Object Transformations in Silverlight
Scale Transform
Translate Transform
Matrix Transform
Chapter 10: 3D Objects in Silverlight
3D Coordinate Axes
Coordinate3D Class
Creating 3D Coordinate Axes
3D Line Charts
Creating a Cube
Cube Class
Creating Multiple Cubes
Animating Cubes
Creating a Sphere
Sphere Class
Creating Multiple Spheres
Animating Spheres
Creating a Cylinder
Cylinder Class
Creating Multiple Cylinders
Animating Cylinders
Creating 3D Surfaces
Surface Class
Creating Simple Surfaces
Chapter 11: Silverlight Built-in Controls
Layout Controls
StackPanel
Grid
Canvas
Text Controls
TextBlock
TextBox
WatermarkedTextBox
Button Controls
Button
CheckBox
RadioButton
ToolTip
ListBox and DataGrid Controls
ListBox
DataGrid
Other Common Controls
HyperlinkButton
Calendar and DatePicker
Image
MediaElement
Ink Control
MultiScaleImage Control and Deep Zoom
Chapter 12: Styles, Templates, and Data Binding
Styles
A Simple Style Example
Control Styles
Control Templates
Creating Control Templates
Template Binding
Default Templates
Data Binding
Element-To-Element Binding
Binding to Non-Element Objects
Binding to Object Collection
Chapter 13: Expression Blend
Expression Blend Overview
Workspace
File Structure
Toolbox
Artboard and Interaction Panel
Properties Panel
Using Expression Blend
Rectangle Animation
Creating the Rectangle Shape
Creating Animation
Event Handling
Dynamic Menu
Chapter 14: Custom Controls
Creating a User Control Using Visual Studio
Implementing the User Control
Testing the User Control
Creating a User Control Using Expression Blend
Making a User Control
Data Binding
Creating a Silverlight Class Library
Silverlight Class Library Example
Implementing Class Library
Testing Booklist Library
Index
Introduction
        Overview
        What This Book Includes
        Is This Book for You
        What Do You Need to Use This Book
        How This Book is Organized
        Using Code Examples
Overview
In the Internet age, web developers continue to push the boundaries of the browsing platform, yet remain locked in a world limited by HTML-based web development tools.
Silverlight aims to change this situation by bringing a new paradigm of web development to the table, providing developers with more powerful tools for their web development arsenals, while simultaneously allowing them to leverage their existing development skills.
Silverlight enables the development of next-generation Microsoft .NET-based media experiences and rich interactive applications (RIAs) for the Web. Silverlight is delivered as a cross-platform and cross-browser plug-in that exposes a programming framework and features from a subset of the .NET Framework. With Silverlight, your Web development experience will much more closely resemble the development of desktop applications using the Windows Presentation Foundation (WPF). Ultimately, the goal of Silverlight is to create Web applications that are indistinguishable from desktop applications.
Silverlight 2.0 is based on the .NET Framework and is a subset of WPF, allowing you to use procedural programming languages such as C# or Visual Basic to develop RIAs for Web applications. Practical Silverlight Programming will provide you with the programming techniques necessary for developing interactive web applications using Microsoft Silverlight and C# based on the .NET framework. I believe this book will be useful for Silverlight and C# programmers of all skill levels.
As a C# programmer, you are probably already familiar with WPF and the .NET 3.5 framework. Silverlight, as a lightweight version of WPF, takes advantage of WPF advanced graphical features. Silverlight completely revolutionizes the landscape of Web application development based on conventional HTML techniques. At first, you may think that Silverlight is just another way to create Web pages and Web controls such as menus, dialogs, and custom controls. However, Silverlight has much more to offer than any other Web programming framework does. It integrates three basic Windows elements - text, controls, and graphics - into one single programming model, and puts these three elements into the same element tree in the same manner.
Without Silverlight, developing a Web application with interactive graphics objects and animations might involve a number of different technologies ranging from Flash to GIF animations. Silverlight, on the other hand, is designed as a single model for interactive Web application development, providing seamless integration between such services within an application. Similar constructs can be used for creating animations, data binding, and graphics models. To take further advantage of powerful new graphics hardware technologies, Silverlight, like WPF, implements a vector-based graphics model. This allows graphics to be scaled based on screen-specific resolution without loss of image quality, something nearly impossible to do with fixed-size raster graphics.
With Silverlight, graphics elements can be easily integrated into any part of your Web applications. For example, Silverlight provides 2D shape elements that can be involved in the user interface (UI) tree like other elements can. You are free to mix these shapes with any other kind of element, such as with a button control.
As you may have noticed, there already are a few Silverlight programming books available in bookstores. The vast majority of these books are general-purpose user guides and tutorials explaining the basics of Silverlight and how to implement simple Silverlight applications. To take full advantage of Silverlight advanced features, however, there is need for a book that provides an in-depth introduction specifically to Silverlight programming for real-world Web applications.
This book is written with the intention of providing you with a complete and comprehensive explanation of Silverlight capability in graphics and user interfaces, and pays special attention to code implementation details, which will be useful when you create your own real-world interactive Web applications. This book includes many ready-to-run code examples that cover a broad array of topics on Silverlight programming. Much of this book contains original work based on my own programming experience developing Web applications. Without Silverlight and the .NET framework, developing interactive Web applications with advanced graphics and user interfaces is a difficult and time-consuming task. To add even simple charts or animations to your Web applications, you often have to waste effort creating a chart and animation program, or buy commercial chart and animation add-on packages.
Practical Silverlight Programming provides everything you need to create advanced graphics and user interfaces in your Web applications using Silverlight. It shows you how to create a variety of graphics and user interfaces ranging from simple 2D shapes to complex custom user controls. Even though Silverlight does not contain a built-in 3D model, I will show you how to create your own 3D graphics objects and how to interact with these 3D models. I will try my best to introduce you to practical Silverlight programming in a simple way - simple enough to be easily followed by a beginner who only has basic .NET programming experience. From this book, you can learn how to create a full range of RIA Web applications and how to implement custom user controls that can be reused in your Silverlight projects.
What This Book Includes
This book and its sample code listings, which are available for download at this website (click here), provide you with:
- A complete, in-depth instruction on practical Silverlight programming. After reading this book and running the example programs, you will be able to add various sophisticated graphics and interactive user interfaces to your Web applications.
- About 100 ready-to-run example programs that allow you to explore the graphics techniques described in the book. These examples can be used to better understand how graphics algorithms work. You can modify the code examples or add new features to them to form the basis of your own projects. Some of the example code listings provided in this book are already sophisticated graphics packages that can be used directly in your own real-world Silverlight applications.
- Many classes in the sample code listings that you will find useful in your Silverlight programming. These classes include matrix manipulation, coordinate transformation, color maps, and other useful utility classes. You can extract these classes and plug them into your own applications.
Is This Book for You
You do not have to be an experienced Silverlight developer or an expert to use this book. I designed this book to be useful to people of all levels of Silverlight programming experience. In fact, I believe that if you have some experience with C#, Windows Forms, HTML, and the .NET framework, you will be able to sit down in front of your computer, start up Microsoft Visual Studio 2008 and Silverlight 2.0 Beta 2, follow the examples provided in this book, and quickly become familiar with Silverlight programming. For those of you who are already experienced Silverlight developers, I believe this book has much to offer as well. There is a great deal of information about Silverlight programming in this book not available in other Silverlight tutorial and reference books. In addition, most of the example programs in this book can be used directly in your own real-world Web application development. This book will provide you with a level of detail, explanation, instruction, and sample program code that will enable you to do just about anything Silverlight graphics and user interface related.
The majority of the example programs in this book can be used routinely by Silverlight developers and technical professionals. Throughout the book, I will emphasize the usefulness of Silverlight programming in real-world Web applications. If you follow the instructions presented in this book closely, you will be able to develop various practical Silverlight Web applications, from 2D graphics and charts to sophisticated 3D model and custom user controls. At the same time, I would not spend too much time discussing programming style, execution speed, and code optimization because there are a plethora of books out there that already deal with such topics. Most of the example programs you will find in this book omit error handlings. This makes the code easier to understand by focusing only on the key concepts and practical applications.
What Do You Need to Use This Book
You would not need any special equipment to make the best use of this book or to understand the algorithms. To run and modify the sample programs, you will need a computer that is capable of running either Windows Vista or Windows XP. The software installed on your computer should include Visual Studio 2008 and Silverlight 2.0 Beta 2 or later. Please note that Silverlight 2.0 Beta 2 will not run applications that target Silverlight 2.0 Beta 1 since a number of API changes were made between Beta 1 and Beta 2. Therefore, if you have a browser with Silverlight 2.0 Beta 1 installed and visit a site that hosts a Silverlight 2.0 Beta 2 application, you will be prompted to upgrade to the newer Beta version of Silverlight. Once you do this you would not be able to run Beta 1 applications without uninstalling Beta 2. This means that if you have published a running sample on the Web built with Silverlight 2.0 Beta 1, you will probably need to update it to Beta 2 soon.
If you have Visual Studio 2005 and Silverlight 2.0 Beta 1 installed, you can still run most of the sample code with few modifications. Please remember, however, that this book is intended for Visual Studio 2008 and Silverlight 2.0 Beta 2 or later, and that all of the example programs were created and tested on this platform, so it is best to run the sample code on the same platform.
How This Book is Organized
This book is organized into fourteen chapters, each of which covers a different topic in Silverlight programming. The following summaries of each chapter should give you an overview of the book content:
Chapter 1, Overview of Silverlight Programming
This chapter introduces the basics of Silverlight and reviews some of the general aspects of Silverlight
programming, including XAML files used to define user interfaces.
Chapter 2, Graphics Basics in Silverlight
This chapter reviews some fundamental concepts of the 2D graphics and the 2D drawing model in Silverlight. It introduces coordinate systems and basic 2D shapes.
Chapter 3, 2D Transformations
This chapter covers the mathematical basics for 2D graphics programming. 2D vectors, matrices, and transformations in the homogeneous coordinate system, including translation, scaling, reflection, and rotation, are discussed. These 2D matrices and transformations allow Silverlight applications to perform a wide variety of graphical operations on graphics objects in a simple and consistent manner.
Chapter 4, Geometry and 2D Drawing
This chapter introduces Silverlight Geometry classes and demonstrates why you need them to create complex 2D graphics objects. It also shows you how to create interactive 2D drawing programs.
Chapter 5, Colors and Brushes
This chapter covers the color system and brushes that Silverlight uses to paint graphics objects. It introduces a variety of brushes and their transformations. You will learn how to create exotic visual effects using different brushes, such as the gradient and image brushes.
Chapter 6, Animation
This chapter describes Silverlight animation facilities, which allow most of the properties and transformations of graphics objects (such as position, size, translation, rotation, etc.) to be animated. It also describes how to create a custom animation class that can be used in physics-based animation.
Chapter 7, Physics and Games in Silverlight
This chapter covers topics related to real-world Silverlight applications. You will learn how to create and simulate physics models by solving ordinary differential equations with the Runge-Kutta method, and how to incorporate physics models into real-world games in Silverlight. This chapter discusses several physics models and games, including a pendulum, a coupled spring system, a golf ball (projectiles), and ball collision.
Chapter 8, Charts in Silverlight
This chapter contains instructions on creating 2D line charts in Silverlight. It introduces basic chart elements including the chart canvas, text canvas, axes, title, labels, ticks, and legend.
Chapter 9, 3D Transformations
This chapter extends the concepts described in Chapter 3 into the third dimension. It explains how to define 3D graphics objects and how to translate, scale, reflect, and rotate these 3D objects. It also describes transformation matrices that represent projection and transformations, which allow you to view 3D graphics objects on a 2D screen. You will also learn how to define 3D vectors, matrices, and projections.
Chapter 10, 3D Objects in Silverlight
Silverlight does not provide 3D support, but this chapter shows you how to create your own 3D objects in Silverlight.
Chapter 11, Silverlight Built-in Controls
This chapter provides an introduction to the basic built-in controls in Silverlight and demonstrates how to use these controls in your Silverlight applications.
Chapter 12, Styles, Templates, and Data Binding
This chapter explains the Silverlight style and template system, which shows how you can apply a set of common property values to a group of controls and how you can give any Silverlight control a dramatic new look by applying a customized template. This chapter also introduces Silverlight data binding.
Chapter 13, Expression Blend
This chapter provides an overview of Microsoft Expression Blend, which is a visual tool for developing complex Silverlight applications.
Chapter 14, Custom Controls
This chapter explains how you can extend the existing Silverlight controls and create your own custom controls. You will learn how to create custom controls using three different approaches.
Using Code Examples
You may use the code in this book in your applications and documentation. You do not need to contact me or the publisher for permission unless you are reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing the example code listings does require permission. Incorporating a significant amount of example code from this book into your applications and documentation does require permission. Integrating the example code from this book into your commercial products is not allowed without the written permission from the author.