Silverlight – View Model

Silverlight – View Model ”; Previous Next In this chapter, we will be looking at an important technique in Silverlight”s software development, the use of View Models. The view model is a key piece, which introduces a technique called separated presentation by keeping the view separate from the model. View Models offer one-way of achieving separated presentation, and we will see how they exploit Silverlight”s data binding to reduce the amount of code needed in your user interface. UI Development Challenges View Models are designed to solve certain problems that crop up frequently when developing user interface software. Perhaps the most important one is that user interface code is often difficult to inextricably test, especially with automated unit tests. There are also code quality problems that can affect the ongoing flexibility and maintainability of your code. If you follow the path of least resistance that Visual Studio”s design tools lead you down, you can end up putting far too much code into the code behind. It is very common to see large amounts of application functionality are added into the code behind. Few developers would actually plan to put business logic into a user interface class, but because that is where Visual Studio puts your event handlers, it becomes an all too convenient place to get the things done. It is widely accepted that software is easier to develop and maintain if classes have well-defined, and reasonably narrow responsibilities. The code behind”s job is to interact directly with the objects that make up the user interface where it is necessary. As soon as you start putting code that makes decisions about how your application behaves in there which tends to lead to problems. Not only can application logic flow into code that”s supposed to be concerned with the user interface, some developers start to rely on controls, and other user interface objects to hold important application state. The model simply holds the data, the view simply holds the formatted date, and the controller (ViewModel) acts as the liaison between the two. The controller might take input from the view and place it on the model and vice versa. Separated Presentation To avoid the problems caused by putting application logic in the code behind or XAML, it is best to use a technique known as separated presentation. Having XAML and code behind with the minimum required for working with user interface objects directly, a user interface classes also contain code for complex interaction behaviors, application logic, and everything else as shown below on left side. Important features of Seperated Presentation − With separated presentation, the user interface class is much simpler. It has XAML of course, but the code behind does as little as is practical. The application logic belongs in a separate class, which is often referred to as the model. Many developers attempt to use data binding to connect elements in the XAML directly to properties in the model. The problem is the model is entirely concerned with matters of what the application does, and not with how the user interacts with the application. Most user interfaces have some state that does not belong in the application model. For example, if your user interface uses a drag and drop, something needs to keep track of things like where the item being dragged is right now, how its appearance should change as it moves over possible drop targets, and how those drop targets might also change as the item is dragged over them. This sort of state can get surprisingly complex, and needs to be thoroughly tested. In practice, you normally want some other class sitting between the user interface and the model. This has two important roles. First, it adapts your application model for a particular user interface view. Second, it is where any nontrivial interaction logic lives, and by that, I mean code required to get your user interface to behave in the way you want. Model / View / ViewModel View Model is an example of the separated presentation approach, but let us be clear about exactly what sort of thing we have in each layer. There are three layers − Model View ViewModel Model This is a classic object model comprising of ordinary C# classes that has no direct relationship with the user interface. You would typically expect your Model codes to be able to compile without references to any user interface libraries. In fact, you would probably be able to take the exact same source code and compile it into a Silverlight application, an ordinary .NET Console application, or even server-side web code. The types in the Model should represent the concepts your application works with. View A View is normally a UserControl, it might be your MainPage, or it might just be some part of your page. In most Silverlight applications, it is a good idea to split your user interface up into small pieces defining a UserControl, or View for each piece. Silverlight applications are not unique in this respect. Something that is obviously Silverlight specific is the View. The more fine-grained your user interface is, the better things tend to be. Not only are you less likely to trip over other developers working on the same files, keeping things small and simple naturally discourages the shortcuts that lead to spaghetti-like code. For example, it is very common to define a View to represent an individual item in a List. ViewModel Finally, for each View, you write a ViewModel. So, this is one of the important features of a ViewModel class. It exists to serve a particular View. The ViewModel is specialized for a particular way of presenting things, such as a particular data item as it appears in Lists. This is why it is called a ViewModel; it adapts the underlying Model especially for a particular View. Like the Model, the ViewModel is also an ordinary C# class. It does not need to derive from any particular type.

Silverlight – Dynamic Layout

Silverlight – Dynamic Layout ”; Previous Next The Canvas is the least interesting of all of the Silverlight”s Layout panels. The other panels enable Dynamic Layouts, meaning that the layouts can adapt as the number of displayed items changes, or the size of the displayed information varies, or if the amount of space available to the application changes because the user has resized the browser. Silverlight offers two panels with Dynamic Layout strategies. StackPanel − which arranges elements in a vertical or horizontal stack. Grid − which provides a flexible grid-like, or table-like layout system. Stack Panel Stack panel is a simple and useful layout panel in XAML. In Stack Panel, the child elements can be arranged in a single line either horizontally or vertically based on their orientation property. It is often used whenever any kind of list needs to be created. ItemsControls use stack panels. Menu, ListBox and ComboBox are their default internal layout panel. Given below are the commonly used properties of StackPanel. Given below are the most commonly used properties of StackPanel. Sr. No. Property & Description 1 Background Gets or sets a Brush that fills the panel content area. (Inherited from Panel) 2 Children Gets a UIElementCollection of child elements of this Panel. (Inherited from Panel.) 3 Height Gets or sets the suggested height of the element. (Inherited from FrameworkElement.) 4 ItemHeight Gets or sets a value that specifies the height of all items that are contained within a WrapPanel. 5 ItemWidth Gets or sets a value that specifies the width of all items that are contained within a WrapPanel. 6 LogicalChildren Gets an enumerator that can iterate the logical child elements of this Panel element. (Inherited from Panel.) 7 LogicalOrientation The Orientation of the panel, if the panel supports layout in only a single dimension. (Inherited from Panel.) 8 Margin Gets or sets the outer margin of an element. (Inherited from FrameworkElement.) 9 Name Gets or sets the identifying name of the element. The name provides a reference so that code-behind, such as event handler code, can refer to a markup element after it is constructed during processing by a XAML processor. (Inherited from FrameworkElement.) 10 Orientation Gets or sets a value that specifies the dimension in which child content is arranged. 11 Parent Gets the logical parent element of this element. (Inherited from FrameworkElement.) 12 Resources Gets or sets the locally-defined resource dictionary. (Inherited from FrameworkElement.) 13 Style Gets or sets the style used by this element when it is rendered. (Inherited from FrameworkElement.) 14 Width Gets or sets the width of the element. (Inherited from FrameworkElement.) The following example shows how to add child elements into a StackPanel. Given below is the XAML implementation in which Buttons are created inside a StackPanel with some properties. <UserControl x:Class = “DynamicLayout.MainPage” xmlns = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/2006/xaml” xmlns:d = “http://schemas.microsoft.com/expression/blend/2008” xmlns:mc = “http://schemas.openxmlformats.org/markup-compatibility/2006” mc:Ignorable = “d” d:DesignHeight = “300” d:DesignWidth = “400”> <Grid x:Name = “LayoutRoot” Background = “White”> <StackPanel> <Button x:Name = “button” Content = “Button” Margin = “10” /> <Button x:Name = “button1” Content = “Button” Margin = “10”/> <Button x:Name = “button2” Content = “Button” Margin = “10”/> <Button x:Name = “button3” Content = “Button” Margin = “10”/> </StackPanel> </Grid> </UserControl> When the above code is compiled and executed, you will see the following output. The StackPanel tries to arrange for each element to have as much space as it requires in the direction of stacking. Now if you resize the browser, you will see that the width of the buttons have also changed. Grid Grid panel provides a flexible area, which consists of rows and columns. In Grid, the child elements can be arranged in tabular form. An element can be added to any specific row and column by using Grid.Row and Grid.Column properties. By default, the Grid panel is created with one row and one column. Multiple rows and columns are created by RowDefinitions and ColumnDefinitions properties. The height of the rows and the width of the columns can be defined in the following three ways − Fixed value − To assign a fixed size of logical units (1/96 inch). Auto − It will take the space, which is required for the controls in that specific row/column. Star (*) − It will take the remaining space when Auto and fixed sized are filled. Given below are the commonly used properties of Grid class. Given below are the most commonly used properties of Grid. Sr. No. Property & Description 1 Background Gets or sets a Brush that fills the panel content area. (Inherited from Panel) 2 Children Gets a UIElementCollection of child elements of this Panel. (Inherited from Panel.) 3 ColumnDefinitions Gets a list of ColumnDefinition objects defined on this instance of Grid. 4 Height Gets or sets the suggested height of the element. (Inherited from FrameworkElement.) 5 ItemHeight Gets or sets a value that specifies the height of all items that are contained within a WrapPanel. 6 ItemWidth Gets or sets a value that specifies the width of all items that are contained within a WrapPanel. 7 Margin Gets or sets the outer margin of an element. (Inherited from FrameworkElement.) 8 Name Gets or sets the identifying name of the element. The name provides a reference so that code-behind, such as event handler code, can refer to a markup element after it is constructed during processing by a XAML processor. (Inherited from FrameworkElement.) 9 Orientation Gets or sets a value that specifies the dimension in which child content is arranged. 10 Parent Gets the logical parent element of this element. (Inherited from FrameworkElement.) 11 Resources Gets or sets the locally-defined resource dictionary. (Inherited from FrameworkElement.) 12 RowDefinitions Gets a list of RowDefinition objects defined on this instance of Grid. 13 Style Gets or sets the style used by this element when it is rendered. (Inherited from FrameworkElement.) 14 Width Gets or sets the width of the element. (Inherited from FrameworkElement.) Given below are the commonly

Silverlight – Environment Setup

Silverlight – Environment Setup ”; Previous Next Microsoft provides two important tools for Silverlight application development. They are − Visual Studio Expression Blend Currently, both tools can create Silverlight projects, but the fact is that Visual Studio is used more by developers while Blend is still used more often by designers. Microsoft provides a free version of visual studio, which can be downloaded from https://www.visualstudio.com. For this tutorial, we will be mostly using Visual Studio. Installation Step 1 − Once Silverlight is downloaded, run the installer. The following dialog box will be displayed. Step 2 − Click the Install button and it will start the installation process. Step 3 − Once Sivelight is installed successfully, you will see the following dialog box. Step 4 − Close this dialog box and restart your computer if required. Step 5 − Now open Visual studio from the Start menu, which will open the dialog box shown below. It will take some time for preparation, while staring for the first time. Step 6 − Next, you will see the main window of Visual Studio. Step 7 − Now, to start with Silverlight application, you also need to install Silverlight Developer tool on your machine. Download and install the latest Silverlight Developer tool from here Step 8 − Click Install. It will take some time for installation. Step 9 − Once the installation is complete, you will see the following message. Step 10 − Now you are ready to build your first Silverlight application. Click Close. Print Page Previous Next Advertisements ”;

Silverlight – Controls

Silverlight – Controls ”; Previous Next All controls have interactive behavior of some kind such as, the way the button lights up when you move the mouse over it and pushes it when you press it, scrolling and selection behavior of a list box. In all the cases, the controls go beyond simple visibility. It might be more complex than it seems. These controls are a combination of the parents and the code. Silverlight allows a developer to easily build and create visually enriched UI based applications. The controls distinguish Silverlight from the other elements. Some important features are − The classical UI elements or controls in other UI frameworks are also enhanced in silverlight applications. Almost all of the standard Silverlight controls can be found in the Toolbox, which is a part of the System.Windows.Controls. These controls can also be created in XAML markup language. The complete inheritance hierarchy of Silverlight controls is as follows − Print Page Previous Next Advertisements ”;

Silverlight – CSS

Silverlight – CSS ”; Previous Next Since Silverlight content always runs inside a web page, the object tag is subject to normal CSS layout rules. There is no way for the plug-in to push a preferred size back to the browser, so regardless of what size the Silverlight content may want to be, its size and position will be wholly determined by the containing web page. The default Silverlight project template puts CSS in the web page that gives the object tag the whole of the browser window. The default XAML appears to have a fixed size, but if you look closely, you will see that the template sets the design width, and design height properties. These tell Visual Studio, or Blend, how large the user interface should look in the designer, but they allow it to resize at runtime. In Solution Explorer you will see {project name}TestPage.html file, which is the default HTML you get when you create a new Silverlight project in Visual Studio as shown below. The CSS at the top here, sets the HTML and body style to be 100%, which may seem a bit odd. Here is the complete html file, which contains different settings. <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”> <html xmlns = “http://www.w3.org/1999/xhtml” > <head> <title>FirstExample</title> <style type = “text/css”> html, body { height: 100%; overflow: auto; } body { padding: 0; margin: 0; } #silverlightControlHost { height: 100%; text-align:center; } </style> <script type = “text/javascript” src = “Silverlight.js”></script> <script type = “text/javascript”> function onSilverlightError(sender, args) { var appSource = “”; if (sender != null && sender != 0) { appSource = sender.getHost().Source; } var errorType = args.ErrorType; var iErrorCode = args.ErrorCode; if (errorType == “ImageError” || errorType == “MediaError”) { return; } var errMsg = “Unhandled Error in Silverlight Application ” + appSource + “n” ; errMsg += “Code: “+ iErrorCode + ” n”; errMsg += “Category: ” + errorType + ” n”; errMsg += “Message: ” + args.ErrorMessage + ” n”; if (errorType == “ParserError”) { errMsg += “File: ” + args.xamlFile + ” n”; errMsg += “Line: ” + args.lineNumber + ” n”; errMsg += “Position: ” + args.charPosition + ” n”; } else if (errorType == “RuntimeError”) { if (args.lineNumber != 0) { errMsg += “Line: ” + args.lineNumber + ” n”; errMsg += “Position: ” + args.charPosition + ” n”; } errMsg += “MethodName: ” + args.methodName + ” n”; } throw new Error(errMsg); } </script> </head> <body> <form id = “form1” runat = “server” style = “height:100%”> <div id = “silverlightControlHost”> <object data = “data:application/x-silverlight-2,” type = “application/xsilverlight-2” width = “100%” height = “100%”> <param name = “source” value = “ClientBin/FirstExample.xap”/> <param name = “onError” value = “onSilverlightError” /> <param name = “background” value = “white” /> <param name = “minRuntimeVersion” value = “5.0.61118.0” /> <param name = “autoUpgrade” value = “true” /> <a href = “http://go.microsoft.com/fwlink/?LinkID=149156&v=5.0.61118.0” style = “textdecoration:none”> <img src = “http://go.microsoft.com/fwlink/?LinkId=161376” alt = “Get Microsoft Silverlight” style = “border-style:none”/> </a> </object> <iframe id = “_sl_historyFrame” style = “visibility:hidden;height:0px; width:0px;border:0px”></iframe> </div> </form> </body> </html> Looking at the silverlightControlHost, we need to make sure it stars with a fixed height, say 300 pixels, and a width of 400 pixels, which matches the default design width and height in the XAML. You can also change these settings according to your application requirements. Overlapping Content By default, Silverlight and HTML contents cannot share the same space on the screen. If you make a content from both, such that they occupy the same space then only the Silverlight content will be visible. This is because, by default, Silverlight will ask the browser for its own private window, rendering all the content into that. It is a child window inside the browser, so it looks like a part of the web page, but it prevents the content from overlapping. The main reason for this is performance. By getting its own private area on the screen, Silverlight does not have to coordinate its rendering with a web browser. However, sometimes it is useful to have an overlapping content. There is a performance price to pay. You might find that animations do not run as smoothly when Silverlight and HTML share space on screen, but the extra layout flexibility may be worth the price. To use the overlapping content, you need to enable Windowless mode. In Windowless mode, the Silverlight plug-in renders to the same target window handler as the browser allowing the content to mingle. Zed index, or Z index is significant when the contents overlap. As far as HTML is concerned, the Silverlight content is a single HTML element, so it appears at exactly one place in the HTML Z order. This has an impact on mouse handling. If the Silverlight plug-in is at the top of the HMTL Z order, any mouse activity anywhere within its bounding box, will be delivered to the plug-in. Even if some areas of the plug-in are transparent, and you can see the HTML behind, you won”t be able to click it. However, if you arrange for the Z index with some HTML content to be on top, it will continue to be interactive even when it overlaps with Silverlight content. Example Take a look at the simple example given below in which we have a layout with a container, in which three divs have all been arranged to overlap inside of this containing div. <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”> <html xmlns = “http://www.w3.org/1999/xhtml” > <head> <title>HtmlOverlap</title> <style type = “text/css”> #container { position: relative; height: 300px; font-size: small; text-align:justify; } #silverlightControlHost { position: absolute; width: 400px; height: 300px; } #underSilverlight { position: absolute; left: 4px; width: 196px; } #overSilverlight { position: relative; left: 204px; width: 196px; } </style> <script type = “text/javascript” src = “Silverlight.js”></script> <script type = “text/javascript”> function onSilverlightError(sender, args) { var appSource = “”; if (sender != null && sender != 0) { appSource = sender.getHost().Source; } var errorType = args.ErrorType;

Silverlight – File Access

Silverlight – File Access ”; Previous Next In this chapter, we will see how Silverlight applications can access files on the end user”s computer. There are three main ways to access files in Silverlight. The choice will depend on the reason you need to use files, and on whether you are writing a trusted application. The most flexible option is to use the file dialog classes. With the Open and Save file dialogs, you can get access to any file that the end user chooses, as long as the user has appropriate permissions. User consent is central to this approach. The user has to choose which file to read, or when saving, they pick a file to overwrite or pick a location and a file name for you. The second option is to use the various classes in the System.IO namespace. Silverlight offers classes such as FileStream, StreamWriter, FileInfo, Directory, and DirectoryInfo, all of which make it possible to write code that opens and accesses files without needing to get the user involved. That may be more convenient for the developer, but of course, most users would not want any old code downloaded as part of a web page to be able to search around in their files. The third option is Isolated Storage, which we will discuss later. Open & Save File Dialogs SaveFileDialog The SaveFileDialog class shows the standard operating system supplied user interface for choosing where to save a file. Some important features are − To use it, we create an instance of the SaveFileDialog class. Calling ShowDialog, causes it to appear, and the return code tells us whether the user selected a place to save the file, or cancelled the dialog. You might be wondering about the redundant-looking comparison with True there. If ShowDialog returns True value, which means the user has selected a file. So we can go on to call the OpenFile method, which returns us a Stream. If we want to, we can discover the name the user chose. The dialog provides a property called SafeFileName, but that does not include the path. In any case, the only way to write data is to use the Stream returned by the dialog. From a developer’s perspective, this is just an ordinary .NET stream, so we can wrap it in a StreamWriter, to write text into it. OpenFileDialog The OpenFileDialog is similar in use to the SaveFileDialog. Obviously, you are always picking an existing file rather than a new one, but there is another important difference. It offers a property called MultiSelect. If you set that to True, the user can choose multiple files. This means the dialog needs a slightly more complex API. The SaveFileDialog only deals with one file at a time, but OpenFileDialog is able to cope with more, so it does not offer an OpenFile method. We need to expand the code. Depending on whether the dialog is in single file mode, or MultiSelect mode, you use either its File, or Files property. Here, in the below given example, we are in single file mode. Hence, we use File, and we call OpenRead on the FileInfo object that returns. In multiselect mode, we would use Files instead, which returns a collection of FileInfo objects. FileStream The second approach to file access as mentioned above is to use the FileStream class, or related types in the System.IO namespace directly. There is not very much to say about this, because for the most part, it is similar to file access with the full .NET Framework. However, there are a couple of Silverlight-specific twists. First, this approach lets you access files at any time without user intervention, and without any obvious visible indication of file activity, only trusted applications are allowed to use this technique. Remember, you need to run out of browser to get elevated trust. The second issue is that only files in certain specific folders are available. You can only read and write files that are under the User”s Documents, Music, Pictures, or Video files. One reason for this is that Silverlight runs on multiple platforms, and the file system structure for, say, an Apple Mac, is very different from that of Windows. Hence, cross-platform file access has to work in terms of a limited set of folders that are available on all systems Silverlight supports. Since these folders will be in different locations on different operating systems, and their location will typically vary from one user to another, you need to use the Environment.GetFolderPath method to discover the actual location at runtime. You can inspect the directory structure beneath the starting points. The Directory and DirectoryInfo classes in the System.IO namespace lets you enumerate files and directories. Consider a simple example in which file can open via OpenFileDialog and save some text to the file via SaveFileDialog. Given below is the XAML code in which two buttons and a text box are created. <UserControl x:Class = “FileDialogs.MainPage” xmlns = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/2006/xaml” xmlns:d = “http://schemas.microsoft.com/expression/blend/2008” xmlns:mc = “http://schemas.openxmlformats.org/markup-compatibility/2006” mc:Ignorable = “d” d:DesignHeight = “300” d:DesignWidth = “400”> <Grid x:Name = “LayoutRoot” Background = “White”> <Grid.RowDefinitions> <RowDefinition Height = “Auto” /> <RowDefinition Height = “265*” /> </Grid.RowDefinitions> <Button x:Name = “saveFileButton” Content = “Save” Width = “75” FontSize = “20” HorizontalAlignment = “Left” VerticalAlignment = “Top” Margin = “12,12” Click = “saveFileButton_Click” /> <Button x:Name = “openFileButton” Content = “Open” Width = “75” FontSize = “20” HorizontalAlignment = “Left” VerticalAlignment = “Top” Margin = “101,12,0,0” Click = “openFileButton_Click” /> <TextBox x:Name = “contentTextBox” Grid.Row = “1” Margin = “12” FontSize = “20” /> </Grid> </UserControl> Given below is C# code for click events implementation in which file is opened and saved. using System; using System.Diagnostics; using System.IO; using System.Windows; using System.Windows.Controls; namespace FileDialogs { public partial class MainPage : UserControl { public MainPage() { InitializeComponent(); } private void saveFileButton_Click(object sender, RoutedEventArgs e) { var save = new SaveFileDialog(); save.Filter = “Text Files (*.txt)|*.txt|All Files (*.*)|*.*”; save.DefaultExt

Silverlight – Video and Audio

Silverlight – Video & Audio ”; Previous Next In this chapter, we will see how Silverlight facilities are playing video and audio. The MediaElement is the heart of all video and audio in Silverlight. This allows you to integrate audio and video in your application. The MediaElement class works in a similar way like as Image class. You just point it at the media and it renders audio and video. The main difference is it will be a moving image, but if you point it to the file that contains just audio and no video such as an MP3, it will play that without showing anything on the screen. MediaElement as UI Element MediaElement derives from framework element, which is the base class of all Silverlight user interface elements. This means it offers all the standard properties, so you can modify its opacity, you can set the clip, or transform it and so. Let us have a look at a simple example of MediaElement. Open Microsoft Blend for Visual Studio and create a new Silverlight Application project. Now drag and video or audio file into Blend design surface. It will add a MediaElement to the surface and also add a copy of the video file in your project. You can see it in Solution explorer. You can move it around, change its size, you can do things like applying a rotation etc. Now, it will generate the related XAML for you in MainPage.xaml file like shown below. <UserControl x:Class = “MediaElementDemo.MainPage” xmlns = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/2006/xaml” xmlns:d = “http://schemas.microsoft.com/expression/blend/2008” xmlns:mc = “http://schemas.openxmlformats.org/markup-compatibility/2006” mc:Ignorable = “d” d:DesignHeight = “300” d:DesignWidth = “400”> <Grid x:Name = “LayoutRoot” Background = “White”> <MediaElement x:Name = “Microsoft_Silverlight_DEMO_mp4” Margin = “51,49,53,53” Source = “/Microsoft Silverlight DEMO.mp4” Stretch = “Fill” RenderTransformOrigin = “0.5,0.5”> <MediaElement.RenderTransform> <CompositeTransform Rotation = “-18.384″/> </MediaElement.RenderTransform> </MediaElement> </Grid> </UserControl> When the above application is compiled and executed, you will see that the video is playing on your web page. Controlling The MediaElement just presents the media. It does not offer any standard player controls. It starts playing automatically and stops when it reaches the end, and there is nothing a user can do to pause or otherwise control it. So in practice most applications will want to provide the user with a bit more control than that. You can disable the automatic playback by setting AutoPlay to False. This means the media player will not play anything until you ask it. <MediaElement x:Name = “Microsoft_Silverlight_DEMO_mp4” AutoPlay = “False” Margin = “51,49,53,53” Source = “/Microsoft Silverlight DEMO.mp4” Stretch = “Fill” RenderTransformOrigin = “0.5,0.5”> So when you want to play the video, you can just call the MediaElement Play() method. It also offers stop and pause methods. Let us have a look at the same example again and modify it little bit to allow a bit of control. Attach the MouseLeftButtonDown handler in MediaElement as shown in the XAML code below. <UserControl x:Class = “MediaElementDemo.MainPage” xmlns = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/2006/xaml” xmlns:d = “http://schemas.microsoft.com/expression/blend/2008” xmlns:mc = “http://schemas.openxmlformats.org/markup-compatibility/2006” mc:Ignorable = “d” d:DesignHeight = “300” d:DesignWidth = “400”> <Grid x:Name = “LayoutRoot” Background = “White”> <MediaElement x:Name = “Microsoft_Silverlight_DEMO_mp4” AutoPlay = “False” MouseLeftButtonDown = “Microsoft_Silverlight_DEMO_mp4_MouseLeftButtonDown” Margin = “51,49,53,53” Source = “/Microsoft Silverlight DEMO.mp4” Stretch = “Fill” RenderTransformOrigin = “0.5,0.5”> </MediaElement> </Grid> </UserControl> Here is the implementation on the MouseLeftButtonDown event handler in which it will check that if the current state of the media element is plating then it will pause the video otherwise it will start playing the video. using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; namespace MediaElementDemo { public partial class MainPage : UserControl { public MainPage() { InitializeComponent(); } private void Microsoft_Silverlight_DEMO_mp4_MouseLeftButtonDown (object sender, MouseButtonEventArgs e) { if (Microsoft_Silverlight_DEMO_mp4.CurrentState == MediaElementState.Playing) { Microsoft_Silverlight_DEMO_mp4.Pause(); } else { Microsoft_Silverlight_DEMO_mp4.Play(); } } } } When the above code is compiled and executed, you will see the blank web page because we have set the AutoPlay property to False. When you click the web page, it will start the video. When you click the web page again, it will pause the video. Print Page Previous Next Advertisements ”;

Silverlight – Browser Integration

Silverlight – Browser Integration ”; Previous Next In this chapter, we are going to see how a Silverlight application can work in conjunction with a web page using the browser integration support. We can explore Silverlight integration with the browser in the following two ways − JavaScript code running in the browser can access features within your Silverlight application. Silverlight has the ability to provide JavaScript wrappers for objects. Your .NET code running inside the Silverlight plug-in has access to the HTML DOM and other browser scripting features because of Silverlight .NET wrappers for JavaScript objects. We will see how a browser based software application can store information persistently on the client. Silverlight and HTML As far as the world of HTML is concerned, Silverlight content is just a single element. This is true for layout. The whole of the Silverlight plug-in and all its content looks like just a single object element. You must keep in mind that − Silverlight was not a replacement for HTML, it was designed to complement it. Therefore, the ability to access just another element in the DOM is important. It enables you to use Silverlight where appropriate. On a page, that mainly uses HTML, Silverlight integration with the world of the browser goes beyond merely existing as a DOM element, subject to normal HTML Layout. Accessing DOM The Silverlight content must able to participate fully in a web page. Therfore, it should be able to access the HTML DOM. Silverlight provides the bridge objects that wrap browser script objects as Dot Net objects, the Script object class in the system. The browser namespace provides methods that let you read and write properties and devote functions on the browser script object. You need a way to get hold of a Script object in the first place. Silverlight provides an HTML page class that gives you access to various pages of the features such as the Script objects. Let us have a look at a simple example in which we have a simple script that creates an object with a few attributes. Some of them are just values and a couple of them are functions. <script type = “text/javascript”> myJsObject = { answer: 42, message: “Hello, world”, modifyHeading: function(title) { document.getElementById(”heading”).innerHTML = title; }, performReallyComplexCalculation: function(x, y) { return x + y; } }; </script> Given below is the XAML code in which a button is added. <UserControl x:Class = “DomAccess.Page” xmlns = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/2006/xaml” Width = “400” Height = “300”> <Grid x:Name = “LayoutRoot” Background = “White”> <Button x:Name = “useDomButton” Content = “Use DOM” Width = “75” Height = “30” Click = “useDomButton_Click” /> </Grid> </UserControl> Here is the button click implementation in which a script is called which is created in HTML file. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using System.Windows.Browser; using System.Diagnostics; namespace DomAccess { public partial class Page : UserControl { public Page() { InitializeComponent(); } private void useDomButton_Click(object sender, RoutedEventArgs e) { ScriptObject myJsObject = HtmlPage.Window.GetProperty(“myJsObject”) as ScriptObject; string[] propertyNames = { “answer”, “message”, “modifyHeading”, “performReallyComplexCalculation” }; foreach (string propertyName in propertyNames) { object value = myJsObject.GetProperty(propertyName); Debug.WriteLine(“{0}: {1} ({2})”, propertyName, value, value.GetType()); } object result = myJsObject.Invoke(“performReallyComplexCalculation”, 11, 31); HtmlElement h1 = HtmlPage.Document.GetElementById(“heading”); h1.SetProperty(“innerHTML”, “Text from C# (without JavaScript”s help)”); h1.SetStyleAttribute(“height”, “200px”); } } } Given below is the complete HTML file. <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” ” http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”> <html xmlns = “http://www.w3.org/1999/xhtml” > <!– saved from url = (0014)about:internet –> <head> <title>DomAccess</title> <script type = “text/javascript”> myJsObject = { answer: 42, message: “Hello, world”, modifyHeading: function(title) { document.getElementById(”heading”).innerHTML = title; }, performReallyComplexCalculation: function(x, y) { return x + y; } }; </script> <style type = “text/css”> html, body { height: 100%; overflow: auto; } body { padding: 0; margin: 0; } #silverlightControlHost { height: 100%; } </style> <script type = “text/javascript” src = “Silverlight.js”></script> <script type = “text/javascript”> function onSilverlightError(sender, args) { var appSource = “”; if (sender != null && sender != 0) { appSource = sender.getHost().Source; } var errorType = args.ErrorType; var iErrorCode = args.ErrorCode; var errMsg = “Unhandled Error in Silverlight 2 Application ” + appSource + “n” ; errMsg += “Code: “+ iErrorCode + ” n”; errMsg += “Category: ” + errorType + ” n”; errMsg += “Message: ” + args.ErrorMessage + ” n”; if (errorType == “ParserError”) { errMsg += “File: ” + args.xamlFile + ” n”; errMsg += “Line: ” + args.lineNumber + ” n”; errMsg += “Position: ” + args.charPosition + ” n”; } else if (errorType == “RuntimeError”) { if (args.lineNumber != 0) { errMsg += “Line: ” + args.lineNumber + ” n”; errMsg += “Position: ” + args.charPosition + ” n”; } errMsg += “MethodName: ” + args.methodName + ” n”; } throw new Error(errMsg); } </script> </head> <body> <!– Runtime errors from Silverlight will be displayed here. This will contain debugging information and should be removed or hidden when debugging is completed –> <div id = ”errorLocation” style = “font-size: small;color: Gray;”></div> <h1 id = ”heading”></h1> <div id = “silverlightControlHost”> <object data = “data:application/x-silverlight-2,” type = “application/x-silverlight-2” width = “100%” height = “100%”> <param name = “source” value = “ClientBin/DomAccess.xap”/> <param name = “onerror” value = “onSilverlightError” /> <param name = “background” value = “white” /> <param name = “minRuntimeVersion” value = “2.0.30923.0” /> <param name = “autoUpgrade” value = “true” /> <a href = “http://go.microsoft.com/fwlink/?LinkID=124807” style = “text-decoration: none;”> <img src = “http://go.microsoft.com/fwlink/?LinkId=108181” alt = “Get Microsoft Silverlight” style = “border-style: none”/> </a> </object> <iframe style = ”visibility:hidden;height:0;width:0;border:0px”></iframe> </div> </body> </html> When the above code is compiled and executed, you will see all the values in the output window, which are fetched from the HTML file. Print Page Previous Next Advertisements ”;

Silverlight – Text

Silverlight – Text ”; Previous Next In this chapter, we will look at what Silverlight offers to display text. The text block is used for all text rendering and Silverlight. Other important features are − It can be used to simple plain text or you can apply a mixture of formatting styles. Silverlight supports a standard set of built in fonts. You can also download custom fonts when your applications visual style need something less ordinary. TextBlock To display text we use Silverlight textbook element, which is a lightweight control for displaying small amounts of read-only text. In fact, we have already seen this quite a lot as its basic usage does not really need much explanation. You just set the text property and it displays that text for you. <TextBlock Text = “Print Testing” HorizontalAlignment Center” FontFamily = “Georgia”/> The hierarchical inheritance of TextBlock class is as follows, Given below are the commonly used properties of TextBlock class. Given below are the most commonly used properties of TextBlock. Sr. No. Property & Description 1 ContentEnd Gets a TextPointer object for the end of text content in the TextBlock. 2 ContentStart Gets a TextPointer object for the start of text content in the TextBlock. 3 IsTextSelectionEnabled Gets or sets a value that indicates whether text selection is enabled in the TextBlock, either through user action or calling selection-related API. 4 IsTextSelectionEnabledProperty Identifies the IsTextSelectionEnabled dependency property. 5 LineHeight Gets or sets the height of each line of content. 6 MaxLines Gets or sets the maximum lines of text shown in the TextBlock. 7 SelectedText Gets a text range of selected text. 8 SelectionEnd Gets the end position of the text selected in the TextBlock. 9 SelectionHighlightColor Gets or sets the brush used to highlight the selected text. 10 SelectionStart Gets the starting position of the text selected in the TextBlock. 11 Text Gets or sets the text contents of a TextBlock. 12 TextAlignment Gets or sets a value that indicates the horizontal alignment of text content. 13 TextTrimming Gets or sets the text trimming behavior to employ when content overflows the content area. 14 TextWrapping Gets or sets how the TextBlock wraps text. Given below are commonly used events of TextBlock class. Given below are the most commonly used events of TextBlock. Sr. No. Event & Description 1 ContextMenuOpening Occurs when the system processes an interaction that displays a context menu. 2 SelectionChanged Occurs when the text selection has changed. Given below are the commonly used methods in TextBlock class. Given below are the most commonly used methods of TextBlock. Sr. No. Method & Description 1 Focus Focuses the TextBlock, as if it were a conventionally focusable control. 2 Select Selects a range of text in the TextBlock. 3 SelectAll Selects the entire contents in the TextBlock. Run Sometimes you want fine-grained control over formatting and setting one style for an entire text block. It is sometimes useful to format individual words or even letters, and if you want this then instead of using the Text property, you put the text inside the TextBlock as content. If you are using a code, this corresponds to adding items to the TextBlock inline property. Using this approach, you can add a series of run elements. Each Run supports the same font family, front weight, foreground and so on properties for controlling the text style. Although Run is a separate element this does not disrupt the flow. Let us have a look at a simple example, which contains multiple Run element inside TextBlock. Given below is the XAML code. <UserControl x:Class = “SilverlightRunDemo.MainPage” xmlns = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/2006/xaml” xmlns:d = “http://schemas.microsoft.com/expression/blend/2008” xmlns:mc = “http://schemas.openxmlformats.org/markup-compatibility/2006” mc:Ignorable = “d” d:DesignHeight = “300” d:DesignWidth = “400”> <Grid x:Name = “LayoutRoot” Background = “White”> <TextBlock Width = “192” TextWrapping = “Wrap” FontFamily = “Verdana”> <Run Text = “Hello, ” /> <Run FontWeight = “Bold” Text = “world!” /> <Run Text = “You” /> <Run FontStyle = “Italic” Text = ” are ” /> <Run Text = “learning” FontSize = “40” FontFamily = “01d English Text MT” /> <Run Text = ” the ” /> <Run Text = “basics of ” Foreground = “Blue” /> <Run Text = ” Silverlight.” FontSize = “30” /> </TextBlock> </Grid> </UserControl> When the above code is compiled and executed, you will see the following output. As you can see, this text block is arranged with different formatting styles by using the Run element. By the way, you do not need to wrap every single bit of text in a run. You can leave most of the content of a text block as plain text and just apply run to the parts that need different formatting as shown below. <TextBlock> Hello, <Run FontWeight = “Bold” Text =” world!”/> </TextBlock> LineBreak Silverlight usually ignores line breaks in the XAML. It assumes that most white spaces are there to make them easier to read because you actually want that space to appear. Let us have a look at this XAML code, which has three separate lines of text in it. <TextBlock> This is not the end. It is not even the beginning of the end. But it is, perhaps, the end of the beginning </TextBlock> When the above code is compiled and executed, you will see the following output. As you can see that it has ignored the line breaks and executed all the text together. If you enable text wrapping, it will put line breaks in where it needs to be to make the text fit but it will ignore the line breaks in your example. If you just want to add explicit line breaks, you need to add a line break tag inside your text block. The text follows it will start on a new line. Let us have a look at the same example again by adding the LineBreak tag. <TextBlock FontSize = “16”> This is not the end. <LineBreak/> It is not even the beginning of

Silverlight – Home

Silverlight Tutorial PDF Version Quick Guide Resources Job Search Discussion Silverlight is a platform for building rich internet applications. This tutorial will explain the concepts behind Silverlight, and will show you how to build it into your web applications. After completing this tutorial, you will have a better understanding of Silverlight applications and how to develop them using XAML and C#. Audience This tutorial has been prepared for anyone who has a basic knowledge of XAML and C# and has an urge to develop websites. After completing this tutorial, you will find yourself at a moderate level of expertise in developing websites using Silverlight. Prerequisites Before you start proceeding with this tutorial, we are assuming that you are already aware about the basics of XAML and C#. If you are not well aware of these concepts, then we will suggest you to go through our short tutorials on XAML and C#. Print Page Previous Next Advertisements ”;