Thursday, April 19, 2012

Silverlight For Beginners

What is Silverlight?

Silverlight applications are based on XAML, so first learn something about XAML.
 
1. XAML(eXtensible Application Markup Language) is a declarative language to create UI, such as controls, shapes, text and other contents presented on the screen.
Its like HTML but more powerful, uses elements and attributes.

2. XAML is just a procedural code but easier.
<Button Width="60" Height="30">Click Me</Button>
In code behind we can do this like 
Button myButton = new Button();
myButton.Width = 60;
myButton.Height = 30;
myButton.Content = "Click Me";
LayoutRoot.Children.Add(myButton);

3. Attributes and Elements - Fill is an attribute assigned a color and Rectangle is an element.
<Rectangle Fill="Red">
OR
<Rectangle>
  <Rectangle.Fill>
    <SolidColorBrush Color="Red" />
  </Rectangle.Fill>  
</Rectangle>

4. If an attribute can be assign multiple values and you require that, than we use Elements instead of attribute
<Rectangle Width="200" Height="100">
  <Rectangle.Fill>
    <LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
      <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>
  </Rectangle.Fill>
</Rectangle>

5. Many typical events of child controls can be handled(Bubble up) by parent control those events called Routed events.

Example 

<Grid x:Name="LayoutRoot" Background="Red">
    <StackPanel Margin="20" Background="Yellow" MouseLeftButtonDown="commonMouseHandler" >
        <TextBlock Name="firstTextBlock" Width="Auto" >First TextBlock</TextBlock>
        <TextBlock Name="secondTextBlock" Width="Auto" >Second TextBlock</TextBlock>
        <TextBlock Name="thirdTextBlock" Width="Auto" >Third TextBlock</TextBlock>
    </StackPanel>
</Grid>

C# Code
private void commonMouseHandler(object sender, RoutedEventArgs e)
{
    FrameworkElement feSource = e.OriginalSource as FrameworkElement;
    switch (feSource.Name)
    {
        case "firstTextBlock":
            firstTextBlock.Text = firstTextBlock.Text + " Thanks for the click!"; break;
        case "secondTextBlock":
            secondTextBlock.Text = secondTextBlock.Text + " Thanks for the click!"; break;
        case "thirdTextBlock":
            thirdTextBlock.Text = thirdTextBlock.Text + " Thanks for the click!"; break;
    }
}
To try this example, click the following TextBlock objects. When you click a TextBlock, the event gets captured by the TextBlock, but then the event bubbles up to its parent element (the StackPanel), which then handles the event.
Because the event continues up the tree, you could "listen" for the MouseLeftButtonDown event in the Grid element as well.

6. Animation 
In Resources tag A Story Board is used for adding animation.
Story Board is used to pointout control that to be animated, and its elements are used to set behavior of animation.

Example

<StackPanel x:Name="LayoutRoot" Background="White">
   <StackPanel.Resources>
      <Storyboard x:Name="FirstStoryBoard">
         <DoubleAnimation Storyboard.TargetName="FirstEllipse"
                          Storyboard.TargetProperty="Width"
                          To="1" AutoReverse="True"
                          Duration="00:00:01" />
      </Storyboard>
   </StackPanel.Resources>
   <TextBlock Text="Hello, World!" HorizontalAlignment="Center" />
   <Ellipse Name="FirstEllipse" Height="100" Width="200" Fill="SlateBlue" />
   <Button Name="FirstButton" Width="100" Content="Click" Click="FirstButton_Click" />
</StackPanel>

C# code
private void FirstButton_Click(object sender, RoutedEventArgs e)
{
   FirstButton.Content = "Click Again!";
   FirstStoryBoard.Begin();
}

7. Calling a Silver light application on web page - A silver light application is packaged as an .xap file. We need to call Silverlight plug-Ins and xap file on web page.
We can also define display area by specifying width, height. We write a Object tag and child Param elements to call them.
<body>
   <form id="form1" runat="server" style="height:100%">
     <div id="silverlightControlHost">
       <object data="data:application/x-silverlight-2,"
               type="application/x-silverlight-2"
               width="100%" height="100%">
          <param name="source" value="HelloWorld.xap"/>
          <param name="onError" value="onSilverlightError" />
          <param name="background" value="white" />
          <param name="minRuntimeVersion" value="4.0.50401.0" />
          <param name="autoUpgrade" value="true" />
          <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.50401.0"
                   style="text-decoration:none">
          <img src="http://go.microsoft.com/fwlink/?LinkId=161376"
                   alt="Get Microsoft Silverlight" style="border-style:none"/>
          </a>
       </object>
       <iframe id="_sl_historyFrame"
               style="visibility:hidden;height:0px;width:0px;border:0px">
       </iframe>
     </div>
   </form>
</body>

8. The Silverlight 3 runtime and Silverlight 3 SDK are part of Visual Studio 2010 and Visual Web Developer 2010 Express. The Silverlight 4 runtime and Silverlight 4 SDK are part of the Silverlight Tools for Visual Studio installation. With this installation, you get the Visual Studio Silverlight 4 project templates, the Silverlight 4 runtime, and the Silverlight 4 SDK. The Silverlight Toolkit is a separate installation.

9. Control's categories -

I Layout Controls  
II Text Controls  
III Resource Controls   
IV Content Controls
V List Controls

10. Layout controls
- All are derived from Panel class.
There are 3 types of Layout controls

A. Grid - Collection of rows and columns. (Most useful)

B. Stack Panel - Makes vertical stack or horizontal queue of controls, depends on value of 'Orientation' attribute.

C. Canvas - Places controls on a location, calculated by attributes top, left or bottom, right.
<Grid x:Name="LayoutRoot" Background="LightYellow" ShowGridLines="True" Height="259" Width="429">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="190*" />
        <ColumnDefinition Width="210*" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="150" />
    </Grid.RowDefinitions>
    <TextBlock Margin="5" FontSize="10" Text="Grid Row 0 - Star sized" Grid.ColumnSpan="2" />
    <TextBlock Margin="5,5,-66,-28" FontSize="10" Grid.Row="1" Text="Grid Row 1 - Fixed size" Grid.ColumnSpan="2" />
    <StackPanel Grid.Row="1" Orientation="Horizontal" Grid.Column ="1">
        <TextBlock FontSize="10" Text="Horizontal StackPanel"  Margin="5"/>
        <TextBlock FontSize="10" Text="Row 1, Column 1" Margin="5" />
    </StackPanel>
    <Canvas Grid.Column="1" Grid.Row="0">
        <TextBlock Canvas.Left="20" Canvas.Top="20" FontSize="10" Text="Canvas in Row 0, Column 1" Margin="5"/>
    </Canvas>
</Grid>

11. Text Controls -
A. TextBlock - Its read-only, used to display simple text.
B. TextBox - Used to take short or multi line inputs.
C. PasswordBox - Masks text.
D. RichTextBox - Provide formatting features.
TextBlock, TextBox and RichTextBox can be set by Content property, and PasswordBox can be set by Text property.

12. Resource Controls - All are can be set by Source property.

A. Media elements - For audio/Video
B. Image - For Images
C. WebBrowser - To display Rendered HTML
<Image Height="102" HorizontalAlignment="Left" Margin="39,165,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Top" Width="97" Source="sdk-team.jpg"/>
<MediaElement Height="168" HorizontalAlignment="Left" Margin="195,99,0,0" Name="mediaElement1" VerticalAlignment="Top" Width="248" Source="SilverlightControls.wmv" />
<WebBrowser Source="http://localhost/HTMLPage1.html" Height="160" Width="160" x:Name="WB1"/>

13. Content Controls -
A. Label
B. Button
C. CheckBox
D. RadioButton

Content controls are derived from 'ContentControl' class. These controls can be set by Content property. Type of Content property is 'Object', so it can be set with varied content like other controls.
<Button Height="23" HorizontalAlignment="Left" Margin="18,40,0,0" Name="button1" VerticalAlignment="Top" Width="75" >
    <Button.Content>
        <StackPanel Orientation="Horizontal" >
            <Image Source="sdk-team.jpg"  />
            <TextBlock Text="Button"  />
        </StackPanel>
    </Button.Content>
</Button>

14. Categories of List Controls

A. Items Control
B. Headered Items Control
C. Data Grid
A. Items Controls
- Item Controls used to display collection of data. These controls can be set directly using 'Items' property and by using 'ItemsSource' property you can bind them with a collection of data.
Items controls contains collection of controls those contains each piece of data. Ex ListBox contains collection of ListBoxItem controls those hold data pieces(like rows).
ListBox and TabControl are Items controls.

B. Headered Items Controls - These are derived from HeaderedItemsControl class. These are very similar to Items controls with additional property 'header' to display heading, header property is Object type so can display different types of contents.
Ex of this type is TreeView control. TreView is identical control for displaying hierarchical data.

C. DataGrid Control is special type of control, used to display data in highly customizable Grid. It can be set only by using 'ItemsSource' property.

<ListBox  Name="listBox1" HorizontalAlignment="Left" DisplayMemberPath="Name"
    ItemsSource="{Binding}" Height="134" Width="224" />
<sdk:TreeView Height="132" Name="treeView1" Width="230"
    ItemsSource="{Binding}" ItemTemplate="{StaticResource WriterTemplate}" />
<sdk:DataGrid AutoGenerateColumns="True" Height="133" Name="dataGrid1"
    Width="456" ItemsSource="{Binding}"/>

C# Code
public partial class MainPage : UserControl
{
    public MainPage()
    {
        InitializeComponent();
        ObservableCollection<Writer> writers = new ObservableCollection<Writer>() {
            new Writer("Chris Sells", new ObservableCollection<string>() {"ComboBox", "ComboBoxItem"}, "Writer II"),
            new Writer("Luka Albrous", new ObservableCollection<string>() {"ListBox","ListBoxItem"}, "Senior Writer"),
            new Writer("George Louverdis", new ObservableCollection<string>() {"DataGrid","Binding"}, "Writer I")   };    
        listBox1.DataContext = writers;
        dataGrid1.DataContext = writers;
        treeView1.DataContext = writers;
    }
    public class Writer
    {
        public Writer() { }
        public Writer(string writerName,
        ObservableCollection listOfTypes, string writerTitle)
        {
            Name = writerName;
            Types = listOfTypes;
            Title = writerTitle;
        }
        public string Name { get; set; }
        public ObservableCollection Types { get; set; }
        public string Title { get; set; }
    }
}

15. Layout Systems - You need panel controls to make layout on pages, controls - Canvas, StackPanel and Grid. Two layout types are there

A. Absolute - Canvas we set Canvas.Left and Canvas.Top to position a control on page.

B. Dynamic - StackPanel, Grid


Auto sizing is used to allow controls to fit their content, even if the content changes size. Star sizing is used to distribute available space among the rows and columns of a grid by weighted proportions.
<Grid x:Name="LayoutRoot" Background="White" ShowGridLines="True">
    <Grid.RowDefinitions>
        <RowDefinition Height="auto" />
        <RowDefinition />
        <RowDefinition Height="auto" />
    </Grid.RowDefinitions>

    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>

    <TextBox Text="First row and first column" Grid.Column="0" Grid.Row="0" />
    <TextBox Text="Third row and first column" Grid.Column="0" Grid.Row="2" />
    <Button Content="First row and second column" Grid.Column="1" Grid.Row="0" />
    <Button Content="Third row and second column" Grid.Column="1" Grid.Row="2" />
</Grid>

No comments:

Post a Comment

CI/CD - Safe DB Changes/Migrations

Safe DB Migrations means updating your database schema without breaking the running application and without downtime . In real systems (A...