YOU ARE DOWNLOADING DOCUMENT

Please tick the box to continue:

Transcript
Page 1: Silver Light Training

SILVERLIGHT 4.0

Page 2: Silver Light Training

Agenda• Introduction• Architecture• XAML• Standard Controls• Resources and Styles• Data Binding• Templates• Custom Controls• Graphics, Transformations and Animations• UI interaction• Triggers• Hosting • Working with Services• Navigation Applications• Debugging Silverlight Applications• Unit Tests• Expression Suite• 3-rd party libraries

Page 3: Silver Light Training

Day 1

• Introduction• Architecture• XAML• Standard Controls– Layout controls– Useful properties

• Exercise

Page 4: Silver Light Training

Introduction

Page 5: Silver Light Training

What is Silverlight ?

• Microsoft Silverlight is a cross-browser, cross-platform implementation of the .NET Framework

• It is used for creating Internet/Intranet applications with rich graphic interface and business logic executed by client

Page 6: Silver Light Training

History• Until middle of 90s the most applications had

Win32/MFC style GUI• In 90s the Web started to grow• Many Web frameworks offered “Windows style”

solutions for creating “rich internet applications”:– JavaScript-based (AJAX, jQuery, Dojo, ExtJs, etc)– Flash-based– Java applets– ActiveX

• In 2002 Microsoft introduced .NET 1.0 with new API for creating WinForms application that replaced MFC

Page 7: Silver Light Training

History• In .NET 3.0 Microsoft added a totally new concept

for building WinForms applications – Windows Presentation Foundation (WPF)

• Silverlight 1.0 was released shortly after .NET 3.0. It was developed under code name WPF/E – WPF everywhere

• There was a big gap between WPF 3.0/3.5 and Silverlight 1.0/2.0, but starting from Silverlight 3.0 this gap had minimized drastically and now Silverlight 4.0 pretty much comparable to WPF 4.0

Page 8: Silver Light Training

Architecture

Page 9: Silver Light Training

Silverlight platform

• Silverlight must by installed before first-time using by running small footprint installation (~6 MB)

• Silverlight is installed as plug-in to Internet browser

• Silverlight consists from 2 major parts:– Core presentation framework– .NET Framework for Silverlight

Page 10: Silver Light Training

Silverlight platform

Page 11: Silver Light Training

Compatible Operating Systems and Browsers

Page 12: Silver Light Training

Application structure

• Silverlight application contains – Application assembly:

• complied application code• XAML files• Embedded resources: Images, video

– Included resources referred by URL– 3-rd party assemblies referenced by application

• Visual Studio combines all these files into application package – compressed zip file that has .xap extension

Page 13: Silver Light Training

Application structure

• XAP file includes manifest file that identifies all assemblies in the package

• At minimum the application package includes assembly with your implementation of System.Windows.Application class:– Handles Startup and Exit events– Interaction with Silverlight plug-in– Resource management

Page 14: Silver Light Training

Deployment

• Silverlight application is always deployed from Web server on Internet/Intranet

• Web Server must include at least:– XAP package– HTML page that embeds Silverlight plug-in

• End user just browses to HTML page and Silverlight plug-in downloads and initializes XAP package

Page 15: Silver Light Training

HELLO WORLD

Page 16: Silver Light Training

Application Caching

• Browsers store XAP file in browser cache in order to improve startup time

• Usually XAP file includes number of non-changed standard or 3-rd party assemblies

• Application library caching improves startup time by separating these rarely changed assemblies from main XAP to dedicated ZIPs

Page 17: Silver Light Training

XAML

Page 18: Silver Light Training

What is XAML

• Extensible Application Markup Language (XAML) is a declarative language based on XML

• Initializes objects and sets properties• Has hierarchical structure that defines relations

between objects• Could include code that respond to events and

manipulates objects in separate code-behind file

Page 19: Silver Light Training

Example<UserControl

x:Class="MySilverlight.Page" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >

<Grid Background="OldLace"> </Grid> </UserControl>

Page 20: Silver Light Training

XAML syntax

• XAML defines objects that are mapped into CLR types

• Attributes defined in XAML are mapped into properties of CLR type

• Examples<Button Name="CheckoutButton"/><TextBox Text="This is a Text Box"/>

Page 21: Silver Light Training

Controls• WPF/Silverlight GUI is combined from hierarchy

of controls that are combined into “visual tree”• Controls are defined in XAML or in code-behind.

<UserControl> <Grid Background="OldLace">

<Border><TextBlock Text=“Text is here”/>

</Border><my:CustomControl>

<TextBlock Text=“Another Text is here”/></my:CustomControl>

</Grid> </UserControl>

Page 22: Silver Light Training

Control Content Model• Most controls are designed to display certain kinds

of content• Controls could be divided to following categories

from content point of view:– No content controls

<TextBox…/> <TextBlock …/> <Rectangle …/>

– Controls that display a single element<Border><TextBlock/></Border>

– Controls that display collection of elements (layout controls)<StackPanel><TextBlock/><Border>…</Border></StackPanel>

Page 23: Silver Light Training

XAML properties syntax

• Properties of objects could be defined in various ways:

• Attribute syntaxSets a value for a property by declaring an attribute on an existing object element

<TextBox Text="This is a Text Box"/>

• The string value of attribute is converted/parsed into type of underlying property

<Button Visibility=“Collapsed” /><Border Width=“50” Background=“Red”/>

Page 24: Silver Light Training

XAML properties syntax

• Property element syntaxAllows to assign non-string values (objects) to property

<Button Content=“Click Me”> <Button.BorderBrush>

<LinearGradientBrush> … </LinearGradientBrush> </Button.BorderBrush> </Button>

Page 25: Silver Light Training

XAML properties syntax• Collection syntax

Properties that implement IList, IDictionary or derived from Array could be defined as:

<Button Content=“Click Me”> <Button.BorderBrush>

<LinearGradientBrush> <LinearGradientBrush.GradientStops>

<GradientStop Color="Yellow" Offset="0.0" /> <GradientStop Color="Red" Offset="0.25" />

<GradientStop Color="Blue" Offset="0.75" /> <GradientStop Color="LimeGreen" Offset="1.0" /> </LinearGradientBrush.GradientStops> </LinearGradientBrush> </Button.BorderBrush> </Button>

Page 26: Silver Light Training

XAML properties syntax

• Content propertiesEnabled for classes that has ContentPropertyAttribute which specifies what property will get value of content

<LinearGradientBrush><GradientStop Color="Yellow" Offset="0.0" />

<GradientStop Color="Red" Offset="0.25" /> <GradientStop Color="Blue" Offset="0.75" /> <GradientStop Color="LimeGreen" Offset="1.0" /></LinearGradientBrush>

Page 27: Silver Light Training

Attached properties

• Attached properties are owned and defined by a particular type, but set on any element

• Example<Canvas> <TextBlock Canvas.Left="10" Canvas.Top="10"

Text="Left-top corner"></TextBlock> <TextBlock Canvas.Left="170" Canvas.Top="170"

Text="Right-bottom corner"></TextBlock></Canvas>

Page 28: Silver Light Training

Events

• Silverlight controls usually have various events that help for interaction with controls

• Event handling is provided as method in code-behind file

Page 29: Silver Light Training

CLICK ME

Page 30: Silver Light Training

Routed events

• A routed event is an event that is potentially passed on (routed) from a child object to each of its successive parent objects in the object tree

• When routed event is handled by non-owner the sender is no longer the same object as the event-raising object. For these cases, the value of the RoutedEventArgs.OriginalSource property is the object of interest

• Setting RoutedEventArgs.Handled to true stops future routing of event

Page 31: Silver Light Training

Routed events• Routed events in Silverlight:

– KeyDown– KeyUp– GotFocus– LostFocus– MouseLeftButtonDown– MouseLeftButtonUp– MouseMove– MouseWheel– BindingValidationError– DragEnter– DragLeave– DragOver– Drop

Page 32: Silver Light Training

XAML namespaces

• Namespaces are used for resolve ambiguities of string tokens (object names and properties)

• XAML uses XML-style namespace declaration (xmlns)

• Used for distinguish between:– Silverlight core objects from core libraries– Objects from extension libraries– Objects defined in Silverlight application

Page 33: Silver Light Training

Using namespaces

• Every XAML file has definition of default XAML namespace and XAML language xmls:x namespacexmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml

• Default XAML namespace defines all XAML standard elements

• XAML language namespace defines few properties that could be defined for every XAML object:x:Name – name of object. Unique per XAML filex:Key – unique key for resource

Page 34: Silver Light Training

Using namespaces

• Other namespaces need to be declared first xmlns:sdk=http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdkxmlns:mpsl="clr-namespace:MP.SL“

• Than objects from these namespaces could be used:<sdk:ValidationSummary

x:Name="validationSummary" Grid.Row="2" Margin="0,20,0,0" />

<mpsl:WaitControl x:Name="waitMessage" Grid.RowSpan="3">

</mpsl:WaitControl>

Page 35: Silver Light Training

Standard Controls

Page 36: Silver Light Training

Controls types• Silverlight ships with many common controls. In addition

there are more controls available from Silverlight SDK (Toolkit)

• All controls could be ordered by types:– Layout– Information display– Buttons– Data display– User input– Dialog boxes– Media– HTML display

Page 37: Silver Light Training

Layout controls

Layout controls are used to manage the size, dimensions, position, and arrangement of child elements

– Border– Canvas– Grid, GridSplitter– StackPanel– DockPanel– WrapPanel– ViewBox– ScrollViewer– TabControl

Page 38: Silver Light Training

Layout controls - Border

• Provides a border, background, or both to another control

• Syntax<Border> singleChild </Border>

• Useful propertiesWidth, Height, BorderBrush, BorderThickness, Background, CornerRadius, Padding

• Useful attached propertiesVerticalAlignment, HorizontalAlignment

Page 39: Silver Light Training

Layout controls - Canvas

• Provides a surface to display child elements at specific coordinates in the canvas

• Syntax<Canvas ...> one or more UIElements </Canvas>

• Useful attached propertiesCanvas.Left, Canvas.Top, Canvas.ZIndex

Page 40: Silver Light Training

Layout controls - Grid

• Provides a surface composed of rows and columns to display child elements

• Syntax<Grid ...> one or more UIElements </Grid>

• Useful propertiesColumnDefinitions, RowDefinitions

• Useful attached propertiesGrid.Column, Grid.Row, Grid.ColSpan, Grid.RowSpanVerticalAlignment, HorizontalAlignment

Page 41: Silver Light Training

Layout controls – Grid cont.

• Width of columns and height of rows could be defined in various ways:– Default (not specified) – proportionally divide

available space– Absolute value in pixels– Star - weighted proportion of available space

Syntax: “[weight]*”– Auto – based on size of content

Syntax: “Auto”

Page 42: Silver Light Training

Layout controls – GridSplitter (SDK)

• Allows a user to resize the columns or rows in a Grid control

• The resizing behavior depends on Grid.ColSpan, Grid.RowSpan, HorizontalAlignment and VerticalAlignment

HorizontalAlignment VerticalAlignment ResultStretch Top, Center, Bottom Resizes rows.Right, Left, Center Stretch Resizes columns.

Page 43: Silver Light Training

Layout controls – StackPanel

• Provides a surface to display child elements in a line; either horizontally or vertically.

• Syntax<StackPanel ...>

oneOrMoreChildren </StackPanel>

• Useful propertiesOrientation

• Useful attached propertiesVerticalAlignment, HorizontalAlignment

Page 44: Silver Light Training

Layout controls – DockPanel (Toolkit)

• Defines an area where you can arrange child elements either horizontally or vertically, relative to each other

• Syntax<toolkit:DockPanel>

Children </toolkit:DockPanel>

• Useful propertiesLastChildFill

• Useful attached propertiesDockPanel.Dock

Page 45: Silver Light Training

Layout controls – WrapPanel (Toolkit)

• Positions child elements in sequential position, breaking content to the next line at the edge of the containing box

• Syntax<toolkit:WrapPanel>

Children </toolkit:WrapPanel>

• Useful propertiesOrientation

Page 46: Silver Light Training

Layout controls – ViewBox

• Provides a control that can stretch or scale its content to fill the available space

• Syntax<ViewBox ...>

child </ViewBox>

• Useful propertiesStretch, StretchDirection

Page 47: Silver Light Training

Layout controls – ScrollViewer

• Provides a scrollable surface for displaying a child element

• Syntax<ScrollViewer ...>

single content control</ScrollViewer>

• Useful propertiesHorizontalScrollBarVisibility, VerticalScrollBarVisibilityCould be Visible, Hidden, Auto

Page 48: Silver Light Training

Layout controls – TabControl (SDK)

• Provides a tabbed interface for displaying elements• Syntax

<sdk:TabControl …>one or more sdk:TabItem controls

</sdk:TabControl>

<sdk:TabItem Header=“Tab caption”…>single content control

</sdk:TabItem>• Useful properties

TabStripPlacement

Page 49: Silver Light Training

Useful properties - Size

• Control sizeFrameworkElement.WidthFrameworkElement.HeightWidth and Height are specified in pixels. The default value is “Auto” – according to size of content.

• Control actual sizeFrameworkElement.ActualWidthFrameworkElement.ActualHeightCan’t be set. Contains calculated width and height of control in pixels

Page 50: Silver Light Training

Useful properties - Position

• AlignmentFrameworkElement.VerticalAlignmentValues: Top, Bottom, Center, StretchFrameworkElement.HorizontalAlignmentValues: Left, Right, Center, StretchBoth are attached properties

Page 51: Silver Light Training

Useful properties - Position• Margin

FrameworkElement.MarginDefines outlet margin of control in pixelsSyntax:

<frameworkElement Margin="uniform"/>or

<frameworkElement Margin="left+right,top+bottom"/>

or <frameworkElement

Margin="left,top,right,bottom"/>

• PaddingControl.PaddingDefines space between content of control and its outlet borderHas same syntax like MarginSome controls implements Control.Padding too (Border)

Page 52: Silver Light Training

Useful properties - Visibility

• VisibilityUIElement.VisibilityDefines visibility of control. Collapsed controls are not renderValues: Visible, Collapsed

• OpacityUIElement.OpacityDefines the degree of control opacity 0.0-1.0. Default is 1.0

Page 53: Silver Light Training

Useful properties - Background

• BackgroundControl.BackgroundDefines color backgroundValues: color string or Brush

Page 54: Silver Light Training

Useful properties - Border

• BorderControl.BorderBrushDefines color of borderValues: color string or Brush

• BorderThicknessControl. BorderThicknessDefines thickness of borderSyntax:

<control BorderThickness="uniform"/> or

<control BorderThickness="left&right,top&bottom"/> or

<control BorderThickness="left,top,right,bottom"/>

Page 55: Silver Light Training

Useful properties - Brushes

• SolidColorBrushDefines solid colorSyntax:<object property="predefinedColor/#rgb/#argb"/>

<object.property><SolidColorBrush Color=“color"/>

</object.property>

predefinedColor – Colors class properties#rgb – Red, Green, Blue#argb – Alpha (%), Red, Green, Blue

Page 56: Silver Light Training

Useful properties - Brushes

• ImageBrushSyntax:<ImageBrush ImageSource=“image"/>

Page 57: Silver Light Training

Useful properties - Brushes• LinearGradientBrush

Defines a gradient along a lineSyntax:<LinearGradientBrush ...> oneOrMoreGradientStops </LinearGradientBrush>The gradient line is definedby StartPoint and EndPointproperties. Default is diagonalline StartPoint=0,0 and EndPoint=1,1

Page 58: Silver Light Training

Useful properties - Brushes

• RadialGradientBrushDefines radial gradientSyntax:<RadialGradientBrush>

oneOrMoreGradientStops </RadialGradientBrush>

The gradient is defined by focal point (GradientOrigin) and ellipse (Center, RadiusX, RadiusY).

Page 59: Silver Light Training

LAYOUT EXERCISE

Page 60: Silver Light Training

Day 2

• Standard Controls– Information display– Buttons– Data display– User input– Dialog boxes– Media– HTML display

• Resources and Styles• Exercise

Page 61: Silver Light Training

Information display

User information controls provide contextual feedback or clarify an application's user interface. The user typically cannot interact with these controls.– TextBlock– Fonts, Foreground, Text decorations– ProgressBar– ToolTip

Page 62: Silver Light Training

Information display - TextBlock

• Displays small amounts of read-only text• Syntax

<TextBlock ...>text

</TextBlock> or <TextBlock Text=“text”.../>

• Useful propertiesText, TextAlignment

• Useful attached propertiesfont and decoration properties

Page 63: Silver Light Training

Information display – TextBlock cont

• TextBlock inline Syntax<TextBlock>

oneOrMoreInlineElements </TextBlock>

• RunRepresents a discrete section of formatted or unformatted text<Run Text=“text”… /> or <Run>text</Run>

• LineBreakBegins a new line <LineBreak/>

• Bold, Italic, Span

Page 64: Silver Light Training

Fonts, Foreground

• FontsControl.FontFamilyControl.FontSizeControl.FontWeightControl.FontStyleControl.FontStretch

• ForegroundDefines color of textControl.Foreground

Page 65: Silver Light Training

Text decorations

• TextDecorationsTextBlock.TextDecorations

• Text wrappingTextBlock.TextWrappingTextBlock.TextTrimming

Page 66: Silver Light Training

Information display – ProgressBar

• Represents the progress of an operation• Syntax

<ProgressBar .../>• Useful properties

Width, Height,Value, Minimum, Maximum, IsIndeterminate, Foreground

Page 67: Silver Light Training

Information display – ToolTip• Displays a ToolTip• Syntax

<ToolTip Content=“string”.../> or

<ToolTip ...> singleObject

</ToolTip ...> or

<ToolTip ...>stringContent</ToolTip>• Useful attached properties

HorizontalOffset, VerticalOffset• Useful attached properties

ToolTipService.ToolTip, ToolTipService.Placement

Page 68: Silver Light Training

Buttons

Buttons are one of the most basic user interface controls. Applications typically perform some task in the Click event when a user clicks on them. – Button– HyperlinkButton– RepeatButton

Page 69: Silver Light Training

Buttons - Button

• Responds to user input from a mouse, keyboard, stylus, or other input device and raises a Click event.

• Syntax<Button Content=“string”.../>

or<Button>

singleObject </Button>

• Useful eventsClick

• Useful propertiesIsEnabled

Page 70: Silver Light Training

Buttons – HyperlinkButton• Represents a button control that displays a hyperlink.

Allows users to navigate to an external Web page or content within the same Silverlight application

• Syntax<HyperlinkButton Content=“string”.../>

or <HyperlinkButton>

singleObject </HyperlinkButton>

Useful eventsClick

• Useful propertiesIsEnabled, NavigateUri

Page 71: Silver Light Training

Buttons - RepeatButton

• Represents a control that raises its Click event repeatedly from the time it is pressed until it is released.

• Syntax<RepeatButton Content=“string”.../>

or<RepeatButton>

singleObject </RepeatButton>

• Useful eventsClick

• Useful propertiesDelay

Page 72: Silver Light Training

Data display

Data display controls are used to show information from a data source– DataGrid– Collection views– DataPager– TreeView

Page 73: Silver Light Training

Data display – DataGrid (SDK)

• Displays a collection of data in rows and columns

• Syntax<sdk:DataGrid .../>

• Useful propertiesItemsSource, AutoGenerateColumns, Columns

Page 74: Silver Light Training

Data display – DataGrid cont.

• Columns typesDataGridTextColumnDataGridCheckBoxColumnDataGridTemplateColumn

Page 75: Silver Light Training

Data display – Collection views

• PagedCollectionViewRepresents a view for grouping, sorting, filtering

• Useful propertiesSortDescriptions, GroupDescriptions, Filter

Page 76: Silver Light Training

Data display – DataPager (SDK)

• Provides a user interface for paging through a collection of data that implements IPagedCollectionView

• Syntax<sdk:DataPager .../>

• Useful propertiesSource, PageSize, DisplayMode, AutoEllipsis

• Typically used with DataGrid or ListBox

Page 77: Silver Light Training

Data display – TreeView (SDK)

• Displays hierarchical data in a tree structure that has items that can expand and collapse.

• Syntax<sdk:TreeView ItemsSource=“items”.../>or<sdk:TreeView>

oneOrMore <sdk:TreeViewItem></sdk:TreeView>

• Useful propertiesSelectedValue, SelectedItem

Page 78: Silver Light Training

User input

– TextBox– PasswordBox– RichTextBox– AutoCompleteBox– CheckBox– ComboBox– ListBox– RadioButton– Slider– Calendar, DatePicker

Page 79: Silver Light Training

User input - TextBox

• Control for displaying or editing text• Syntax

<TextBox Text=“text”.../> • Useful properties

Text, IsReadOnly, AcceptsReturn• Useful attached properties

font and decoration properties

Page 80: Silver Light Training

User input - PasswordBox

• Control that allows the user to enter sensitive data, such as a password

• Syntax<PasswordBox Password=“password”.../>

• Useful propertiesPassword, PasswordChar

Page 81: Silver Light Training

User input - RichTextBox• Control for displaying or editing rich text. Supports formatted

text, hyperlinks, images, and other rich content• Syntax

<RichTextBox .../> or <RichTextBox ...>

blocksContent </RichTextBox>

• BlocksInline, InlineUIContainer, Run, Span, Bold, Hyperlink, Italic, Underline, LineBreak

Page 82: Silver Light Training

User input – AutoCompleteBox (SDK)

• Provides a text box for user input and a drop-down that contains possible matches based on the input in the text box

• Syntax<sdk:AutoCompleteBox .../>

• Useful propertiesItemsSource, FilterMode, TextFilter, ItemFilter

• Filter ModesStartsWith (default), Contains, Equals, Custom, etc

Page 83: Silver Light Training

User input – CheckBox

• Control that a user can select or clear• Syntax

<CheckBox Content=“string” .../>or<CheckBox>

singleObject </CheckBox>

• Useful propertiesIsChecked, IsThreeState

• Useful eventsClick, Checked, Indeterminate,Unchecked

Page 84: Silver Light Training

User input – ComboBox

• Displays a drop-down list of items a user can select from

• Syntax<ComboBox .../>

• Useful propertiesItems, ItemsSource, SelectedItem,SelectedIndex, SelectedValue, DisplayMemberPath, SelectedValuePath

• Useful eventsSelectionChanged

Page 85: Silver Light Training

User input – ListBox

• Displays a list of items a user can select by clicking• Syntax

<ListBox .../>• Useful properties

Items, ItemsSource, SelectionMode, SelectedItem, SelectedValue,SelectedIndex, DisplayMemberPath, SelectedValuePath

• Useful eventsSelectionChanged

Page 86: Silver Light Training

User input – RadioButton• Allows a user to select a single option from a list of options• Syntax

<RadioButton Content=“string”.../> or <RadioButton ...>

content </RadioButton>

• Useful propertiesContent, IsChecked, GroupName

• Useful eventsClick, Checked, Indeterminate,Unchecked

• Grouping– Radio buttons under same parent are grouped. – Radio buttons with same GroupName are grouped

Page 87: Silver Light Training

User input – Slider

• Represents a control that lets the user select from a range of values by moving a thumb along a track

• Syntax<Slider .../>

• Useful propertiesValue, Minimum, Maximum, SmallChange, LargeChange, Orientation, IsDirectionReversed

Page 88: Silver Light Training

User input – Calendar (SDK)

• Allows a user to select a date from a visual calendar display

• Syntax<sdk:Calendar .../>

• Useful propertiesDisplayMode, SelectionMode, BlackoutDates, SelectedDate, SelectedDates

• Useful eventsSelectedDatesChanged

Page 89: Silver Light Training

User input – DatePicker (SDK)

• Allows a user to select a date by typing it in a text field or selecting it from a drop-down calendar control

• Syntax<sdk:DatePicker .../>

• Useful propertiesSame as Calendar control

Page 90: Silver Light Training

Dialog boxes

– MessageBox – standard .NET message box– OpenFileDialog– SaveFileDialog– ChildWindow– Popup

Page 91: Silver Light Training

Dialog boxes - OpenFileDialog

• Enables the user to select one or more files from the file system

• Syntaxbool? userClickedOK =

(new OpenFileDialog()).ShowDialog();• Useful properties

MultiSelect, File, Files, Filter

Page 92: Silver Light Training

Dialog boxes - SaveFileDialog

• Enables the user to specify options for saving a file

• Syntaxbool? userClickedOK =

(new SaveFileDialog()).ShowDialog();• Useful properties

File, Filter

Page 93: Silver Light Training

Dialog boxes – ChildWindow (SDK)

• Provides a window that can be displayed over a parent window and blocks interaction with the parent window

• Syntax<sdk:ChildWindow Content=“string”.../> or<sdk:ChildWindow ...>

singleObject </sdk:ChildWindow>

• Useful methodsShow, Close

• Useful propertiesTitle, HasCloseButton, DialogResult

• ChildWindow is independent control that has its own XAML and code-behind files

Page 94: Silver Light Training

Dialog boxes – Popup

• Overlays content on top of the existing content within the bounds of the Silverlight plug-in

• Syntax<Popup .../>

• Useful propertiesIsOpen, VerticalOffset, HorizontalOffset

Page 95: Silver Light Training

Media

– Image– MultiScaleImage– MediaElement

Page 96: Silver Light Training

Media - Image• Displays an image• Syntax

<Image .../> • Useful properties

Source, Stretch• Image size is defined by Width, Height and Stretch properties• Image Source

– Absolute URI (http://contoso.com/myPicture.jpg)– Relative to the referencing XAML file, no leading slash

(Source="myPicture.png" or Source="../resources/myPicture.png")– Relative to the XAP file application root

(Source="/resources/myPicture.png“)– Specifying an assembly, and then referencing the component

(Source=“/MySilverlightApp;component/myPicture.png")

Page 97: Silver Light Training

Media – MultiScaleImage (DeepZoom)

• Enables users to open a multi-resolution image which can be scaled or repositioned for detail viewing

• Syntax<MultiScaleImage .../>

• The pictures need to be prepared using DeepZoom Composer

Page 98: Silver Light Training

Media – MediaElement

• Hosts audio or video content• Syntax

<MediaElement Source=“URI”.../>

Page 99: Silver Light Training

HTML display

– WebBrowser

Page 100: Silver Light Training

HTML display - WebBrowser

• Provides a surface for displaying HTML content when the application is hosted outside the browser

• Syntax<WebBrowser .../>

• Useful propertiesSource

Page 101: Silver Light Training

ResourcesStyles

Page 102: Silver Light Training

Resource dictionaries

• A resource dictionary is a keyed dictionary of objects that can be used both in XAML and in code

• Resource dictionaries can exist as:– Immediate (page) resources– Application resources (App.xaml)– Separate XAML resource files

• Typically resources used for sharing objects as Styles, Brushes, Templates, Storyboards, Transforms, custom types, etc

• Every Silverlight element has Resources property that could be used for resources definition

Page 103: Silver Light Training

Keys and resources

• The item within resource dictionary must have a key defined using x:Key attribute. The key must be unique inside particular resource dictionary

• Example<Page> <Page.Resources> <Style x:Key=“ButtonStyle” … /> <SolidColorBrush x:Key=“BlueBrush” … /> </Page.Resources></Page>

Page 104: Silver Light Training

Resource scope• Resources defined in App.xaml file are application

resources - globally available in every page• Resources defined at <root user

control>.Resources are page resources – visible to all elements of the page

• Resources defined in Element.Resources – are element resources – visible to all children of the specific element

• Resources are resolved from bottom-up. From several resources with the same key the nearest to requested element will be taken

Page 105: Silver Light Training

Referencing resources in XAML• StaticResource markup extension is used for referencing

resources in XAML• Syntax

property=“{StaticResource key}”• Example

<Page> <Page.Resources> <SolidColorBrush x:Key=“BlueBrush” … /> </Page.Resources></Page>…<Border Background=“{StaticResource BlueBrush}” …/><TextBox Foraground=“{StaticResource BlueBrush}” …/>

Page 106: Silver Light Training

Referencing resources from code

• Every Silverlight element has FrameworkElement.Resources property of type ResourceDictionary

• ResourceDictionary class has string-keyed indexer:

Brush brush = (Brush)page.Resources[“key1”];App.Current.Resources[“s1”] = “test”;

Page 107: Silver Light Training

Merged resource dictionaries• A merged resource dictionary enables you to declare the

contents of a resource dictionary by referencing an external file• Example

<Grid> <Grid.Resources> <ResourceDictionary> <SolidColorBrush Color="#d0157820" x:Key="muddyBrush"/> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="/rd1.xaml" /> <ResourceDictionary Source="/rd2.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Grid.Resources> .... <Grid>

Page 108: Silver Light Training

Styles• A Style is basically a collection of property

settings applied to single or multiple instances of the same type

• Every Silverlight element has a Style property (FrameworkElement.Style)

• Syntax<Style TargetType=“type”>

<Setter Property=“property” Value=“value”/>…

</Style>

Page 109: Silver Light Training

Inline styles• Style could be defined directly for the element (inline)

<Border> <Border.Style> <Style TargetType="Border"> <Setter Property="Background" Value="Blue“/> <Setter Property="Width" Value="50“/> <Setter Property="Height" Value="50“/> </Style> </Border.Style></Border>

• Inline styles are useless, because properties could be set as attributes

• The real added value of styles is ability to reuse the same style over multiple elements. Such style are always defined inside Resources

Page 110: Silver Light Training

Styles scope

• Style without x:key attribute is called implicit style and it is applied to all elements of specific type under resource container, except elements that have its own style. As result style without x:key defined in App.xaml applies to whole application

• Style with x:key applies only to elements that explicitly called to this style using StaticResource markup

Page 111: Silver Light Training

Styles inheritance

• Style class has BasedOn property that can contain reference to another Style

• When a base style and the BasedOn style have the same property, the property value set in the BasedOn style is used

Page 112: Silver Light Training

STANDARD CONTROLS AND STYLES EXERCISE

Page 113: Silver Light Training

Day 3

• Data Binding• Templates• Custom Controls• Graphics, Transformations and Animations• Exercise

Page 114: Silver Light Training

Data Binding

Page 115: Silver Light Training

Understanding DataBinding• Data binding provides a simple way for Silverlight

applications to display and interact with data• The way data is displayed is separated from the

management of the data• A connection, or binding, between the UI and a

data object allows data to flow between the two• When a binding is established and the data

changes, the UI elements that are bound to the data can reflect changes automatically. Similarly, changes made by the user in a UI element can be reflected in the data object

Page 116: Silver Light Training

Connecting UI Elements with Data• Every binding must specify a source and a target

• Direction (Mode)– OneTime - update the target with the source data

when the binding is created– OneWay - update the target with the source data

(default)– TwoWay - update both the target and the source

when either changes

Page 117: Silver Light Training

Data Binding Syntax

• Markup extension<object property="{Binding …}" .../>

• {Binding path, oneOrMoreBindingProperties}– path – string representing the property path for

the binding. If not specified DataContext property is used

– Binding properties are specified as propertyName=value pairs separated by comma

Page 118: Silver Light Training

DataContext• Data context is a concept that allows objects to

inherit binding-specifying information from their parents in the object tree

• Every control in Silverlight has DataContext property (FrameworkElement .DataContext)

• Example of usage:<StackPanel DataContext=“{Binding …}”>

<TextBlock Text=“{Binding}”/><TextBox Text=“{Binding}”/><Grid>

<TextBlock Text=“{Binding}”/></Grid>

</StackPanel>

Page 119: Silver Light Training

Data Binding properties - Path

• Specifies the path to the binding source property

{Binding} = DataContext{Binding Name} = DataContext.Name{Binding Employee.FirstName} = DataContext. Employee.FirstName{Binding Path=Name} = DataContext.Name{Binding (Errors)[2].Message} = DataContext.Errors[2].Message

Page 120: Silver Light Training

Data Binding properties - Mode

• Specifies the binding mode, as one of the following strings: OneTime, OneWay, or TwoWay.

{Binding path,Mode=OneTime}{Binding path,Mode=OneWay} – default{Binding path,Mode=TwoWay}

Page 121: Silver Light Training

Data Binding properties - ElementName

• Specifies a data source by referencing another element by name

{Binding path,ElementName=name}

Page 122: Silver Light Training

Data Binding properties – fall backs

• FallbackValue - Specifies a value to be assigned when the source path cannot be resolved{Binding path,FallbackValue=string}

• TargetNullValue - Specifies a value to be assigned when the source value is null{Binding path,TargetNullValue=string}

Page 123: Silver Light Training

Data Binding properties – StringFormat

• Specifies the String format to use for display{Binding path,StringFormat=format}

• ExampleText=“{Binding Value, StringFormat=f2}”Displays: 50.12

Page 124: Silver Light Training

Data conversions

• Data binding allows to perform two-way conversions during binding using classes implemented IValueConverter interface

• This interface exposes two methods:– Convert– ConvertBack

• The converter should be defined as Resource and referenced via {Binding Converter={StaticResource key}} markup

• Converters support a single converter parameter which can be specified using {Binding ConverterParameter=string} markup

Page 125: Silver Light Training

Dependency Properties

• The purpose of dependency properties is to provide a way to compute the value of a property based on the value of other inputs

• Most properties of Silverlight elements are dependency properties

• Dependency properties are exposed as regular CLR properties, but the value of dependency property is stored differently.

Page 126: Silver Light Training

Dependency Properties• CLR property usually backed by private field:

private string name;public string Name{

get { return name; }set { name = value; }

}

• Dependency properties are owned only by classes derived from DependencyObject class

• Dependency property must be registered and its identifier is stored as static readonly field in owner class

• The CLR wrapper of dependency property uses GetValue/SetValue methods of DependencyObject

Page 127: Silver Light Training

Dependency Properties

public static readonly DependencyPropertyIsSpinningProperty =

DependencyProperty.Register( "IsSpinning", typeof(Boolean), typeof(SilverlightExampleClass), null );

public bool IsSpinning {

get { return (bool)GetValue(IsSpinningProperty); } set { SetValue(IsSpinningProperty, value); }

}

Page 128: Silver Light Training

Dependency Properties

• A dependency property provides functionality that extends the functionality of regular CLR property:– Target of data binding– Property-Changed behavior – ability to notify

other objects when property is changed (implemented by DependencyObject class)

– Default value

Page 129: Silver Light Training

INotifyPropertyChanged interface

• The ability of dependency property to notify other objects about its value change is relied on implementation of INotifyPropertyChanged interface

• This interface has a single event PropertyChanged that provides the name of changed property

• When source object of data binding is implementing INotifyPropertyChanged interface the changes in source object is automatically reflected by target of data binding

Page 130: Silver Light Training

Data Annotation and Validation

• There are few CLR attributes that when applied on data source impact the display and validation behavior

• The data annotation attributes fall into three categories: validation attributes, display attributes, and data modeling attributes

• Data validation is processed by data binding

Page 131: Silver Light Training

Data validation attributes

• CustomValidationAttribute• DataTypeAttribute• EnumDataTypeAttribute• RangeAttribute• RegularExpressionAttribute• RequiredAttribute• StringLengthAttribute

Page 132: Silver Light Training

Data validation attributespublic class Product {

[Range(0, 5000)] public int ProductID { get; set; }

[Required] public string ProductName { get; set; }

[DataType(DataType.Currency)] public double ListPrice { get; set; }

[EnumDataType(typeof(ProductColor))] public ProductColor Color { get; set; }

}

Page 133: Silver Light Training

Display attributes

• DataTypeAttribute• DisplayAttribute• DisplayColumnAttribute• DisplayFormatAttribute• FilterUIHintAttribute• UIHintAttribute• Display attributes are used by DataGrid control

Page 134: Silver Light Training

Data modeling attributes

• AssosiationAttribute• ConcurrencyCheckAttribute• EditableAttribute• KeyAttribute• TimestampAttribute

Page 135: Silver Light Training

Validation controls (SDK)

• ValidationSummaryDisplays a summary of the validation errors on a form

• DescriptionViewerDisplays a description and tracks error state for an associated control

• LabelDisplays a caption, required field indicator, and validation error indicator for an associated control.

• Validation properties of Data BindingValidatesOnNotifyDataErrors, ValidatesOnDataErrors, ValidatesOnExceptions, NotifyOnValidationError

Page 136: Silver Light Training

Custom validation• Data object may implement IDataErrorInfo or INotifyDataErrorInfo

interfaces in order to provide custom validation logic• IDataErrorInfo interface

Provides simple object validation– Syntax

string this[ string columnName ] { get; }Returns error if property has invalid value

• INotifyDataErrorInfo interfaceProvides more complex validation scenarios– Syntax

IEnumerable GetErrors( string propertyName )bool HasErrors { get; }event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged

• Both interfaces are supported by data binding and validation controls

Page 137: Silver Light Training

Templates

Page 138: Silver Light Training

Control Templates• Every Silverlight control has Control.Template

property that specifies ControlTemplate class object

• ControlTemplate specifies the visual structure and visual behavior of control

• Every standard Silverlight control has default template defined by Microsoft and published in MSDN

• Defining an alternative ControlTemplate allows customization of control representation without effecting the control logic

Page 139: Silver Light Training

Controls used in ControlTemplate• You can use any Silverlight standard or custom

controls inside of ControlTemplate• There is a special controls ContentPresenter and

ItemsPresenter that displays the content of template owner

• You can use binding markups inside ControlTemplate• There is a special binding markup TemplateBinding

that allows to make binding to the property of template owner

• There is a good practice to define control template as part of style for achieving reuse

Page 140: Silver Light Training

Defining control appearance according to visual states

• Many standard and custom controls define different visual states as part of controls definition. For example Button has: Normal, MouseOver, Pressed, Disabled, Focused and Unfocused states. The states could be grouped by state groups

• Control template could define a different visual appearance of control for each state using VisualStateManager and VisualState controls

Page 141: Silver Light Training

ContentControl

• Represents a control with a single piece of content of any type

• Syntax<ContentControl>

single child</ContentControl>

• ContentControl doesn’t have default visual template. Usually used for creating custom templated controls

Page 142: Silver Light Training

ItemsControl

• Represents a control that can be used to present a collection of items

• Syntax<ItemsControl>

one or more items</ItemsControl>

or<ItemsControl ItemsSource=“binding”/>

• ItemsControl doesn’t have a default template for presenting items. The visual representation of items could be defined via ItemTemplate property of type DataTemplate

Page 143: Silver Light Training

VirtualizingStackPanel

• Improves application performance when large number of items is used in ItemsControl

• Syntax<ItemsPanelTemplate> <VirtualizingStackPanel .../> </ItemsPanelTemplate>

• The improvement is achieved by generating only visible elements

Page 144: Silver Light Training

Custom Controls

Page 145: Silver Light Training

Customization in Silverlight

• Silverlight provides several ways for customization of existing controls or creating new controls:– Setting properties of existing control directly or

via styles– Overwriting ControlTemplate of existing control– Creating custom user control– Creating custom templated control

Page 146: Silver Light Training

Custom user control• Reasons for creating custom user controls:– To separate functionality into smaller, manageable

pieces of logic that can be created independently from an application and other controls

– To group related controls that can be used more than once in an application

• Actually there is always at least one custom user control in each Silverlight application – the main page

• Custom user control can be reused in only in application in which it is created

Page 147: Silver Light Training

Custom user control - structure

• Custom user control is combined from XAML file and code-behind file.

• It could contain standard and custom controls included in XAML file and refer these controls in code-behind

• It could contain resources• It could define dependency, attached

properties and events

Page 148: Silver Light Training

CustomerEditor Example<UserControl x:Class="Training.CustomControls.CustomerEditor“ ….. Standard Namespaces ….. xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk" xmlns:local="clr-namespace:Training.CustomControls" x:Name="editor"> <UserControl.Resources> <local:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"></local:BooleanToVisibilityConverter> <Style TargetType="TextBox"> <Setter Property="Width" Value="100"></Setter> </Style> </UserControl.Resources> <StackPanel> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"></ColumnDefinition> <ColumnDefinition Width="5"></ColumnDefinition> <ColumnDefinition Width="Auto"></ColumnDefinition> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition></RowDefinition> <RowDefinition></RowDefinition> <RowDefinition></RowDefinition> <RowDefinition></RowDefinition> </Grid.RowDefinitions> <sdk:Label Grid.Column="0" Grid.Row="0" Target="{Binding ElementName=FistName}"></sdk:Label> <TextBox Grid.Column="2" Grid.Row="0" x:Name="FistName" Text="{Binding FirstName}"></TextBox> <sdk:Label Grid.Column="0" Grid.Row="1" Target="{Binding ElementName=LastName}"></sdk:Label> <TextBox Grid.Column="2" Grid.Row="1" x:Name="LastName" Text="{Binding LastName}"></TextBox> <sdk:Label Grid.Column="0" Grid.Row="2" Target="{Binding ElementName=City}" Visibility="{Binding ShowAddress,ElementName=editor,Converter={StaticResource BooleanToVisibilityConverter}}"></sdk:Label> <TextBox Grid.Column="2" Grid.Row="2" x:Name="City" Text="{Binding City}" Visibility="{Binding ShowAddress,ElementName=editor,Converter={StaticResource BooleanToVisibilityConverter}}"></TextBox> <sdk:Label Grid.Column="0" Grid.Row="3" Target="{Binding ElementName=Address}" Visibility="{Binding ShowAddress,ElementName=editor,Converter={StaticResource BooleanToVisibilityConverter}}"></sdk:Label> <TextBox Grid.Column="2" Grid.Row="3" x:Name="Address" Text="{Binding Address}" Visibility="{Binding ShowAddress,ElementName=editor,Converter={StaticResource BooleanToVisibilityConverter}}"></TextBox> </Grid> <sdk:ValidationSummary></sdk:ValidationSummary> </StackPanel></UserControl>

Page 149: Silver Light Training

CustomerEditor Example public partial class CustomerEditor : UserControl { public bool ShowAddress { get { return (bool)GetValue(ShowAddressProperty); } set { SetValue(ShowAddressProperty, value); } }

public static readonly DependencyProperty ShowAddressProperty = DependencyProperty.Register("ShowAddress", typeof(bool), typeof(CustomerEditor), new PropertyMetadata(true));

public CustomerEditor() { InitializeComponent(); } }

Page 150: Silver Light Training

Custom templated controls

• These controls usually based (derived) from existing controls and extend its functionality

• These controls could be packed into separate DLL (library) and reused in multiple Silverlight applications

• Custom templated control is combined from code-behind file and template defined in Themes\Generic.xaml

Page 151: Silver Light Training

Graphics Transformations Animations

Page 152: Silver Light Training

Shape controls

• Silverlight provides number of “shape” controls that enables drawing of various shapes:– Ellipse– Line– Polygon– Polyline– Rectangle– Path

• All shape controls share the following properties:– Stroke – defines the brush for outline of shape– StrokeThickness – defines the thickness of stroke– Fill – defines the brush that fills the shape

Page 153: Silver Light Training

Cropping objects

• You can crop an object by clipping out an area of the object's display. This is done by using the Clip property

• Clip property gets Geometryobjects:– EllipseGeometry– LineGeometry– RectangleGeometry– PathGeometry– GeometryGroup

Page 154: Silver Light Training

Transforms

• Transforms allow to rotate, scale, skew and move Silverlight controls.

• Every Silverlight control derived from UIElement has RenderTransform property that could be set to one of transform classes:– RotateTransform – rotates an element

by the specified Angle– ScaleTransform – scales an element by

specified ScaleX and ScaleY amounts– SkewTransform – skews an element by

specified AngleX and AngleY amounts– TranslateTransform – moves an element

by specified X and Y amounts

Page 155: Silver Light Training

Transforms cont.

• In order to create more complex transforms the following classes could be used:– CompositeTransform – applies multiple

transforms to the same object– TransformGroup – like CompositeTransform, but

allows to specify the order of transforms– MatrixTransform – allows creation of custom

transformations

Page 156: Silver Light Training

3-D transforms

• Silverlight allows "perspective transforms" that provides 3-D effects

• 3-D transforms are applied via Projection property that should be set to PlaneProjection class

Page 157: Silver Light Training

Animations• Silverlight animates objects by applying animations to individual

properties of object• Animations are executed by Storyboard objects (container for

animations)• Storyboard may contain animations or other nested storyboards:

– Simple animations• DoubleAnimation• ColorAnimation• PointAnimation

– Key frame animations• DoubleAnimationUsingKeyFrames• ColorAnimationUsingKeyFrames• PointAnimationUsingKeyFrames• ObjectAnimationUsingKeyFrames

Page 158: Silver Light Training

Storyboard

• Container for animations• Syntax

<Storyboard>one of many animations

</Storyboard>• Useful methods

Begin, Stop, Pause, Resume• Useful attached properties

Storyboard.TargetName, Storyboard.TargetProperty• Useful properties

Duration• Useful events

Completed

Page 159: Silver Light Training

DoubleAnimation• Animates the value of a Double property between two

target values using linear interpolation over a specified Duration

• Syntax<Storyboard>

<DoubleAnimation Storyboard.TargetName=“element”Storyboard.TargetProperty=“property”

From=“x” To=“y”/> </Storyboard>• Useful properties

AutoReverse, RepeatBehavior, Duration

Page 160: Silver Light Training

ColorAnimation

• Animates the value of a Color property between two target values using linear interpolation over a specified Duration

• Syntax<Storyboard>

<ColorAnimation Storyboard.TargetName=“element”Storyboard.TargetProperty=“property”

From=“color1” To=“color2”/> </Storyboard>• Useful properties

AutoReverse, RepeatBehavior, Duration

Page 161: Silver Light Training

PointAnimation

• Animates the value of a Point property between two target values using linear interpolation over a specified Duration

• Syntax<Storyboard>

<PointAnimation Storyboard.TargetName=“element”Storyboard.TargetProperty=“property”

From=“x1,y1” To=“x2,y2”/> </Storyboard>• Useful properties

AutoReverse, RepeatBehavior, Duration

Page 162: Silver Light Training

Key frame animations

• Key-frame animations enable you to animate using more than two target values, and control an animation's interpolation method

• Key frame animation contains series of key frames. • The key-frame animation classes adhere to the

following naming convention:type_AnimationUsingKeyFrames

• For example: DiscreteDoubleKeyFrame, EasingDoubleKeyFrame, LinearDoubleKeyFrame, SplineDoubleKeyFrame

Page 163: Silver Light Training

BINDING AND CUSTOM CONTROLS EXERCISE

Page 164: Silver Light Training

Day 4

• UI interaction• Triggers• Hosting • Working with Services• Navigation Applications• Debugging Silverlight Applications• Unit Tests• Expression Suite• 3-rd party libraries

Page 165: Silver Light Training

UI Interaction

Page 166: Silver Light Training

Keyboard support• UIElement has 2 keyboard related events:

– KeyDown– KeyUp

• The element must be “in focus” in order to get these events• The handler for these events has the following syntax:

void KeyHandler(object sender, KeyEventArgs e)• KeyEventArgs.Key provides the pressed/released key• These events are “bubbling” events – go from bottom to top in

controls hierarchy. Setting KeyEventArgs.Handled to true stops event bubbling

• Some controls may handle key events and prevent its bubbling. For example TextBox, Button. Usually such controls provide their own events(TextBox.TextChanged, Button.Click, etc)

Page 167: Silver Light Training

Mouse support• There are few mouse related events in UIElement:

– MouseMove– MouseEnter– MouseLeave– MouseLeftButtonDown– MouseLeftButtonUp– MouseRightButtonDown– MouseRightButtonUp– MouseWheel

• All mouse events provides mouse data of type MouseEventArgs (or derived from it) in their handler. This class provides mouse position and Handled property

• Some mouse events are routed (bubbling) events, that can be stopped by setting Handled property to true.

• Controls like Button hides mouse button events and provides its own Click event.

Page 168: Silver Light Training

Drag & Drop support

• UIElement has AllowDrop property (false by default)

• Setting AllowDrop to true indicates that specific element can be drop target of drag-and-drop operations. In this case element starts getting: DragEnter, DragLeave, DragOver and Drop events

Page 169: Silver Light Training

Isolated storage

• Silverlight application usually hosted by browser. This means it is running inside security sandbox and doesn’t have access to file system

• There is a special “safe virtual file system” provided to Silverlight application for its file operations – isolated storage

• Application works with isolated storage via IsolatedStorageFile class

• Isolated storage could be encrypted

Page 170: Silver Light Training

Threading

• Silverlight application has one main application thread (UI thread) and can use additional threads

• BackgroundWorker and ThreadPool classes could be used for providing multithreaded in Silverlight application

• Any UI operations could be executed only in context of UI thread. For this purpose DependencyObject.Dispatcher property provides Dispatcher class that allows invoking methods calls in context of UI thread

Page 171: Silver Light Training

Triggers

Page 172: Silver Light Training

Event triggers• Silverlight supports only event triggers that can start storyboards in

response to an event• Syntax

<EventTrigger>one or more BeginStoryboard

</EventTrigger>• Example

<Rectangle …><Rectangle.Triggers>

<EventTrigger RoutedEvent=“Rectangle.Loaded”><BeginStoryboard>

<Storyboard …> … </Storyboard></BeginStoryboard>

</EventTrigger></Rectangle.Triggers>

</Rectangle>

Page 173: Silver Light Training

Hosting

Page 174: Silver Light Training

Silverlight plug-in

• Silverlight application is usually hosted by web browser• During Silverlight installation a special plug-in is

installed. This plug-in allows executing Silverlight application code

• Every Silverlight application is embedded into HTML page using <object> HTML tag:<object width="300" height="300"

type="application/x-silverlight-2" > <param name="source“ value=“app.xap"/>

</object> • Width and height of object defines the available screen

size of Silverlight application

Page 175: Silver Light Training

Silverlight plug-in parameters• minRuntimeVersion – specifies minimal required

version of Silverlight<param name="minRuntimeVersion" value="version"/>

• initParams – sets user defined initialization parameters. These parameters are passed to Application_Startup method in App.xaml.cs<param name=" initParams" value=“k1=v1[,k2=v2,..,kn=vn]"/>

• splashscreensource – specifies alternative Splash screen to be displayed during application load <param name="splashscreensource" value="uri to XAML"/>

• There are more rear used parameters

Page 176: Silver Light Training

Splash screens

• Silverlight plug-in includes default splash screen which is displayed when download of application takes more than 0.5 sec. The default splash screen displays percent of download

• Splash screen could be customized by providing an alternative XAML page resized in hosting Web site. This is page of type “Silverlight JScript page” – means does not have code-behind

• The URL for alternative splash screen is defined via splashscreensource parameter of Silverlight plug-in

Page 177: Silver Light Training

Out-of-browser support• Silverlight application could be installed locally on user

machine and became out-of-browser application• Out-of-browser support is enabled by checking “Enable

running application out of browser” checkbox in project settings

• User installs application via menu provided by right-clicking on Silverlight application

• Out-of-browser application can run without network connection – offline

• If configured as trusted out-of-browser application may bypass some sandbox restrictions

• Application code may distinguish between running in-browser and out-of-browser by examining Application.IsRunningOutOfBrowser property

Page 178: Silver Light Training

Out-of-browser special features

• Window manipulation – change size, minimize, maximize application window

• Window customization – trusted applications may hide title bar and window border

• HTML hosting – display HTML content within your application using WebBrowser class

• Notification windows – style Outlook e-mail notifications in task bar. NotificationWindow class

• File system access – trusted applications can access files out of isolated storage

Page 179: Silver Light Training

Updates of out-of-browser apps

• Regular Silverlight application is always running its latest version – Silverlight plug-in compares version of XAP stored in browser cache with XAP on the server

• Out-of-browser application must provide its own logic for upgrades. Application class has few related methods and events: CheckAndDownloadUpdateAsync method, CheckAndDownloadUpdateCompleted event

Page 180: Silver Light Training

HTML bridge

In Silverlight, the HTML Bridge is an integrated set of types and methods that enable you to do the following:– Expose complete managed types to JavaScript for

scripting.– Expose individual methods of managed types to JavaScript

for scripting– Pass managed types as parameters to JavaScript functions

and objects– Return managed types from JavaScript– Assign managed types as event handlers, which are

callable from JavaScript– Call JavaScript event handlers from managed types

Page 181: Silver Light Training

Working with Services

Page 182: Silver Light Training

Silverlight networking options

• HTTP classes – Silverlight supports HttpWebRequest/HttpWebResponse and WebClient classes from System.Net namespaceThese classes are useful for accessing REST or raw HTTP services

• Proxy classes – these classes are generated by Visual Studio by adding reference to SOAP Web service or WCF service

• Sockets – Silverlight supports Socket class from System.Net.Sockets namespace which allows adding UDP/TCP/Multicast communication to Silverlight application

Page 183: Silver Light Training

Navigation Applications

Page 184: Silver Light Training

Navigation between pages

• Regular Silverlight application has a single “main page” - the user control specified as RootVisual in Application_Startup of App.xaml.cs

• This “main page” may contain other user controls and may provide interaction behavior by hiding or dynamically creating these user controls

• Other option is reassigning of RootVisual to other control upon user action or other logic

Page 185: Silver Light Training

Navigation in Silverlight 4.0

• In Silverlight 4.0 two new controls were supported: Frame and Page

• Page represents discrete section of content• Frame acts as container for Page controls• At any time Frame displays content of single page• Usually you are creating “main page” and set it as

RootVisual. The main page contains permanent UI – which is not changed during navigation and one or more frames

• The navigation (changing a page displayed in the frame) could be done through user action (HyperlinkButton) or programmatically (Source property, Navigate, GoBack, GoForward methods)

Page 186: Silver Light Training

Uri mapping

• Browser address bar reflects the current page URL when navigation is used

• Frame control supports Uri mapping that allows to map certain pattern to specific Url

• Example: /Home is actually /Views/Home.xaml• The mapping is defined using UriMapper

property of Frame that gets collection of UriMapping classes

Page 187: Silver Light Training

Debugging Silverlight Applications

Page 188: Silver Light Training

Unit Tests

Page 189: Silver Light Training

Expression Suite

Page 190: Silver Light Training

3-rd Party Libraries


Related Documents