Adding an Overlay 1
Adding an overlay to a video can be a great way to give an identity to such a file, for example, with a company logo. However, don't forget that everything you're doing here will be burned into the video file. It might not be an appropriate way to display a message that must change often, such as an advertisement. In that case, a better solution would be to set your Silverlight 242 CHAPTER 13 Progressing with Videos application so that the advertisement is displayed on top of the media element...
Discovering the ButtonBase
What do a Button, Checkbox, and RadioButton have in common When you click on them something happens. This is enough to make them share a base class the ButtonBase. This class defines one important event the Click event. By handling this event, you define what the reaction of the application must be. ButtonBase derives from ContentControl. All subclasses get a Content property that is of type object. You can store anything in the Content property, for example, a string which will become the text...
The background Parameter
This sets the color of the Silverlight application's background. This color will be visible only if you set the windowless parameter to true as explained in the next section. The background parameter is a XAML color, not an HTML color. It means that you can also set the Alpha channel, as we saw in Chapter 5. In addition to these generated parameters, you can create additional ones as discussed in the following sections. The windowless Parameter This parameter is tricky. To keep it simple, let's...
Accessing the HTML Page From NET 1
In Chapter 14, we talked about the Silverlight HtmlPage class as a gateway to the HTML page hence the name containing the application. We talked about the HtmlPage.Window property and used it to get JavaScript object instances, and to call the Alert, Confirm, and Prompt methods. Another handy property of the HtmlPage class is the Document. This is the exact equivalent of calling document in JavaScript. Using the well-known methods GetElementById and GetElementsByTagName, you can access any HTML...
Creating Objects with JSON
JSON is not just useful for web services, but also provides a handy way to create new objects in a compact way see Listing 8.4 . LISTING 8.4 JavaScript Object Notation and Objects 1 lt script 4 propertyl Value, 8 function doSomething settings 140 CHAPTER 8 Programming Silverlight with JavaScript Lines 2 to 6 assign a new object to a local variable myNewObject. This object is created on-the-fly and has two properties. Another great use of JSON is to pass parameters to functions or methods ,...
Using ResourceDictionaries in Silverlight
By studying which interfaces the ResourceDictionary implements, we learn a great deal about this class. We know that A ResourceDictionary can store any Object. You can loop through all the items, for example using a foreach loop. Each item stored must have a unique key. 344 CHAPTER 17 Using Resources, Styling, and Templating You can access the items using their key or if you know which position they have in the dictionary using their index.
Creating an EventArgs
Often, you want to pass additional information to the event's subscribers. By convention, an event always has two parameters The event's sender declared as an object An instance of EventArgs or of another class deriving from EventArgs. If you don't want to pass any information, simply create an empty instance of EventArgs and use it when you raise the event. This avoids breaking any application if you decide to change it later and to pass information using your own flavor of EventArgs. For...
Raising Events and Using Delegates 1
When an object wants to notify another object that something occurred, a good way is to raise an event. For the event's sender, it is handy because it doesn't need to know who is interested in the event. The event is raised, and all subscribers will be notified without the need for a direct reference. Raising Events and Using Delegates 187 For the event's subscriber, you just need to register once, and you will get all the notifications asynchronously. We already saw how to register for an...
Adding a Scale Animation
Let's add some movement to our animation with a scaling effect. We want the scene to come from far away and to grow while rotating, before going back into the background. The modifications needed to do this are easy. First, we need something to animate, so add a ScaleTransform to Listing 3.7 with the following steps 1. In KaXaml, add a ScaleTransform to the TransformGroup section. Note that we start with ScaleX ScaleY 0. If we don't animate the scene, we will not see anything, because scaling...
Understanding the Animation Elements
The Objects and Timeline category offers a nice way to see and interact with each animation element separately. Follow the steps 1. Expand all the elements under the top user control. 2. The tree displays many animation elements, each with a double arrow icon this icon is shown in Figure 11.9 for a different Silverlight application . 3. Using the tree, you can understand how the animations are structured. Try to compare this with the XAML markup. For example, the ellipse gets animated by six...
Handling Validation Errors
Since bindings can also update the source object in TwoWay mode , you need to make sure that the value entered can be converted. In the case of a DateTime class, for example, if the user enters an invalid string, the framework won't be able to create a DateTime instance with this value. The default behavior in this case is to just leave the source object untouched. This can be confusing, however, because the string in the TextBox will not be corrected, and the invalid value will still be...
Storing Resources
The Resources property is defined on the class FrameworkElement, so each class deriving from it can store resources. In XAML you store resources in an element using Listing 17.1 LISTING 17.1 Defining Resources in XAML lt LinearGradientBrush x Key BackgroundBrush gt lt GradientStop Offset 0 Color Yellow gt lt GradientStop Offset 1 Color Red gt lt LinearGradientBrush gt lt UserControl.Resources gt lt Grid x Name LayoutRootM gt lt Grid.Resources gt lt SolidColorBrush x Key MyBrush2 Color MGreen gt...
Using a Canvas to Drag an Element
With the possibility to position its children in an absolute way using the Canvas.Left and Canvas.Top properties, the Canvas is great when you must move an element on the screen, for example with the following steps 1. Create a new Silverlight application in Visual Studio and name it CanvasDrag. 2. Create a XAML scene within the UserControl in the file Page.xaml as in Listing 15.3 LISTING 15.3 XAML Scene for Dragging lt Grid x Name LayoutRoot Background Red lt Grid.ColumnDefinitions gt lt...
Raising the Event in the UserControl
In Visual Studio, in ThumbnailsViewerControl.xaml.cs, get the clicked element and the corresponding MediaEx instance. Thankfully we know that the data item is automatically set as the DataContext of the FrameworkElement, and that it is passed to all its children. We already have an empty method for the media_MouseLeftButtonDown event. You can now replace it with Listing 19.14. LISTING 19.14 media_MouseLeftButtonDown Event Handler private void media_MouseLeftButtonDown object sender,...
Writing to the Data Object with a Binding
We now write to the Settings instance when the SizeSlider moves. Remember that for the moment, we do this in an event handler. This creates a tight connection between the XAML UI and the code-behind, which is annoying. If a graphics designer changes the UI and replaces the Slider with another control, a change is needed in the code-behind. With a binding, on the other hand, the XAML can directly write and read to and from the data object. The coupling is looser, cleaner, and easier to modify if...
Easing the Translate Animation
In this section, we will ease the animation to make it look more natural with the following steps 1. In Blend, make sure that the storyboard named ExpandStoryboard is open, then expand the tree until you find the translate animation see Figure 11.9 . This is the animation we want to ease. If you add a keyframe manually at 0.5 seconds, this additional keyframe is added to each animation, which will cause problems later. By simply setting the RotateTransform's Angle, we add a keyframe only for...
Why Cant We Step Through InitializeComponent
You might have noticed that the method InitializeComponent in the Page constructor cannot be stepped in, not even if you press F11. The reason is that this generated method has an attribute that explicitly prevents this from happening. You can see that with the following steps 1. Position the mouse on the call to InitializeComponent and right-click. 2. From the context menu, select Go to Definition. This opens the Page.g.cs file. 3. On top of the InitializeComponent method, you should see the...
Adding an Icon or a Video
One type of overlay is a static image or even a video file. You can add one with the following steps 1. Open Expression Encoder and prepare a video for encoding like we did in Chapter 12. 2. In the Overlay category of the Enhance panel, check the Add Overlay check box. 3. Using the File controls, click on the button to display a file dialog. 4. In the Open dialog, select Files of Type, Media Files. 5. Select an image or a video file for the overlay. Do not worry about the size you can resize it...
Exploring the FrameworkElement
As we navigate down the family tree, the classes become more and more specialized. FrameworkElement is responsible for extending the layout capabilities, for watching an element's life time, and for providing a support for data binding which we study in Chapter 18, Data Binding and Using Data Controls . FrameworkElement also defines properties such as Width, Height, ActualWidth, ActualHeight, alignment properties, margins, style, and many others. All these properties are defined as...
Embedding a Font in Blend
Expression Blend offers an elegant way to solve the problem of font availability. Not only is the functionality easy to use, thanks to a font manager dialog, but also Blend will analyze your application's needs and extract a subset of the font needed for the application to run. Follow the steps Embedding Fonts in the Application 355 1. In Expression Blend, open the file Page.xaml of the Thumbnails application. 2. Select either one of the title TextBlocks. Then choose Object, Edit Style, Edit...
Using Resources in CodeBehind
Once resources have been stored, you can access them in .NET through the Resources property. You can only access resources stored in XAML markup after the method InitializeComponent has been executed. This method parses the XAML markup and creates the objects in memory, for example in Listing 17.3. LISTING 17.3 Using a Resource in Code Rectangle rectangle new Rectangle
Adding Elements to a Grid in CodeBehind
The elements can as usual be created and added to the Grid in code-behind. To set attached properties in C , use the method Grid.SetXXX. For example, Listing 15.7 shows how the red Ellipse from Listing 15.6 can be added to the Grid in C LISTING 15.7 Adding Elements to a Grid in Code Ellipse ellipse new Ellipse Grid.SetColumn ellipse, 1 Grid.SetColumnSpan ellipse, 2 Grid.SetRow ellipse, 2 ellipse.Fill new SolidColorBrush Colors.Red ellipse.Margin new Thickness 20 LayoutRoot.Children.Add ellipse
Managed Versus Unmanaged
Traditional Windows applications were and still are often programmed using a framework called Microsoft Foundation Classes MFC . This code compiles to machine code, which is low-level, machine-near computer code. It is called unmanaged because it is directly executed by the processor, without an additional layer. .NET code is different. The application is made of assemblies EXE and DLLs containing code written in intermediate language IL . This code is not machine code. When the application...
Using the HtmlEventArgs Class
When an HTML event is handled by a .NET event handler, an instance of HtmlEventArgs is passed to the method. This is useful, because this class contains a wealth of information about the HTML element having caused the event. For example, why not modify the button's caption from Silverlight to display the number of clicks In Page.xaml.cs, replace the HtmlButton_Click event handler we added in the previous section as shown in Listing 21.27 LISTING 21.27 New Event Handler HtmlButton_Click 1 string...
Embedding a Font in Visual Studio
Embedding a font in Visual Studio requires a little more manual work, and you cannot choose a subset. Follow the steps 1. Locate the Fonts folder on your PC. It is located in your Windows folder depending on your configuration, it can be C Windows Fonts, or C WINNT Fonts . 2. Copy the Font file s for example, Algerian that you want to add to your application. For some fonts, a separate file is available for Bold, Italic, or Bold Italic. If you want to use these variations of a font, you must...
Clipping Path 1
When we started talking about Silverlight, we mentioned an exciting feature It is possible to create nonsquare areas, so that not only the visual but also the hit test area is nonsquare. This allows you to easily create nonsquare controls. The support for nonsquare shapes is extensive, and it is actually possible to give any shape to any element, even images and videos This amazing feat is accomplished using clipping paths. Follow these steps. 1. Set LayoutRoot's color to yellow. 2. In Blend,...
Using Parentheses
Parentheses have multiple purposes in C . We saw before that they can be used to cast a variable from one type into another type. Another important use is to specify the order of the executed operations. For example int result1 5 2 3 stores 11 in int result2 5 2 3 stores 21 in If a condition is true, the expression before the colon is evaluated. If it expression after the colon is evaluated. The evaluated expressions may complex calculations, for example in Listing 9.12 LISTING 9.12 Conditional...
Programming the Control in JavaScript
As we already did, you can also write JavaScript code to handle events raised by the control. For more information about the available events, check the reference documentation available at For example, you can force the video to play in a loop with these steps 1. In Source view, add a JavaScript event handler in the head section of the ASPX page Listing 24.13 LISTING 24.13 VideoPlayer_Ended Event Handler lt script function VideoPlayer_Ended sender, args 2. Add the OnClientMediaEnded attribute...
Using an iframe
The iframe markup you need to include in your HTML page is the one we got from the Publish category earlier see the section Testing the Output earlier in the chapter . If you forgot to write down that markup, you can retrieve it by performing the following steps 1. Under Publish, set the Publish To combo box to Silverlight Streaming. 2. Expand the Advanced Properties under the Publish category. You should see an Applications list. 3. If the list is empty, click on the Refresh button. Note that...
Unleashed 1
800 East 96th Street, Indianapolis, Indiana 46240 USA Copyright 2009 by Pearson Education, Inc. All rights reserved. No part of this book shall be reproduced, stored in a retrieval system, or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without written permission from the publisher. No patent liability is assumed with respect to the use of the information contained herein. Although every precaution has been taken in the preparation of this book, the...
Using a ScrollViewer to Scroll Big Areas
We used a ScrollViewer already in Chapter 6 and also in our Thumbnails application. The purpose of this container is to provide scrollbars so that the element inside the ScrollViewer can be bigger than the ScrollViewer itself. Using a ScrollViewer in XAML is straightforward as shown in Listing 15.8 lt ScrollViewer Width 500 lt Grid x Name LayoutRoot Width 1000 gt lt -- -- gt lt Grid gt lt ScrollViewer gt ScrollViewer is not a panel. Instead, it is a ContentControl, a class deriving from...
Inheritance
Inheritance is a key concept in OOP. An object can have an ancestor base type and derived types. Let's consider a plane wing again A 747 jet, a Cessna, and an F16 fighter all have wings. They do have shared characteristics, but they are also very different from each other. The basic physics is the same, however. So why not create a class Wing to take care of the basic functionality Then, we can create derived classes JumboWing, CessnaWing, and FighterWing. Each refines the base functionality,...
Build the application Playing with the Size
Let's experiment with the application's and its container's size first with the next steps 1. Go back to the file Default.html that we copied before. 2. Change the CSS rule for the HTML page's body as in Listing 7.1 3. Change the CSS rule silverlightControlHost as in Listing 7.2 LISTING 7.2 silverlightControlHost CSS Rule silverlightControlHost height 180px width 280px 112 CHAPTER 7 Deploying to a Web Page 4. Change the value of the background parameter of the Silverlight object tag to Blue. 5....
Drawing Shapes 1
We already talked about shapes earlier in this book, and there is not too much to add. Shapes belong to the namespace System.Windows.Shapes. Their basis class is abstract, and it is named Shape logically . Since a Shape derives from FrameworkElement, it can be handled in many ways like a control. It can be animated, it can be placed in a panel, and you can also use data binding. Through their common basis class, all shapes share properties such as the following The Fill property a brush used...
Colors Transparency and windowless
Let's try diverse transparency settings with the following steps 1. In Blend, set LayoutRoot's background color to red, but with the Alpha channel set to 50 like we did in Chapter 5. When you modify XAML markup or later C code , you need to build the application. If you don't, your changes will not be packaged, and you won't see them when you run the application. When you make a change in the HTML markup, however, you can simply refresh the web page. HTML markup is not compiled, it is...
Implementing Interfaces
In .NET we use interfaces to create a definition for functionality. It's like a contract between the person who implements a class and the person who uses it. The ResourceDictionary shown previously implements the interfaces IDictionary, ICollection, and two kinds of IEnumerable. For users of this class, it means that we know which methods the developers implemented and which functionality is fulfilled. Earlier in this book, we talked about abstract classes, and we said that they cannot be...
Controlling Sound and Video 1
Three things are annoying regarding the video in our Thumbnails gallery The movie automatically starts when the page is loaded, which is distracting for the user. The movie runs until the end then stops and cannot be restarted. Once the movie starts, there is no way to pause it. To correct these issues, we need to set properties, and also a little code-behind. This is our first contact with C , so don't expect to fully understand everything we do here. Everything will become clearer in future...
In This Chapter 1
Using XML for User Interfaces Understanding XML Namespaces Defining Additional Namespaces Creating a Canvas with Children Documenting Your Markup with XML Comments Saving Typing, Saving Space What would software development be without acronyms Let's meet XAML, also known as extensible Application Markup Language and pronounced Zammel . Located at the border between graphics designers and software developers, this language enables new workflows and allows the designers to implement markup...
Creating a New Silverlight Test Application
Once the test framework is installed, we can use it to create a test application with the following steps 1. Start in Visual Studio by creating a new Silverlight class library for our TryFindResource utility method. For this, in Visual Studio, choose File, New Project and select Silverlight Class Library from the Silverlight section. 2. Name the new project SilverlightUtility. 3. In the Solution Explorer, rename the Class1.cs to Extensions.cs. In the dialog asking whether you also want to...
Visibility
We saw that JavaScript cannot protect an object's members against unwanted access. In C , however, you can control who is allowed to use attributes, properties, and methods. 178 CHAPTER 10 Progressing with .NET private This is the most restrictive qualifier. Private members can be used only inside the class that defines them. This is also the Unlike the Java programming language, C does not have a visibility restricted to the current namespace only. define it explicitly, private visibility will...
Decoding the Response
We now implement the code decoding Flickr's response. 1. Declare the method shown in Listing 23.11. You should build the application now, because we added a lot of code before. Building allows you to check that you didn't make mistakes while typing. LISTING 23.11 ExtractResponse Method private void ExtractResponse object state We didn't need to switch the context when we worked with the WebClient class, because this class does it automatically. v_ 510 CHAPTER 23 Placing Cross-domain Requests...
Setting the DataContext
Each FrameworkElement in Silverlight gets a DataContext property. This is a handy way to tell a FrameworkElement every time that you use data, this is where you will find it. Another nice feature of DataContext is that it is propagated to the children of the FrameworkElement. This way, you can just set it once and simplify all your bindings' syntax. We call this the explicit data context. Let's demonstrate this with the following steps 1. In the SilverlightDraw application in Visual Studio,...
Finding Silverlight Elements in JavaScript 1
Events can also be added to other elements in the Silverlight page, for example with the following steps 1. In JavaScriptDotNetTestPage.html, replace the function onSilverlightLoaded with the code shown in Listing 21.4. We use the sender we get as parameter of the onload event handler and find a Silverlight element the CounterButton by its name. Then we add event handlers for the MouseEnter and the MouseLeave events. LISTING 21.4 Registering and Unregistering Event Handler to a Silverlight...
Combining Shapes
Sometimes, you want to use existing paths and combine them to create a more complex one. The steps below show you how. To display the tangent again if it is hidden, use the Direct Selection tool A and click on an anchor point. 1. Delete everything on the screen and draw a blue rectangle. Then draw a red ellipse overlapping the rectangle. Select both paths. You can do this either by selecting the two paths with the Shift key pressed, or with the Ctrl key pressed, or by clicking anywhere on the...
NOTE Ckw
ObservableCollection is a wonderful class when you work with a variable number of items. Each time an item is added or removed or if the sorting order changes , the collection raises events. When you use an ObservableCollection as the source of a binding, the ItemsControl automatically updates its view when such an event occurs. Deriving from ObservableCollection is an elegant way to create a new collection and possibly to extend it with custom properties. We could also have declared the...
Packing and Laying out with Panels 1
Directly under FrameworkElement in the class hierarchy, we find another abstract class named System.Windows.Controls.Panel. This important class is responsible for grouping children, measuring them, and arranging them on the screen. This allows defining new ways to organize the children on the screen, with creativity as your only limit. In addition to being able to create your own Panel, the Silverlight framework also contains enough of them for most situations. Let's talk about them. Packing...
Decoding a JSON String
Flickr can return a response in a number of formats. The default is an XML document that can be parsed using LINQ as we did previously for our own media information file. Another interesting format is JSON, the JavaScript Object Notation that we discussed before. We can get a JSON response from Flickr by setting the parameter format json in the request URL see Listing 23.6 . JSON has the advantage of being compact and less verbose than XML which means that it will be loaded faster from the...
Registering Multiple JavaScript Event Handlers 1
We learned a lot about .NET to JavaScript to .NET communication in Chapter 8, Programming Silverlight with JavaScript, and Chapter 14. We also learned how to register a JavaScript handler for a .NET event. Consider the following steps 1. In Visual Studio, open the application JavaScriptDotNet that we created in Chapter 14. Make sure that JavaScriptDotNetWeb is set as start project and the page JavaScriptDotNetTestPage.html as start page. 2. In JavaScriptDotNetTestPage.html, in the constructor,...
Retrieving Initialization Parameters
The initialization parameters are parsed by the Silverlight framework when the application starts, and passed in a property of the StartupEventArgs, in the Application_Startup event handler in App.xaml.cs . Since this event is handled in the App class, you can get 454 CHAPTER 21 Taking Silverlight 2 Even Further the parameters there, for example, before instantiating the Page class. Let's see how with the following steps 1. In JavaScriptDotNet, modify the Page constructor in the Page.xaml.cs...
Making Requests to WCF Services 1
Silverlight is also equipped with more complex request mechanisms. In Chapter 23, we see how to place cross-domain calls to external services, such as Flickr. We can also place calls to web services either so-called ASMX web services or Windows Communication Foundation WCF based . ASMX web services were used a lot before WCF became available. Although Silverlight supports both, and ASMX web services continue to have a bright life, we only demonstrate a WCF-based service here. In this example,...





