Saturday, 12 July 2014

Elements in XAML

This article will explain Elements and their types in XAML.

Elements
  1. All XAML elements are an XML representation of CLR classes.
  2. Not all CLR classes have representations in XAML.
  3. XAML elements are usually derived from System.Windows.UIElement; they provide basic visual user interface capabilities. They can render themselves. They can receive input from the keyboard or mouse and can raise events.
  4. Not all XAML elements are derived from System.Windows.UIElement . Some are derived from System.Windows.FrameworkContentElement and System.Windows.Frame-workContentElement. Examples are LineBreak, TableColumn and document etc.
Root Elements
  1. They function as the page's base container for all user interface elements.
  2. A page is required to have one Root Element.
  3. To be considered as a Root Element, the element must be the container of at least one other element.
  4. Examples are Stack Panel, Dock Panel, Canvas, Grid and Page.
  5. A custom Root Element can be created by deriving from Page or Window and exposing them as an XAML element.
Control Element
  1. They handle user interactions.
  2. This Control is of 5 types. As follows:
    1. Simple Controls
    2. Content Controls
    3. Item Controls
    4. Header Item Controls
    5. Header Content Controls
Simple Controls
  • Derived directly from System.Windows.Control
  • They do not have Content, Items and Header attributes. 
    Example: HorizantleScrollBar, VerticalScrollBar, Frame, TextBox, RichTextBox etc.
Content Controls
  • They do have Content attributes.
  • They do not have Item and Header attributes. 
    Example: Button, RepearButton, Label, RadioButton, CheckBox, ListBox Item, GroupItem etc.
Item Controls
  • They do have an Item attribute
  • They do not have content and header attributes.
  • They expose a list of elements, usually offering a choice. 
    Example: ListBox, ComboBox, Menu, ContextMenu,RadioButtonList,TabControl etc .
Header Item Control
  • They do have an Item attribute.
  • They do have a Header attribute.
  • They do not have Content attribute. 

    Example: MenuItem etc.
Panel Elements
  1. Panel elements handle page layout and act as containers for elements like Controls or other panels.
  2. The primary purpose of the panel is to provide support for layout and placement of elements on the page.
  3. Some panel classes are intended for designing the user interface, while others are special panels designed specifically for special layout scenarios.
  4. The panel elements designed for user-interface design are DockPanel, StackPanel, Canvas, WrapPanel, and Grid.
Shape and Geometric Elements
  1. Shape and geometric elements represent 2-D vector graphics
  2. Shapes derive from the Shape class and represent predefined geometric shapes. WPF shapes available for use with XAML are Ellipse, Line, Path, Polygon, Polyline, and Rectangle
  3. Shapes are a type of UIElement, which means they can be used inside panels and most other controls
  4. Geometric elements, while also representing 2-D vector graphics, are more flexible than shape elements and can also be used for hit-testing and clipping purposes
  5. Geometry elements can be simple vector graphics, such as circles or polygons, or more complex elements comprised of Bezier lines and arcs
  6. Geometries cannot render themselves
  7. They must be drawn by another element, such as Drawing or Path
Document Elements
  1. They handle document presentation.
  2. They are of two types either Flow or Fixed.
  3. The Fixed Document element is designed to be what you see is what you get.
  4. A Flow Document provides more flexibility in appearance to enhance readability.
  5. Flow documents dynamically reformat content based on a variety of factors, including screen and page size, font size, and optional user preferences
  6. Flow documents are comprised of one or more elements derived from Block or Inline
  7. Block elements such as Block, Figure, Floater, List, ListItem, Paragraph, Section, Table, and TableCell are used to organize and format blocks of text.
  8. Inline elements are used to format text within a block. Inline elements are Bold, AccessKey, LineBreak, Hyperlink, Italic, Subscript, Superscript, and Underline
Example:
A button with three ellipses inside them. The following XAML does that:
<Window x:Class="Button.Window1"
xmlns
="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns
:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title
="Window1" Height="300" Width="300">
<
StackPanel>
<
Button Width="100" Height="200">
<
DockPanel>
<
Ellipse Margin="10" DockPanel.Dock="Top" Stroke="Red" Fill="red" />
<
Ellipse Margin="10" DockPanel.Dock="Top" Stroke="Black" />
<
Ellipse Margin="10" DockPanel.Dock="Top" Stroke="Black" />
</
DockPanel>
</
Button>
</
StackPanel>
</
Window>

Playing Video in Windows Store App Using C#

Introduction
In a Windows 8 Apps we can also play a video file using the Media Element control of Windows 8 Apps. To play videos in a Windows 8 Apps we use the MediaElement class. We can play audio and video using the HTML5 audio and video tags, or using C#. The Media Element class has many properties and methods that create media more attractively. It provides the options of play, pause, forward etc. To play video files we have set the source to the media file to play. We can set the source at the design time or by selecting from the local system using the FileOPenPicker class.

In this article we create a page that plays a video file with various buttons such as Play, Pause, Forward and Normal. We use the FileOpenPicker class to open a local media file and play it using the Media Element with various options.

Steps to be followed:

Step1: To create a new Windows Store project:
  • Start Visual Studio 2012.
  • Select File > New Project. The New Project dialog box opens.
  • Select the Windows Store template.
  • In the center pane, select Blank Application.
  • Enter a name for the project.
  • Click OK. Your project files are created
Select-Windows-8-apps.jpg

Step 2: Create a MediaElement in the MainPage.xaml page and give it a Name. Set the height and width of the element.
<Page
    x:Class="media.MainPage"
    IsTabStop="false"
    xmlns:local="using:media"
    mc:Ignorable="d">

    <Grid Margin="20,50">
        <Grid.Background>
            <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                <GradientStop Color="Black"/>
                <GradientStop Color="#FFC5947D" Offset="1"/>
            </LinearGradientBrush>
        </Grid.Background>

        <StackPanel x:Name="content" Margin="120,40,-10,0">
            <MediaElement DefaultPlaybackRate="0.5"  x:Name="media" HorizontalAlignment="Left" Height="442" VerticalAlignment="Top" Width="877" Margin="165,150,0,0"/>
        </StackPanel>
      <Button x:Name="select" Click="b_Click_1" Height="63"  Width="229" Content="Select Media file" Margin="24,35,0,576"></Button>
      <Button x:Name="play" Click="play_Click_1"  Height="63" Width="177" FontSize="15"Content="Play" Margin="47,109,0,496"/>
      <Button x:Name="pause" Click="stop_Click_1"  Height="63" Width="177" FontSize="15"Content="Pause" Margin="47,198,0,407"/>
     <Button x:Name="btnForward" Click="btnForward_Click"  Content="Forward" Height="63"Width="177"  FontSize="15" Margin="47,283,0,322" />
     <Button x:Name="normal" Click="normal_Click_1"  Height="63" Width="177" FontSize="15"Content="Normal" Margin="47,369,0,236"/>
   </Grid>
</Page>

Step 3: Include the following namespaces in the MainPage.xaml.cs file:
 
using Windows.Storage.Pickers;
using Windows.Storage;

Step 4: Then, we use the FileOpenPicker class to select a media file from the user in the MainPage.xaml.cs file:
private async void b_Click_1(object sender, RoutedEventArgs e)
{
     var openPicker = new FileOpenPicker();
     openPicker.SuggestedStartLocation = PickerLocationId.VideosLibrary;
     openPicker.FileTypeFilter.Add(".wmv");
     openPicker.FileTypeFilter.Add(".mp4");
     var file = await openPicker.PickSingleFileAsync();
     var stream = await file.OpenAsync(FileAccessMode.Read);
     / mediaControl is a MediaElement defined in XAML
     media.SetSource(stream, file.ContentType);
     media.Play();
}

In the above code we use the FileOpenPicker class. We set the SuggestedStartLocation properties that specify the default location of where the user selects the media file from and the FileTypeFilter properties that specify the type of media file to be play by the Media Element. Here we use Async Calling to pick a file and give the stream of the file to the setSource properties of MediaElement.

Step 5: Then, we provide code for the various buttons that we have created:
 
private void btnForward_Click(object sender, RoutedEventArgs e)
{
    media.DefaultPlaybackRate = 2.0;
    media.Play();
}
private void stop_Click_1(object sender, RoutedEventArgs e)
{
    media.Pause();
}
private void normal_Click_1(object sender, RoutedEventArgs e)
{
    media.DefaultPlaybackRate = 0.5;
    media.Play();
}
private void play_Click_1(object sender, RoutedEventArgs e)
{
    media.Play();
}

Step 6: 
The full code is here that enables the user to choose a file from the local system and play it with various control options:
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Storage.Pickers;
using Windows.Storage;

namespace media
{
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }
       private async void b_Click_1(object sender, RoutedEventArgs e)
        {
            var openPicker = new FileOpenPicker();
            openPicker.SuggestedStartLocation = PickerLocationId.VideosLibrary;
            openPicker.FileTypeFilter.Add(".wmv");
            openPicker.FileTypeFilter.Add(".mp4");
            var file = await openPicker.PickSingleFileAsync();
            var stream = await file.OpenAsync(FileAccessMode.Read);
            // mediaControl is a MediaElement defined in XAML
            media.SetSource(stream, file.ContentType);
            media.Play();
         }
        private void btnForward_Click(object sender, RoutedEventArgs e)
        {
            media.DefaultPlaybackRate = 2.0;
            media.Play();
        }
        private void stop_Click_1(object sender, RoutedEventArgs e)
        {
            media.Pause();
        }
        private void normal_Click_1(object sender, RoutedEventArgs e)
        {
            media.DefaultPlaybackRate = 0.5;
            media.Play();
        }
        private void play_Click_1(object sender, RoutedEventArgs e)
        {
            media.Play();
        }
    }
}

Step 7:
 Press F5 to run the program. Click the "Select Media File" button to select the file to be played:

Media-Element-In-Windows8-Apps.jpg

Step 8: Select Media file from the local system drives and click "Open" button.

File-Upload-In-Windows8-Apps.jpg

Step 9: The media is playing on the Media Element control on the page.
 The user can use various control options to pause, play, forward and normal buttons. When the user clicks on the "Pause" button the video is paused until the user plays it again.
If we want to fast forward a video then we click on the "Forward" button. To return to normal speed click the "Normal" button.


Playing-Video-file-In-Windows8-Apps.jpg