Discuss Silverlight ”; Previous Next 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 understating of Silverlight applications and how to develop them using XAML and C#. Print Page Previous Next Advertisements ”;
Category: silverlight
Silverlight – Printing
Silverlight – Printing ”; Previous Next Printing is an important capability for certain kinds of applications. In this chapter, we will look at the relevant facilities in Silverlight. Printing APIs, and the basic steps that all Silverlight applications must perform if they want to print. Various options for choosing water print. The simplest is to print a copy of user interface elements that are already on the screen. Most applications will want to get a bit more advanced than this, and generate content adapted specifically for printing, and in some cases, it will be necessary to split the content across multiple pages. Steps for Printing Whether you are printing a snapshot or something already on screen, or going for a fully customized multi-page print output, the same basic steps are required. At the heart of the printing API is the PrintDocument class. You begin by constructing one of these, and when you call its Print method, it shows the standard user interface for starting a print job. The user can select a printer and configure the settings as usual. If the user then decides to go ahead by clicking Print, the PrintDocument will immediately raise its PrintPage event, and your handler for that event supplies the contents to be printed. The event argument offers a PageVisual property for this purpose. You can set it to any Silverlight user interface element, either one already visible on screen, or a new one you created especially for printing. Printing Existing Elements Elements The simplest option is to print the content that is already on screen in your Silverlight application. Since the PrintPage event arguments PageVisual, accepts any user interface elements, you can pick anything in your user interface, and print it. It is only a small step up from using the PrintScreen key to grab a screenshot. It is marginally better than that because the user does not have to manually paste the screenshot into some other program to crop it and print it. It is still only a slight improvement. Printing content that is already on screen is problematic. First of all, there is no guarantee that a layout that works on screen will work well for paper. Let us have a look at a simple example in which the ScrollViewer contains some UI elements and its layout adapted for the screen. It resizes based on the browser window size, and it offers scroll bars to ensure that everything is accessible even if it does not fit. Given below is the XAML code. <UserControl 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” xmlns:sdk = “http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk” x:Class = “SilverlightPrinting.MainPage” mc:Ignorable = “d” d:DesignHeight = “300” d:DesignWidth = “500”> <Grid x:Name = “LayoutRoot” Background = “White”> <Button x:Name = “print” Content = “Print” Click = “print_Click” Width = “60” Height = “20” Margin = “10,10,430,270”/> <ScrollViewer x:Name = “myScrollViewer” HorizontalScrollBarVisibility = “Auto” VerticalScrollBarVisibility = “Auto” Width = “400” Margin = “90,0,10,0”> <StackPanel> <Rectangle Fill = “Gray” Width = “100” Height = “100” /> <Button x:Name = “button” Content = “Button” Width = “75”/> <sdk:Calendar Height = “169” Width = “230”/> <Rectangle Fill = “AliceBlue” Width = “475” Height = “100” /> </StackPanel> </ScrollViewer> </Grid> </UserControl> Here is the Print button click-event implementation, which will print the ScrollViewer and its visible data. using System; using System.Windows; using System.Windows.Controls; using System.Windows.Printing; namespace SilverlightPrinting { public partial class MainPage : UserControl { public MainPage() { InitializeComponent(); } private void print_Click(object sender, RoutedEventArgs e) { PrintDocument pd = new PrintDocument(); pd.PrintPage += new System.EventHandler<PrintPageEventArgs>(pd_PrintPage); pd.Print(“Print Screen Content”); } private void pd_PrintPage(object sender, PrintPageEventArgs e) { e.PageVisual = myScrollViewer; } } } As you can see, in Print button click event that PrintDocument object is created, we attach a handler to its PrintPage event. You can set the PageVisual property to refer to ScrollViewer. Then Print method is called. This takes a string, which will show up as the job name in the print queue. When the above code is compiled and executed, you will see the following output. When you click the Print button, you will see the standard Print dialog. Now, select the default printer. For the purpose of demonstration, let us select OneNote and click the Print button. You will see that ScrollViewer is printed. Notice that the scroll bars are still visible on the ScrollViewer. Custom UI Tree Instead of printing content that is already onscreen, it usually makes more sense to build a tree of user interface elements specifically for printing. That way, you can ensure that you use only non-interactive elements on paper, and you can create a specialized layout that is better suited to the paper shape and size. You could create a UserControl just for printing. Let us have a look at a simple example by creating a Silverlight project and add a UserControl called PrintLayout. Set the design time width and height to be approximately paper shaped. Given below is the XAML code of PrintLayout.xaml file. <UserControl x:Class = “PrintCustomUI.PrintLayout” 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 = “768” d:DesignWidth = “960”> <Grid x:Name = “LayoutRoot” Background = “White”> <Grid.RowDefinitions> <RowDefinition Height = “Auto” /> <RowDefinition /> <RowDefinition Height = “Auto” /> </Grid.RowDefinitions> <TextBlock Text = “Silverlight” HorizontalAlignment = “Center” FontSize = “60” FontWeight = “Bold” FontFamily = “Georgia” /> <TextBlock Grid.Row = “2” Text = “Print Testing” HorizontalAlignment = “Center” FontFamily = “Georgia” FontSize = “24” Margin = “0,10”/> <Rectangle Grid.Row = “2” Height = “1” Fill = “Black” VerticalAlignment = “Top”/> <Ellipse Grid.Row = “1” Stroke = “Black” StrokeThickness = “10” Margin = “10”> <Ellipse.Fill> <RadialGradientBrush GradientOrigin = “0.2,0.2” Center = “0.4,0.4”> <GradientStop Color = “Aqua” Offset = “0.006” /> <GradientStop Color = “AntiqueWhite” Offset = “1” /> </RadialGradientBrush> </Ellipse.Fill> </Ellipse> </Grid> </UserControl> Given below is the code in the MainPage.xaml file, which contains a Print button only. <UserControl x:Class = “PrintCustomUI.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”
Silverlight – Quick Guide
Silverlight – Quick Guide ”; Previous Next Silverlight – Overview Welcome to Silverlight tutorials. 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 it, you will have a better understanding of Silverlight applications using XAML and C#. What is Silverlight Silverlight is a browser plug-in, designed for building rich internet applications; applications that run in the browser like normal web applications, but which try to advance the user interface beyond where HTML can go. For example, Silverlight is a framework for building rich, browser-hosted applications that run on a variety of operating systems. It can also co-exist with HTML. Therefore, Silverlight can enhance an existing web application. Silverlight works its magic through a browser plug-in. When you surf to a web page that includes Silverlight content, this browser plug-in runs, executes the code, and renders that content in a specifically designated region of the page. The important part is that the Silverlight plug-in provides a richer environment than the traditional blend of HTML and JavaScript that powers ordinary web pages. You can create Silverlight pages that play video, have hardware accelerated 3D graphics, and use vector animations. From a developer”s perspective, the most interesting feature of Silverlight is that it brings the .NET Framework programming model to the client side of your web applications. Silverlight is designed to run inside the web pages, so it can run as a browser plugin. It provides graphical services for rendering bitmaps, vector graphics, highdefinition video, and animations. You can write in C#, or Visual Basic .NET, and use the .NET Framework class library features on the code that runs in the web browser. Silverlight user interfaces, themselves use a very similar model to Windows Presentation Foundation(WPF), which is the user interface framework in the full desktop .NET Framework. If you know WPF, Silverlight is easy to learn. Silverlight is a much smaller download than .NET. It is roughly a tenth of the size, so only a subset of the class library is present, and various implications have been made to WPF”s model. Despite the reduced scale, experienced .NET developers will feel instantly at home in Silverlight. Platforms and Browsers The platforms and browsers supported by Silverlight are − Windows Silverlight supports Windows, as you would expect of a Microsoft product. It requires Windows XP Service Pack 2 at least or recent versions of Windows. The older versions are not fully supported. For example, Silverlight will not run at all on Windows ME, and Windows 2000 has limited support. As for the browsers, Silverlight supports Microsoft”s own Internet Explorer, of course, and it supports Firefox, and Google Chrome version 4. Broadly, Silverlight supports the common web browser plug-in API. It works in a wider range of browsers than the officially supported list. Mac Silverlight supports Mac OS10, although Silverlight version 2 or later only runs on Intel-based Macs. On modern Macs, both Firefox and Safari are supported. Linux Microsoft”s own Silverlight plug-in does not run on Linux, but the Mono open source project has an offshoot called Moonlight, which is a Silverlight compatible plug-in that runs on Linux. Moonlight runs in Firefox, and interestingly has always been able to run in Standalone mode. One of the reasons the Mono project decided to build Moonlight in the first place is that they thought Silverlight would be a useful technology for building user interface widgets that run on the desktop. Silverlight – Environment Setup 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 http://silverlight.dlservice.microsoft.com/download/8/E/7/8E7D9B4B-2088-4AED8356-20E65BE3EC91/40728.00/Silverlight_Developer_x64.exe 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. Silverlight – Getting Started In this chapter, we will look at a working example of Silverlight. We need two things − First, we require a web page. Silverlight is intended for rich internet applications, It is designed to run inside of a web browser as part of a web page. The page needs to incorporate a suitable tag to load the Silverlight plug-in. It can also include the logic to detect whether Silverlight is installed, and can provide some fallback user interface, when it is absent. The second thing we need is the Silverlight content itself. This tutorial will focus on the .NET programming model for Silverlight. We will create a compiled Silverlight application containing a mixture of XAML, the mockup language we use to define Silverlight user interfaces, and .NET code written in C#. Create a Web-page The easiest way to start using Silverlight is to create an ordinary website with HTML pages and no server side code. Let us look
Applications, Resources & Deployment ”; Previous Next In this chapter, we are going to look at common issues around creating and deploying applications and the resources they need. Loading the Plug-in The minimum requirements for running a Silverlight application are hosting web page containing an object tag to load the Silverlight plug-in, and the compiled Silverlight content itself. As you saw, we used param tags in the object tag to point to the content. HTML <Object> tag There are other parameters we can pass in to control features such as the user interface to be shown while the content is downloaded, the JavaScript code to run in the event of an error, and fallback content to be shown if Silverlight is not installed. <Object> in HTML Here is an example object tag that loads some Silverlight content. You have seen this before, but we are going to look at a few things in a bit more detail, starting with the attributes on the object tag itself. Type Attribute The type attribute contains a MIME type identifying this as a Silverlight element. This is how the browser knows what sort of embedded content we are using. The object tag is surprisingly flexible. It is not just for plug-ins. You can use it to host embedded images, or HTML, as well as plug-in-based content, such as Silverlight, or Flash. If the Silverlight plug-in is installed, this will load it. If not, the standard format behavior is for the browser to render any HTML content inside the object tag as though the object and param tags were not there. <object data = “data:application/x-silverlight-2,” type = “application/x-silverlight-2” width = “100%” height = “100%”> <param name = “source” value = “ClientBin/DataBinding.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> Data Attribute The next attribute, data, is a little less obvious. The comma at the end is meant to be there. Some important features are − This attribute is not technically necessary, but Microsoft recommends you add it because some web browsers have a rather surprising behavior when loading plugins. The object tag is designed to host embedded content, so browsers expect a binary string to be involved, a bitmap file, or a video, or audio stream, or something. You would normally expect to put a URL in the data attribute, and the browser to download that data, and pass it to the plug-in. The data attribute takes a URI, and usually it will be pointed at some data, such as a JPEG file, but here, we are using a slightly unusual URI scheme. <param> Tags We have various param tags inside the object, starting with the source param. <param name = “source” value = “ClientBin/DataBinding.xap”/> It gives the plug-in from where to download the Silverlight content. You should provide a JavaScript error handler. This will be called if the download process fails. It will also be called if an unhandled exception is thrown, once the Silverlight code is up and running. <param name = “onError” value = “onSilverlightError” /> So it”s not just for load failures. You should also specify the minimum version of Silverlight required by your code. Microsoft encourages the users to keep up to date, so once a machine has the Silverlight plug-in installed, new versions will be offered via Windows update, but it is always possible that a user will be running an older version than the one you require. <param name = “minRuntimeVersion” value = “5.0.61118.0” /> <param name = “autoUpgrade” value = “true” /> This minRuntimeVersion parameter lets you say which version you need. If the installed version is older, the onError handler will be invoked. Silverlight passes numeric error codes to the error handling JavaScript function, and there is a distinct error code, ‘8001’ as it happens, to indicate that the plug-in is out of date. You can write JavaScript code to respond to the problem, or you can just ask the plug-in to attempt to upgrade for you. Here, the autoUpgrade parameter is set to ‘True’, which means that if the installed plugin is out of date, Silverlight will automatically show a message telling the user that a more recent version is required, offering to install it for them. Fallback HTML Content After the param tags, comes the fallback HTML content to be used if Silverlight is not installed. The standard browser behavior for object tags whose MIME type is unknown is to act as though the object and param tags were not there at all. So, this a tag and its contents will be shown in systems that do not have the Silverlight plug-in. <a href = “http://go.microsoft.com/fwlink/?LinkID=149156&v=5.0.61118.0” style = “text-decoration:none”> <img src = “http://go.microsoft.com/fwlink/?LinkId=161376” alt = “Get Microsoft Silverlight” style = “border-style:none”/> </a> Notice the two URLs to the go.microsoft.com site, a hyperlink, and an image. The image link resolves to a bitmap with some Silverlight branding, and some text offering to install Silverlight. The endpoint for the hyperlink is moderately smart. The server inspects the user agent to decide where to redirect. It may serve back the Silverlight Install executable, or if the user is on an unsupported platform, it will direct the browser to a page containing information about Silverlight. Silverlight.js There is an alternative to the HTML object tag for loading Silverlight content. Microsoft provides a JavaScript file called Silverlight.js that allows the loading process to be managed from the browser script. Visual Studio adds a copy when you create a web project to host a newly created Silverlight project. The Silverlight SDK also contains a copy of this file. The main benefit of Silverlight.js is that it allows more flexibility when Silverlight is not installed. XAML Resources Silverlight also offers a mechanism
Silverlight – Isolated Storage ”; Previous Next The third file access mechanism is Isolated Storage mechanism, which provides storage associated with the logged in user. The API presents data through the Stream class from .NET System.IO namespace. Therefore, as with the other mechanisms we have looked at so far, you can use the other types in System.IO to work with the streams, enabling you to store either textual or binary data. Some important features are − This storage mechanism is called Isolated Storage because the store is partitioned, and a Silverlight application has access only to certain parts. You cannot access any old stored data. First of all, the store is partitioned per user. A Silverlight application cannot get access to the store for a different user than the one logged in, and running the application. This has nothing to do with any identification mechanisms your web application may use. That is an important point to remember because some people who share computers do not bother with separate Windows accounts, and are accustomed just to logging in and out of the websites that they use. Using Isolated Storage Isolated Storage is not unique to Silverlight. The API was originally introduced for Windows Forms to enable applications launched from the web to store data locally in partial trust scenarios. The implementation is different, and there is no way to access the full .NET Framework”s Isolated Storage from Silverlight”s, or vice versa. However, if you have used it, the steps here will look very familiar. You begin by asking for the user specific store. In this case, we are asking for the one for the application. If we wanted the per-site store shared by all XAPs on the site, we would call GetUserStoreForSite instead. Either method returns an IsolatedStorageFile object, which is a pretty unhelpful name as this represents a directory, not a file. To access a file, you need to ask the IsolatedStorageFile for a Stream. We use the IsolatedStorageFileStream class, and its constructor requires you to pass the IsolatedStorageFile object as an argument. So we are creating a new file in the store. The exact location of the file on disk is unknown. The containing directory has randomized elements in order to make it impossible to guess the name of the file. Without this, it might be possible for malicious websites to place a file on the user”s computer, and then construct a file URL to open it, in the hope of fooling the user into clicking a link that executes a program locally. There are various other safeguards built into Windows that try to prevent this from happening, but this is another layer of defense in case the others have somehow been disabled, or bypassed. The file will be stored somewhere inside the user”s profile, but that is as much as you can know about it. Your IsolatedStorageFileStream will not report its true location. Let us have a look at a simple example that tracks how many times the application has been run. Given below is the XAML code. <UserControl x:Class = “StoreRunCount.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 x:Name = “runCountText” FontSize = “20” /> </Grid> </UserControl> Here is the C# code in which Isolated storage are used. 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.IO.IsolatedStorage; using System.IO; namespace StoreRunCount { public partial class MainPage : UserControl { const string RunCountFileName = “RunCount.bin”; public MainPage() { InitializeComponent(); int runCount = 0; using (var store = IsolatedStorageFile.GetUserStoreForApplication()) { if (store.FileExists(RunCountFileName)) { using (var stm = store.OpenFile(RunCountFileName, FileMode.Open, FileAccess.Read)) using (var r = new BinaryReader(stm)) { runCount = r.ReadInt32(); } } runCount += 1; using (var stm = store.OpenFile(RunCountFileName, FileMode.Create, FileAccess.Write)) using (var w = new BinaryWriter(stm)) { w.Write(runCount); } } runCountText.Text = “You have run this application ” + runCount.ToString() + ” time(s)”; } } } When the above code is compiled and executed, you will see the following webpage which will show you that how many times you run this application. Increasing Your Quota Applications may ask for more space if the initial amount is insufficient for some reason. There is no guarantee that the request will succeed. Silverlight will ask the user if they are happy to grant the application more space. By the way, you are only allowed to ask for more storage in response to user input, such as a click. If you try to ask it some other time, such as when the plug-in loads, or in a timer handler, Silverlight will automatically fail the request without even prompting the user. Extra quota is only available to the applications with which the user is interacting. The IsolatedStorageFile object provides three members for managing quota − AvailableFreeSpace IncreaseQuotaTo Quota AvailableFreeSpace The AvailableFreeSpace property tells you how much of your quota remains free. Note that even an empty subdirectory consumes some of your quota because the operating system needs to allocate space on disk to represent the directory. So, the available space may be less than the total quota, minus the sum size of all your files. IncreaseQuotaTo If you do not have sufficient space to proceed, you ask for more by calling the IncreaseQuotaTo method. Quota Here we are using the third property, Quota, to discover the current quota size, and then we are adding the amount extra we require to get our new requested quota. The method returns either True or False to indicate whether we are allocated what we asked for. Note that Silverlight may decide to allocate more space than you asked for. Here is a simple example to increase the quota, when the button is clicked. Given below is the XAML code. <UserControl x:Class = “ChangeQuota.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”
Silverlight – Buttons
Silverlight – Buttons ”; Previous Next The Button class represents the most basic type of button control. Silverlight recognizes three types of button controls: the familiar Button, the CheckBox, and the RadioButton. All of these controls are content controls that are derived from ButtonBase. The hierarchical inheritance of Button class is as follows − Given below are the most commonly used Properties of a button. Given below are the most commonly used properties of Button. Sr. No. Property & Description 1 Background Gets or sets a brush that provides the background of the control. (Inherited from Control) 2 BorderBrush Gets or sets a brush that describes the border fill of a control. (Inherited from Control) 3 BorderThickness Gets or sets the border thickness of a control. (Inherited from Control) 4 Content Gets or sets the content of a ContentControl. (Inherited from ContentControl) 5 ClickMode Gets or sets a value that indicates when the Click event occurs, in terms of device behavior. (Inherited from ButtonBase) 6 ContentTemplate Gets or sets the data template that is used to display the content of the ContentControl. (Inherited from ContentControl) 7 FontFamily Gets or sets the font used to display text in the control. (Inherited from Control) 8 FontSize Gets or sets the size of the text in this control. (Inherited from Control) 9 FontStyle Gets or sets the style in which the text is rendered. (Inherited from Control) 10 FontWeight Gets or sets the thickness of the specified font. (Inherited from Control) 11 Foreground Gets or sets a brush that describes the foreground color. (Inherited from Control) 12 Height Gets or sets the suggested height of a FrameworkElement. (Inherited from FrameworkElement) 13 HorizontalAlignment Gets or sets the horizontal alignment characteristics that are applied to a FrameworkElement when it is composed in a layout parent, such as a panel or items control. (Inherited from FrameworkElement) 14 IsEnabled Gets or sets a value indicating whether the user can interact with the control. (Inherited from Control) 15 IsPressed Gets a value that indicates whether a ButtonBase is currently in a pressed state. (Inherited from ButtonBase) 16 Margin Gets or sets the outer margin of a FrameworkElement. (Inherited from FrameworkElement) 17 Name Gets or sets the identifying name of the object. When a XAML processor creates the object tree from XAML markup, run-time code can refer to the XAMLdeclared object by this name. (Inherited from FrameworkElement) 18 Opacity Gets or sets the degree of the object”s opacity. (Inherited from UIElement) 19 Resources Gets the locally defined resource dictionary. In XAML, you can establish resource items as child object elements of a frameworkElement.Resources property element, through XAML implicit collection syntax. (Inherited from FrameworkElement) 20 Style Gets or sets an instance Style that is applied for this object during layout and rendering. (Inherited from FrameworkElement) 21 Template Gets or sets a control template. The control template defines the visual appearance of a control in UI, and is defined in XAML markup. (Inherited from Control) 22 VerticalAlignment Gets or sets the vertical alignment characteristics that are applied to a FrameworkElement when it is composed in a parent object such as a panel or items control. (Inherited from FrameworkElement) 23 Visibility Gets or sets the visibility of a UIElement. A UIElement that is not visible is not rendered and does not communicate its desired size to layout. (Inherited from UIElement) 24 Width Gets or sets the width of a FrameworkElement. (Inherited from FrameworkElement) Given below are the commonly used methods of Button. Given below are the most commonly used methods of Button. Sr. No. Method & Description 1 ClearValue Clears the local value of a dependency property. (Inherited from DependencyObject) 2 FindName Retrieves an object that has the specified identifier name. (Inherited from FrameworkElement) 3 OnApplyTemplate Invoked whenever application code or internal processes (such as a rebuilding layout pass) call ApplyTemplate. In simplest terms, this means the method is called just before a UI element displays in your app. Override this method to influence the default post-template logic of a class. (Inherited from FrameworkElement) 4 OnContentChanged Invoked when the value of the Content property changes. (Inherited from ContentControl) 5 OnDragEnter Called before the DragEnter event occurs. (Inherited from Control) 6 OnDragLeave Called before the DragLeave event occurs. (Inherited from Control) 7 OnDragOver Called before the DragOver event occurs. (Inherited from Control) 8 OnDrop Called before the Drop event occurs. (Inherited from Control) 9 OnGotFocus Called before the GotFocus event occurs. (Inherited from Control) 10 OnKeyDown Called before the KeyDown event occurs. (Inherited from Control) 11 OnKeyUp Called before the KeyUp event occurs. (Inherited from Control) 12 OnLostFocus Called before the LostFocus event occurs. (Inherited from Control) 13 SetBinding Attaches a binding to a FrameworkElement, using the provided binding object. (Inherited from FrameworkElement) Given below are the commonly used Events of Button. Given below are the most commonly used events of Button. Sr. No. Event & Description 1 Click Occurs when a button control is clicked. (Inherited from ButtonBase) 2 DataContextChanged Occurs when the value of the FrameworkElement.DataContext property changes. (Inherited from FrameworkElement) 3 DragEnter Occurs when the input system reports an underlying drag event with this element as the target. (Inherited from UIElement) 4 DragLeave Occurs when the input system reports an underlying drag event with this element as the origin. (Inherited from UIElement) 5 DragOver Occurs when the input system reports an underlying drag event with this element as the potential drop target. (Inherited from UIElement) 6 DragStarting Occurs when a drag operation is initiated. (Inherited from UIElement) 7 GotFocus Occurs when a UIElement receives focus. (Inherited from UIElement) 8 Holding Occurs when an otherwise unhandled Hold interaction occurs over the hit test area of this element. (Inherited from UIElement) 9 IsEnabledChanged Occurs when the IsEnabled property changes. (Inherited from Control) 10 KeyDown Occurs when a keyboard key is pressed while the UIElement has focus. (Inherited from UIElement) 11 KeyUp Occurs when a keyboard key is released while the UIElement has focus. (Inherited from UIElement) 12 LostFocus
Silverlight – Data Binding
Silverlight – Data Binding ”; Previous Next Data binding is a mechanism in Silverlight application, which provides a simple and easy way for Windows Runtime apps using partial classes to display and interact with data. The management of data is separated entirely, from the way data is displayed in this mechanism. Data binding allows the flow of data between UI elements and the data object on user interface. When a binding is established and the data or your business model changes, then it will reflect the updates automatically to the UI elements and vice versa. It is also possible to bind, not to a standard data source, but rather to another element on the page. Data binding are of the following two types − One-way data binding Two-way data binding One-way Data Binding In one-way data binding, the data is bound from its source (that is the object that holds the data) to its target (that is the object that displays the data). Let us have a look at a simple example of one-way data binding. Given below is the XAML code in which two labels, two text boxes and one button are created with some properties. <UserControl x:Class = “DataBinding.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 = “Auto” /> <RowDefinition Height = “*” /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width = “Auto” /> <ColumnDefinition Width = “200” /> </Grid.ColumnDefinitions> <TextBlock Name = “nameLabel” Margin = “2”>Name:</TextBlock> <TextBox Name = “nameText” Grid.Column = “1” Margin = “2” Text = “{Binding Name, Mode=OneWay}”/> <TextBlock Name = “ageLabel” Margin = “2” Grid.Row = “1”>Age:</TextBlock> <TextBox Name = “ageText” Grid.Column = “1” Grid.Row = “1” Margin=”2″ Text = “{Binding Age, Mode = OneWay}”/> <StackPanel Grid.Row = “2” Grid.ColumnSpan = “2”> <Button Content = “_Show…” Click = “Button_Click” /> </StackPanel> </Grid> </UserControl> We observe the following things − The text properties of both the text boxes bind to “Name” and “Age”, which are class variables of Person class as shown below. In Person class, we have just two variables Name and Age, and its object is initialized in MainPage class. In XAML code, we are binding to a property Name and Age, but we have not selected which property belongs to the object. An easy way is to assign an object to DataContext whose properties we are binding in the C# code in MainPage constructor as shown below. using System.Windows; using System.Windows.Controls; namespace DataBinding { public partial class MainPage : UserControl { Person person = new Person { Name = “Salman”, Age = 26 }; public MainPage() { InitializeComponent(); this.DataContext = person; } private void Button_Click(object sender, RoutedEventArgs e) { string message = person.Name + ” is ” + person.Age; MessageBox.Show(message); } } public class Person { private string nameValue; public string Name { get { return nameValue; } set { nameValue = value; } } private double ageValue; public double Age { get { return ageValue; } set { if (value != ageValue) { ageValue = value; } } } } } Let us run this application and you can see in your webpage immediately that we have successfully bound to the Name and Age of that Person object. When you press the Show button, it will display the name and age in the message box. Let us change the Name and Age in the above dialog box. Now, if you click the Show button, it will display the same message again. This is because the data-binding mode is set to oneway in the XAML code. To show the updated message, you will need to understand the two-way data binding. Two-way data binding In two-way binding, the user is able to modify the data through the user interface and have that data updated in the source. If the source changes while the user is looking at the view, you want the view to be updated. Let us have a look at the same example but only change the binding mode from one-way to two-way binding in XAML code as shown below. <UserControl x:Class = “DataBinding.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 = “Auto” /> <RowDefinition Height = “*” /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width = “Auto” /> <ColumnDefinition Width = “200” /> </Grid.ColumnDefinitions> <TextBlock Name = “nameLabel” Margin = “2”>_Name:</TextBlock> <TextBox Name = “nameText” Grid.Column = “1” Margin = “2” Text = “{Binding Name, Mode=TwoWay}”/> <TextBlock Name = “ageLabel” Margin = “2” Grid.Row = “1”>_Age:</TextBlock> <TextBox Name = “ageText” Grid.Column = “1” Grid.Row = “1” Margin = “2” Text = “{Binding Age, Mode = TwoWay}”/> <StackPanel Grid.Row = “2” Grid.ColumnSpan = “2”> <Button Content = “_Show…” Click = “Button_Click” /> </StackPanel> </Grid> </UserControl> Let us run this application again and you can see the same output. Let us change the Name and Age in the above dialog box. Now, if you click the Show button it will display the updated message. Print Page Previous Next Advertisements ”;
Silverlight – Visual State
Silverlight – Visual State ”; Previous Next It is good if your user can tell which bit of an application is likely to respond to the input. To some extent, this can be done by making buttons just look like buttons. If something looks clickable, it probably is. However, a convention in modern user interface design is that a user interface element should also signal a willingness to respond by changing their parents when the mouse moves over them. For example, the built in button control changes its background slightly, when the mouse moves over, to hint that it is interactive and then changes the parents further when clicked to make it look like its selected. Almost all controls need to do this and the designers need a way to create and edit the animations to make it happen. State & State Group Let us look at an example of visual state in action. Consider a checkbox. It may be unchecked or checked and if you choose, it can support a third indeterminate state. The control needs to look different for all the three cases. Therefore, we have three Visual States. In order to demonstrate that it is ready to respond to the user input, the checkbox changes its appearance slightly when the mouse moves over it and it changes further when the mouse is held there. A fourth state has to be considered if the checkbox is disabled, it looks great out and signals that its not going to respond to the user input. So, we have another four states here. At any given time, the visual state of a checkbox must be either Normal, Mouse over, Checked or Disabled. At the same time, it must be either checked, unchecked or indeterminate. Visual State Manager Since its templates define the appearance of the controls, the template needs to define what happens to each of the Visual States. The templates we have looked at so far do not contain such information. As a result, the appearance of the controls remain static, regardless of its current state. To add visual states to a template, you begin by adding a property element. The simplest thing you can do for visual state handling is to define animation that will run when the control enters a particular state. The controls notify the visual state manager class whenever they change state. The visual state manager then looks in this section of the template and figures out what animation to run. So, when the checkbox enters the mouse overstate, this animation will run, changing the color of some part of a template. Let us have a look at a simple example by using the visual state mechanisms to make a custom template for a checkbox that reflects state changes. Given below is the XAML code for custom template of check box with visual state. <UserControl xmlns = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/2006/xaml” x:Class = “CheckboxVisualState.Page” Width = “640” Height=”480″ xmlns:vsm = “clrnamespace:System.Windows;assembly = System.Windows” xmlns:d = “http://schemas.microsoft.com/expression/blend/2008” xmlns:mc = “http://schemas.openxmlformats.org/markup-compatibility/2006” mc:Ignorable = “d”> <UserControl.Resources> <ControlTemplate x:Key = “CheckBoxControlTemplate1” TargetType = “CheckBox”> <Grid> <vsm:VisualStateManager.VisualStateGroups> <vsm:VisualStateGroup x:Name = “FocusStates”> <vsm:VisualState x:Name = “ContentFocused”/> <vsm:VisualState x:Name = “Focused”/> <vsm:VisualState x:Name = “Unfocused”/> </vsm:VisualStateGroup> <vsm:VisualStateGroup x:Name = “CommonStates”> <vsm:VisualStateGroup.Transitions> <vsm:VisualTransition GeneratedDuration = “00:00:00.5000000″/> </vsm:VisualStateGroup.Transitions> <vsm:VisualState x:Name = “MouseOver”> <Storyboard> <ColorAnimationUsingKeyFrames BeginTime = “00:00:00” Duration = “00:00:00.0010000” Storyboard.TargetName = “background” Storyboard.TargetProperty = “(Shape.Fill). (SolidColorBrush.Color)”> <SplineColorKeyFrame KeyTime = “00:00:00” Value = “#FFFF0000″/> </ColorAnimationUsingKeyFrames> </Storyboard> </vsm:VisualState> <vsm:VisualState x:Name = “Pressed”> <Storyboard> <ColorAnimationUsingKeyFrames BeginTime = “00:00:00” Duration = “00:00:00.0010000” Storyboard.TargetName = “background” Storyboard.TargetProperty = “(Shape.Fill). (SolidColorBrush.Color)”> <SplineColorKeyFrame KeyTime = “00:00:00” Value = “#FFCEFF00″/> </ColorAnimationUsingKeyFrames> </Storyboard> </vsm:VisualState> <vsm:VisualState x:Name = “Disabled”/> <vsm:VisualState x:Name = “Normal”/> </vsm:VisualStateGroup> <vsm:VisualStateGroup x:Name = “CheckStates”> <vsm:VisualStateGroup.Transitions> <vsm:VisualTransition GeneratedDuration = “00:00:00.5000000″/> </vsm:VisualStateGroup.Transitions> <vsm:VisualState x:Name = “Checked”> <Storyboard> <DoubleAnimationUsingKeyFrames BeginTime = “00:00:00” Duration = “00:00:00.0010000” Storyboard.TargetName = “checkPath” Storyboard.TargetProperty = “(UIElement.Opacity)”> <SplineDoubleKeyFrame KeyTime = “00:00:00” Value = “1”/> </DoubleAnimationUsingKeyFrames> </Storyboard> </vsm:VisualState> <vsm:VisualState x:Name = “Unchecked”/> <vsm:VisualState x:Name = “Indeterminate”/> </vsm:VisualStateGroup> </vsm:VisualStateManager.VisualStateGroups> <Grid.ColumnDefinitions> <ColumnDefinition Width = “Auto”/> <ColumnDefinition Width = “3.61782296696066”/> <ColumnDefinition Width = “Auto”/> </Grid.ColumnDefinitions> <Canvas Height = “50” HorizontalAlignment = “Left” VerticalAlignment = “Top” Width = “50”> <Rectangle Height = “33.746” x:Name = “background” Width = “33.746” Canvas.Left = “8.452” Canvas.Top = “7.88” Fill = “#FFFFFFFF” Stroke = “#FF000000” RadiusX = “5.507” RadiusY = “5.507”/> <Path Height = “40.25” x:Name = “checkPath” Width = “39.75” Opacity = “0” Canvas.Left = “5.959” Canvas.Top = “7.903” Stretch = “Fill” Stroke = “#FF1F9300” StrokeThickness = “3” Data = “M1.5,1.5 C15.495283,8.7014561 27.056604,18.720875 33.75,33.75 M36,3.75 C22.004717,10.951456 10.443395,20.970875 3.7499986,36″/> </Canvas> <ContentPresenter HorizontalAlignment = “Left” Margin = “{TemplateBinding Padding}” VerticalAlignment = “{TemplateBinding VerticalContentAlignment}” Grid.Column = “2” Grid.ColumnSpan = “1” d:LayoutOverrides = “Height”/> </Grid> </ControlTemplate> </UserControl.Resources> <Grid x:Name = “LayoutRoot” Background = “White” > <CheckBox HorizontalAlignment = “Left” Margin = “52.5410003662109,53.5970001220703,0,0” VerticalAlignment = “Top” Template = “{StaticResource CheckBoxControlTemplate1}” Content = “CheckBox”/> </Grid> </UserControl> When the above code is compiled and executed, you will see the following web page, which contains one checkbox. When the curser enters the checkbox region, it will change the state. When you click the checkbox, you will see the following state. We recommend you to execute the above example for a better understanding. Print Page Previous Next Advertisements ”;
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 ”;
Constrained vs. Unconstrained Layout ”; Previous Next Layout in Silverlight always occurs in one of the two modes, either Constrained, or Unconstrained. A Constrained layout is one, where a container imposes the width or height. For example, the web browser, usually with CSS, always determines the overall dimensions of the Silverlight plug-ins. Some important features are − The top-level elements layout is constrained both horizontally and vertically. Whatever layout it produces, it must always end up with the results that are of the size imposed by the browser. Some elements end up with Unconstrained Layout, meaning that the elements are free to choose their own size. For example, elements inside a vertical StackPanel are vertically unconstrained. The StackPanel will give them as much height as they require. In fact, it will do this even if there is no enough space. It will tell the elements that they have the height they need, and then crop anything that does not fit. Most Silverlight user interfaces contain a mixture of these two layout styles. Regardless of whether its parent imposes constraints or not, a StackPanel will always perform Unconstrained Layout in the direction of stacking. The same is true for a Grid row or column when the height or width set to Auto. Suppose you have an element, which is inside a container that imposes a fixed horizontal width. By default, your element will be stretched to fill the space. If you set the alignment to Left, Right, or Center, it will remove the constraint. The element will take only the width that it needs.Of course, you can introduce a constraint with a fixed width or height. Unconstrained Layout is sometimes called Size to Content, because the size of an unconstrained element is typically determined by its content. Size to Content is an important idea in Silverlight layout. It is what enables the layout to adapt itself to whatever information is being displayed. Sr. No. Controls & Description 1 GridSplitter Constraints can come from the containing browser, or fixed dimensions in your design. However, it is sometimes useful to let the user impose constraints. 2 ScrollViewer Some user interfaces end up needing to display more information than will fit in the available space. One common solution to this is to provide a scrollable region. Silverlight makes this very easy with the ScrollViewer. 3 Border One more useful element to bear in mind when laying out the user interface is Border. Full Screen Mode The Silverlight plug-in is able to take over the entire screen. There is a property you can set on a helper class to go into full screen mode. However, there are a couple of constraints for security purposes. To prevent a website from being able to take over the screen at will, and to do something evil, like faking up a prompt asking for the user”s password. To enter full screen mode, you need to get hold of the Host.Content property from the application object, and set its IsFullScreen property to true. Let us have a look at a simple example which toggles the property, so it will flip back and forth between full screen and normal. <UserControl x:Class = “FullScreenExample.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”> <Border BorderBrush = “Gray” BorderThickness = “4” CornerRadius = “30” Padding = “20”> <Border.Background> <LinearGradientBrush StartPoint = “0,0” EndPoint = “0,1”> <GradientStop Offset = “0” Color = “Wheat” /> <GradientStop Offset = “1” Color = “BurlyWood” /> </LinearGradientBrush> </Border.Background> <Grid x:Name = “LayoutRoot”> <Button x:Name = “fullScreenButton” HorizontalAlignment = “Center” VerticalAlignment = “Center” FontSize = “30” Width = “300” Height = “100” Content = “Go Full Screen” Click = “Button_Click” /> </Grid> </Border> </UserControl> Here is a code in C# that initiates the return from full screen to normal. You can find out when this happens by handling the Host.Content objects FullScreenChanged event. using System; using System.Windows; using System.Windows.Controls; namespace FullScreenExample { public partial class MainPage : UserControl { public MainPage() { InitializeComponent(); App.Current.Host.Content.FullScreenChanged += Content_FullScreenChanged; } void Content_FullScreenChanged(object sender, EventArgs e) { if (Application.Current.Host.Content.IsFullScreen) { fullScreenButton.Content = “Return to Normal”; } else { fullScreenButton.Content = “Go Full Screen”; } } private void Button_Click(object sender, RoutedEventArgs e) { var content = Application.Current.Host.Content; content.IsFullScreen = !content.IsFullScreen; } } } When the above code is compiled and executed, you will see the following output. When the user clicks the Go Full Screen button, then it will switch to the full screen mode. Notice that the button”s text has changed. It now says Return to Normal. If you click it again or by hit Escape, it will flip back out of full screen mode. Print Page Previous Next Advertisements ”;