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
Category: silverlight
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 ”; 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 – Content Model
Silverlight – Content Model ”; Previous Next The buttons offer a form of content to the model content. Models crop up a lot in controls. The idea is simple. It will accept any content and not just text. If you want to create a truly exotic button, you could even place other content controls such as text boxes and buttons inside (and nest still elements inside these). It is doubtful that such an interface would make much sense, but it is possible. Let us have a look at a simple example with button, inside button other content controls. <UserControl x:Class = “ContentModel.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”> <Button Margin = “3” Height = “70” Width = “215”> <Grid Margin = “5”> <Polygon Points = “100,25 125,0 200,25 125,50” Fill = “LightSteelBlue” /> <Polygon Points = “100,25 75,0 0,25 75,50” Fill = “LightGray”/> </Grid> </Button> </Grid> </UserControl> When the above code is compiled and executed, you will see the following button. RangeControl The scrollbar and slider controls are closely related. They both allow the user to choose an input value from a particular range. Conventionally, these controls signify different things. Scrollbars are normally used to set the position into a scrotal area whereas, the slider is used to specify some value or setting. These are just conventions; the controls have similar behaviors and APIs. The range controls are simple to use. You specify the minimum and maximum values to indicate the range of values you would like the slider to represent. The Value property will vary as the use of drags varies. The hierarchical inheritance of Slider class is as follows − Given below are the commonly used properties of Slider. Given below are the most commonly used properties of Slider. Sr. No. Property & Description 1 Header Gets or sets the content for the control”s header. 2 HeaderProperty Identifies the Header dependency property. 3 HeaderTemplate Gets or sets the DataTemplate used to display the content of the control”s header. 4 HeaderTemplateProperty Identifies the HeaderTemplate dependency property. 5 IntermediateValue Gets or sets the value of the Slider while the user is interacting with it, before the value is snapped to either the tick or step value. The SnapsTo property specifies the value of slider. 6 IntermediateValueProperty Identifies the IntermediateValue dependency property. 7 IsDirectionReversed Gets or sets a value that indicates the direction of increasing value. 8 IsDirectionReversedProperty Identifies the IsDirectionReversed dependency property. 9 IsThumbToolTipEnabled Gets or sets a value that determines whether the slider value is shown in a tool tip for the Thumb component of the Slider. 10 IsThumbToolTipEnabledProperty Identifies the IsThumbToolTipEnabled dependency property. 11 Orientation Gets or sets the orientation of a Slider. 12 OrientationProperty Identifies the Orientation dependency property. 13 StepFrequency Gets or sets the value part of a value range that steps should be created for. 14 StepFrequencyProperty Identifies the StepFrequency dependency property. 15 ThumbToolTipValueConverter Gets or sets the converter logic that converts the range value of the Slider into tool tip content. 16 ThumbToolTipValueConverterProperty Identifies the ThumbToolTipValueConverter dependency property. 17 TickFrequency Gets or sets the increment of the value range that ticks should be created for. 18 TickFrequencyProperty Identifies the TickFrequency dependency property. 19 TickPlacement Gets or sets a value that indicates where to draw tick marks in relation to the track. 20 TickPlacementProperty Identifies the TickPlacement dependency property. Given below are the commonly used events in Slider class. Given below are the most commonly used events of Slider. Sr. No. Event & Description 1 ManipulationCompleted Occurs when a manipulation on the UIElement is complete. (Inherited from UIElement) 2 ManipulationDelta Occurs when the input device changes position during a manipulation. (Inherited from UIElement) 3 ManipulationInertiaStarting Occurs when the input device loses contact with the UIElement object during a manipulation and inertia begins. (Inherited from UIElement) 4 ManipulationStarted Occurs when an input device begins a manipulation on the UIElement. (Inherited from UIElement) 5 ManipulationStarting Occurs when the manipulation processor is first created. (Inherited from UIElement) 6 ValueChanged Occurs when the range value changes. (Inherited from RangeBase) Given below are the commonly used methods in Slider class. Given below are the most commonly used methods of Slider. Sr. No. Method & Description 1 OnManipulationCompleted Called before the ManipulationCompleted event occurs. (Inherited from Control) 2 OnManipulationDelta Called before the ManipulationDelta event occurs. (Inherited from Control) 3 OnManipulationInertiaStarting Called before the ManipulationInertiaStarting event occurs. (Inherited from Control) 4 OnManipulationStarted Called before the ManipulationStarted event occurs. (Inherited from Control) 5 OnManipulationStarting Called before the ManipulationStarting event occurs. (Inherited from Control) 6 OnMaximumChanged Called when the Maximum property changes. (Inherited from RangeBase) 7 OnMinimumChanged Called when the Minimum property changes. (Inherited from RangeBase) 8 OnValueChanged Fires the ValueChanged routed event. (Inherited from RangeBase) 9 SetBinding Attaches a binding to a FrameworkElement, using the provided binding object. (Inherited from FrameworkElement) 10 SetValue Sets the local value of a dependency property on a DependencyObject. (Inherited from DependencyObject) Example Let us have a look at a simple example in which a slider and an ellipse are added and the slider controls the width of the ellipse. <UserControl x:Class = “SliderExample.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:DesignWidth = “640” d:DesignHeight = “480”> <Grid x:Name = “LayoutRoot”> <Grid.RowDefinitions> <RowDefinition Height = “Auto” /> <RowDefinition /> </Grid.RowDefinitions> <Slider Minimum = “1” Maximum = “400” Value = “1” ValueChanged = “Slider_ValueChanged” /> <Ellipse Grid.Row = “1” Fill = “Aqua” Width = “1” x:Name = “myEllipse” /> </Grid> </UserControl> Given below is the value changed event implementation is C#. using System.Windows; using System.Windows.Controls; namespace SliderExample { public partial class MainPage : UserControl { public MainPage() { InitializeComponent(); } private void Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) { if (myEllipse != null) { myEllipse.Width = e.NewValue; } } } } When the above code is compiled and executed, you will see the following output. As
Silverlight – Getting Started ”; Previous Next 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 at a very simple example. Step 1 − Open Visual Studio. Click the File menu, point to New and then click Project. Step 2 − A New Project dialog box will open. Under Templates, select Visual C# and then click Silverlight. In the right pane, choose Silverlight Application. Enter a project name and a location on your hard drive to save your project and then click OK to create the project. The Silverlight project itself is just going to build the Silverlight content, and that content is just one asset amongst many that are going to make up the whole web application. Click OK. Step 3 − Check the Host the Silverlight application checkbox. The default is an ASP.NET Web Application Project. Step 4 − MS-Visual Studio has created two projects, the Silverlight project and an ASP.NET web application. Now, we do need an ASP.NET web application. You can see this in the Solution Explorer window as shown below. Anything that can serve up the content via HTTP will do but this is Visual Studio, and it understands the ASP.NET web technology, so that is what it gives us. To demonstrate that Silverlight does not depend on any particular server-side technology, let us delete this .aspx file, leaving just the plain static HTML file. Step 5 − Right-click FirstExampleTestpage.aspx. From the list of options, click Delete. Step 6 − Set FirstExampleTestPage.html as the Start page. The MainPage.xaml file defines the user interface for Silverlight content. Either you can write XAML code directly or you can also use Toolbox to drag and drop different UI elements. Step 7 − Given below is a simple code in MainPage.xaml in which a Button and a TextBlock are defined inside the StackPanel. <UserControl x:Class = “FirstExample.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> <TextBlock x:Name = “TextMessage” Text = “Hello World!” Margin = “5”> </TextBlock> <Button x:Name = “ClickMe” Click = “ClickMe_Click” Content = “Click Me!” Margin = “5”> </Button> </StackPanel> </Grid> </UserControl> Step 8 − This example assumes that you have created an event-handling method named ClickMe_Click. Here is what it looks like in the MainPage.xaml.cs file. using System.Windows; using System.Windows.Controls; namespace FirstExample { public partial class MainPage : UserControl { public MainPage() { InitializeComponent(); } private void ClickMe_Click(object sender, RoutedEventArgs e) { TextMessage.Text = “Congratulations! you have created your first Silverlight Applicatoin”; } } } Step 9 − A Silverlight application can be run on any installed browsers. Step 10 − When the above code is compiled and executed, you will see the following webpage. Step 11 − Now, when you click the Click Me button, it will update the text in the TextBlock as shown below. We recommend you to execute the above example by adding some more UI elements. Print Page Previous Next Advertisements ”;
Silverlight – ListBox
Silverlight – ListBox ”; Previous Next Listbox is a control that provides a list of items to the user for selection of an item. A user can select one or more items from a predefined list of items at a time. In a ListBox, multiple options are always visible to the user without any user interaction. A Listbox presents a scrollable list of items. If a user selects an item, the selected item changes appearance to indicate selection. It supports a more extensive form of content model and Button. A major difference between a button and a list box is that a button contains a single piece of content whereas a listbox allows every single item in the list. The hierarchical inheritance of ListBox class is as follows − Given below are the commonly used Properties of ListBox class. Given below are the most commonly used properties of ListBox. Sr. No. Property & Description 1 Background Gets or sets a brush that provides the background of the control. (Inherited from Control) 2 BorderThickness Gets or sets the border thickness of a control. (Inherited from Control) 3 FontFamily Gets or sets the font used to display text in the control. (Inherited from Control) 4 FontSize Gets or sets the size of the text in this control. (Inherited from Control) 5 FontStyle Gets or sets the style in which the text is rendered. (Inherited from Control) 6 FontWeight Gets or sets the thickness of the specified font. (Inherited from Control) 7 Foreground Gets or sets a brush that describes the foreground color. (Inherited from Control) 8 GroupStyle Gets a collection of GroupStyle objects that define the appearance of each level of groups. (Inherited from ItemsControl) 9 Height Gets or sets the suggested height of a FrameworkElement. (Inherited from FrameworkElement) 10 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) 11 IsEnabled Gets or sets a value indicating whether the user can interact with the control. (Inherited from Control) 12 Item Gets the collection used to generate the content of the control. (Inherited from ItemsControl) 13 ItemsSource Gets or sets an object source used to generate the content of the ItemsControl. (Inherited from ItemsControl) 14 Margin Gets or sets the outer margin of a FrameworkElement. (Inherited from FrameworkElement) 15 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 XAML-declared object by this name. (Inherited from FrameworkElement) 16 Opacity Gets or sets the degree of the object”s opacity. (Inherited from UIElement) 17 SelectedIndex Gets or sets the index of the selected item. (Inherited from Selector) 18 SelectedItem Gets or sets the selected item. (Inherited from Selector) 19 SelectedValue Gets or sets the value of the selected item, obtained by using the SelectedValuePath. (Inherited from Selector) 20 Style Gets or sets an instance Style that is applied for this object during layout and rendering. (Inherited from FrameworkElement) 21 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) 22 Width Gets or sets the width of a FrameworkElement. (Inherited from FrameworkElement) Given below are the most commonly used Events of ListBox. Given below are the most commonly used events of ListBox. Sr. No. Event & Description 1 DragEnter Occurs when the input system reports an underlying drag event with this element as the target. (Inherited from UIElement) 2 DragLeave Occurs when the input system reports an underlying drag event with this element as the origin. (Inherited from UIElement) 3 DragOver Occurs when the input system reports an underlying drag event with this element as the potential drop target. (Inherited from UIElement) 4 DragStarting Occurs when a drag operation is initiated. (Inherited from UIElement) 5 Drop Occurs when the input system reports an underlying drop event with this element as the drop target. (Inherited from UIElement) 6 DropCompleted Occurs when a drag-and-drop operation is ended. (Inherited from UIElement) 7 GotFocus Occurs when a UIElement receives focus. (Inherited from UIElement) 8 IsEnabledChanged Occurs when the IsEnabled property changes. (Inherited from Control) 9 KeyDown Occurs when a keyboard key is pressed while the UIElement has focus. (Inherited from UIElement) 10 KeyUp Occurs when a keyboard key is released while the UIElement has focus. (Inherited from UIElement) 11 LostFocus Occurs when a UIElement loses focus. (Inherited from UIElement) 12 SelectionChanged Occurs when the currently selected item changes. (Inherited from Selector) 13 SizeChanged Occurs when either the ActualHeight or the ActualWidth property changes value on a FrameworkElement. (Inherited from FrameworkElement) Given below are the most commonly used Methods of ListBox. Given below are the most commonly used methods of ListBox. Sr. No. Method & Description 1 Arrange Positions child objects and determines a size for a UIElement. Parent objects that implement custom layout for their child elements should call this method from their layout override implementations to form a recursive layout update. (Inherited from UIElement) 2 FindName Retrieves an object that has the specified identifier name. (Inherited from FrameworkElement) 3 Focus Attempts to set the focus on the control. (Inherited from Control) 4 GetValue Returns the current effective value of a dependency property from a DependencyObject. (Inherited from DependencyObject) 5 IndexFromContainer Returns the index to the item that has the specified, generated container. (Inherited from ItemsControl) 6 OnDragEnter Called before the DragEnter event occurs. (Inherited from Control) 7 OnDragLeave Called before the DragLeave event occurs. (Inherited from Control) 8 OnDragOver Called before the DragOver event occurs. (Inherited from Control) 9 OnDrop Called before the Drop 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)