145
DONG NAI UNIVERSITY OF TECHNOLOGY 1 5. Navigation 3. Data binding 1. Building The UI with XAML 4. MVVM 2. Phone controls

2 - Xaml, Phone Controls and Navigation (9t)

Embed Size (px)

DESCRIPTION

2 - Xaml, Phone Controls and Navigation (9t)

Citation preview

Page 1: 2 - Xaml, Phone Controls and Navigation (9t)

1

DONG NAI UNIVERSITY OF TECHNOLOGY

5. Navigation

3. Data binding

1. Building The UI with XAML

4. MVVM

2. Phone controls

Page 2: 2 - Xaml, Phone Controls and Navigation (9t)

2

DONG NAI UNIVERSITY OF TECHNOLOGY

1. Building The UI with XAML

1.1 Working with XAML

1.2 Using with Brush

1.3 Resources and Style

1.4 Templates

Page 3: 2 - Xaml, Phone Controls and Navigation (9t)

3

DONG NAI UNIVERSITY OF TECHNOLOGY

1.1 Working with XAML

XAML(Extended Application Markup Language) is a declarative markup language used to create user interfaces. Each XAML element represents an instantiated object. XAML elements are typically visual but can also represent data sources or custom objects.

The root element is PhoneApplicationPage

Your typical starting point will be the MainPage.xaml file that defines the initial user interface

Page 4: 2 - Xaml, Phone Controls and Navigation (9t)

4

DONG NAI UNIVERSITY OF TECHNOLOGY

1.1 Working with XAML

<phone:PhoneApplicationPage x:Class="LearnXAML.MainPage" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" FontFamily="{StaticResource PhoneFontFamilyNormal}" FontSize="{StaticResource PhoneFontSizeNormal}" Foreground="{StaticResource PhoneForegroundBrush}" SupportedOrientations="Portrait" Orientation="Portrait" shell:SystemTray.IsVisible="True">

</phone:PhoneApplicationPage>

Page 5: 2 - Xaml, Phone Controls and Navigation (9t)

5

DONG NAI UNIVERSITY OF TECHNOLOGY

1.1 Working with XAML

XAML Namespace

Prefix String xmlns:x or xmlns:phone

No Prefix Stringxmlns

Namespace Name

Page 6: 2 - Xaml, Phone Controls and Navigation (9t)

6

DONG NAI UNIVERSITY OF TECHNOLOGY

1.1 Working with XAML

XAML Namespace syntax declare

Page 7: 2 - Xaml, Phone Controls and Navigation (9t)

7

DONG NAI UNIVERSITY OF TECHNOLOGY

1.1 Working with XAML

XAML Namespace syntax declare

namespace drthanh.com{ public class MyButton:Button { public MyButton() { Width = 300; Height = 100; SolidColorBrush brush = new SolidColorBrush(Colors.Red); this.Background = brush; } }}

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Controls;using System.Windows.Media;

Page 8: 2 - Xaml, Phone Controls and Navigation (9t)

8

DONG NAI UNIVERSITY OF TECHNOLOGY

1.1 Working with XAML

XAML Namespace syntax declare

xmlns:com="clr-namespace:drthanh.com"

<com:MyButton Content= "Xuân Di u"ệ />

Page 9: 2 - Xaml, Phone Controls and Navigation (9t)

9

DONG NAI UNIVERSITY OF TECHNOLOGY

1.1 Working with XAML

Syntax for Attribute

Object element syntax – Like object syntax <Button> IT DNTU </Button>

Attribute syntax Property Element Syntax Attached Property Syntax

Page 10: 2 - Xaml, Phone Controls and Navigation (9t)

10

DONG NAI UNIVERSITY OF TECHNOLOGY

1.1 Working with XAML

Syntax for Attribute

Page 11: 2 - Xaml, Phone Controls and Navigation (9t)

11

DONG NAI UNIVERSITY OF TECHNOLOGY

1.1 Working with XAML Syntax for Attribute

Property Element Syntax – Some properties are too complex to be set with a simple string – Does not produce an object, sets a property on an object

Page 12: 2 - Xaml, Phone Controls and Navigation (9t)

12

DONG NAI UNIVERSITY OF TECHNOLOGY

1.1 Working with XAML Syntax for Attribute

<Button > <Button.Background> <LinearGradientBrush StartPoint="0,0" EndPoint="1,1"> <GradientStop Color="Red" Offset="0.0"/> <GradientStop Color="Blue" Offset="1.0"/> </LinearGradientBrush> </Button.Background> Click me</Button>

Property Element Syntax

Page 13: 2 - Xaml, Phone Controls and Navigation (9t)

13

DONG NAI UNIVERSITY OF TECHNOLOGY

1.1 Working with XAML Syntax for Attribute

Attached Property Syntax – Attached properties are a special type of property that is defined in one class but used in another.

Page 14: 2 - Xaml, Phone Controls and Navigation (9t)

14

DONG NAI UNIVERSITY OF TECHNOLOGY

1.1 Working with XAML Syntax for Attribute

Page 15: 2 - Xaml, Phone Controls and Navigation (9t)

15

DONG NAI UNIVERSITY OF TECHNOLOGY

1.1 Working with XAML

Markup Extensions

Markup Extensions are expressions surrounded by curly braces to denote syntax that is different from standard XAML. Typically, markup extensions refer to resources or binding expressions.

<TextBlock x:Name="ApplicationTitle" Text="{Binding MyTitle}" Style="{StaticResource PhoneTextNormalStyle}" />

Page 16: 2 - Xaml, Phone Controls and Navigation (9t)

16

DONG NAI UNIVERSITY OF TECHNOLOGY

1.2 Using with Brush

Brush

SolidColorBrush GradientBrush TileBrush

LinearGradientBrush RadialGradientBrush

Page 17: 2 - Xaml, Phone Controls and Navigation (9t)

17

DONG NAI UNIVERSITY OF TECHNOLOGY

1.2 Using with Brush

Page 18: 2 - Xaml, Phone Controls and Navigation (9t)

18

DONG NAI UNIVERSITY OF TECHNOLOGY

1.2 Using with Brush

using System.Windows.Media

SolidColorBrush

Color cr = new Color();cr.B = cr.R = cr.G = 122;cr.A = 255;

SolidColorBrush br = new SolidColorBrush(cr);button1.Background = br;

Page 19: 2 - Xaml, Phone Controls and Navigation (9t)

19

DONG NAI UNIVERSITY OF TECHNOLOGY

1.2 Using with Brush

SolidColorBrush

<Button Content="Button" > <Button.Background> <SolidColorBrush Color="Red"> </SolidColorBrush> </Button.Background></Button>

XAML

Page 20: 2 - Xaml, Phone Controls and Navigation (9t)

20

DONG NAI UNIVERSITY OF TECHNOLOGY

1.2 Using with Brush

LinearGradientBrush

LinearGradientBrush br = new LinearGradientBrush();

GradientStop gs1 = new GradientStop();gs1.Color = Colors.Red;gs1.Offset = 0;GradientStop gs2 = new GradientStop();gs2.Color = Colors.White;gs2.Offset = 1.0;br.GradientStops.Add(gs1);br.GradientStops.Add(gs2);button1.Background = br;

Page 21: 2 - Xaml, Phone Controls and Navigation (9t)

21

DONG NAI UNIVERSITY OF TECHNOLOGY

1.2 Using with Brush

LinearGradientBrush

<Button Content= "drthanh" > <Button.Background> <LinearGradientBrush> <GradientStop Color="Red" Offset="0.0"/> <GradientStop Color="Blue" Offset="0.5"/> <GradientStop Color="White" Offset="1.0"/> </LinearGradientBrush> </Button.Background></Button>XAML

Page 22: 2 - Xaml, Phone Controls and Navigation (9t)

22

DONG NAI UNIVERSITY OF TECHNOLOGY

1.2 Using with Brush

RadialGradientBrush

RadialGradientBrush br = new RadialGradientBrush(Colors.Red,Colors.Blue);button1.Background = br;

Page 23: 2 - Xaml, Phone Controls and Navigation (9t)

23

DONG NAI UNIVERSITY OF TECHNOLOGY

1.2 Using with Brush

RadialGradientBrush

RadialGradientBrush br = new RadialGradientBrush();br.GradientOrigin = new Point(0.75, 0.25);GradientStop gs1 = new GradientStop();gs1.Color = Colors.Yellow;gs1.Offset = 0;GradientStop gs2 = new GradientStop();gs2.Color = Colors.Orange;gs2.Offset = 0.5;GradientStop gs3 = new GradientStop();gs3.Color = Colors.Blue;gs3.Offset = 1.0;br.GradientStops.Add(gs1);br.GradientStops.Add(gs2);br.GradientStops.Add(gs3);button1.Background = br;

Page 24: 2 - Xaml, Phone Controls and Navigation (9t)

24

DONG NAI UNIVERSITY OF TECHNOLOGY

1.2 Using with Brush

RadialGradientBrush

<Button x:Name="button1" Content="drthanh"> <Button.Background> <RadialGradientBrush GradientOrigin="0.75,0.25"> <GradientStop Color="Yellow" Offset="0.0"/> <GradientStop Color="Orange" Offset="0.5"/> <GradientStop Color="Blue" Offset="1.0"/> </RadialGradientBrush> </Button.Background></Button>

XAML

Page 25: 2 - Xaml, Phone Controls and Navigation (9t)

25

DONG NAI UNIVERSITY OF TECHNOLOGY

1.2 Using with Brush

ImageBrush

XAML

<Button Content="drthanh" > <Button.Background> <ImageBrush ImageSource="Assets\\childrens.PNG"> </ImageBrush> </Button.Background></Button>

Page 26: 2 - Xaml, Phone Controls and Navigation (9t)

26

DONG NAI UNIVERSITY OF TECHNOLOGY

1.2 Using with Brush

ImageBrush using System.Windows.Media;using System.Windows.Media.Imaging; ImageBrush br = new ImageBrush();

br.ImageSource = new BitmapImage ( new Uri( "Assets\\hinhvui.PNG", UriKind.Relative) );

btnimg.Background = br;

Page 27: 2 - Xaml, Phone Controls and Navigation (9t)

27

DONG NAI UNIVERSITY OF TECHNOLOGY

1.3 Resources and Style

<Grid.Resources > <RadialGradientBrush x:Key="mybrush"> <RadialGradientBrush.GradientStops> <GradientStop Color="Yellow" Offset="0"/> <GradientStop Color="Red" Offset="0.25"/> <GradientStop Color="Blue" Offset="0.75"/> <GradientStop Color="LimeGreen" Offset="0.8"/> <GradientStop Color="Black" Offset="1" /> </RadialGradientBrush.GradientStops> </RadialGradientBrush></Grid.Resources>

<Button Background="{StaticResource ResourceKey=mybrush}" Content="DRTHANH"/>

<TextBox Background="{StaticResource ResourceKey=mybrush}" />

Page 28: 2 - Xaml, Phone Controls and Navigation (9t)

28

DONG NAI UNIVERSITY OF TECHNOLOGY

1.3 Resources and Style

Merging Resourcesshare resource in application

Create New file XML template, change extension to .xaml

Page 29: 2 - Xaml, Phone Controls and Navigation (9t)

29

DONG NAI UNIVERSITY OF TECHNOLOGY

1.3 Resources and Style

Merging Resources

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <LinearGradientBrush x:Key="drthanhbrush"> <GradientStop Color="AliceBlue" Offset="0" /> <GradientStop Color="Blue" Offset=".7" /> </LinearGradientBrush></ResourceDictionary>

MyResource.xaml

Page 30: 2 - Xaml, Phone Controls and Navigation (9t)

30

DONG NAI UNIVERSITY OF TECHNOLOGY

1.3 Resources and Style

Merging Resources

Open App.xaml:

<Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="MyResource.xaml"/> </ResourceDictionary.MergedDictionaries> <local:LocalizedStrings xmlns:local="clr-namespace:LearnResource" x:Key="LocalizedStrings"/> </ResourceDictionary></Application.Resources>MainPage.xaml:

<Button Background="{StaticResource ResourceKey=drthanhbrush}" Content="Hello Tèo"/>

Page 31: 2 - Xaml, Phone Controls and Navigation (9t)

31

DONG NAI UNIVERSITY OF TECHNOLOGY

1.3 Resources and Style

Style

Group of property settings Apply that style to many different elements Set the inner properties of a XAML element using

setters – Setters require two attributes

Property & Value Can set event triggers – Applies itself whenever a target condition is evaluated to true

Page 32: 2 - Xaml, Phone Controls and Navigation (9t)

32

DONG NAI UNIVERSITY OF TECHNOLOGY

1.3 Resources and Style

Style<Grid.Resources > <Style x:Key="buttonStyle" TargetType="Button"> <Setter Property="Height" Value="100" /> <Setter Property="Width" Value="200"/> <Setter Property="FontSize" Value="16"/> <Setter Property="FontWeight" Value="Bold"/> <Setter Property="Background" Value="BlueViolet"/> </Style></Grid.Resources>

<Button Style="{StaticResource ResourceKey=buttonStyle}"

Content= "drthanh"/>

Page 33: 2 - Xaml, Phone Controls and Navigation (9t)

33

DONG NAI UNIVERSITY OF TECHNOLOGY

1.3 Resources and Style

Style Inheritance

Page 34: 2 - Xaml, Phone Controls and Navigation (9t)

34

DONG NAI UNIVERSITY OF TECHNOLOGY

1.4 Templates

<Button Content="Button" > <Button.Template> <ControlTemplate> <Border CornerRadius="10" BorderThickness="3" BorderBrush="White" Margin="5" Padding="5"> <TextBlock Text="drthanh" /> </Border> </ControlTemplate> </Button.Template></Button>

ControlTemplate

Page 35: 2 - Xaml, Phone Controls and Navigation (9t)

35

DONG NAI UNIVERSITY OF TECHNOLOGY

1.4 Templates

ControlTemplate<Grid.Resources > <ControlTemplate x:Key="ButtonTemplate" TargetType="Button"> <Border CornerRadius="10" BorderThickness="3" BorderBrush="White" Margin="5" Padding="5"> <TextBlock Text="{TemplateBinding Content}" /> </Border> </ControlTemplate></Grid.Resources>

<Button Template="{StaticResource ResourceKey=ButtonTemplate}" Content="DrThanh" />

Page 36: 2 - Xaml, Phone Controls and Navigation (9t)

36

DONG NAI UNIVERSITY OF TECHNOLOGY

2. Phone controls

1.1 Layout Controls

1.2 Button & TextBlock Controls

1.3 Input Controls

1.4 Radio and Checkbox Controls

1.5 List Controls

1.6 Menu Controls

1.7 Media Controls

1.8 Popups, MessageBox

Page 37: 2 - Xaml, Phone Controls and Navigation (9t)

37

DONG NAI UNIVERSITY OF TECHNOLOGY

1.1 Layout Controls

Phone controls that inherit from Panel are used to position and arrange child objects. The three key objects that handle layout are Grid, StackPanel, and Canvas:

Grid positions elements in rows and columns of cells.StackPanel positions elements in a horizontal or vertical

series.Canvas positions elements at absolute coordinates.

The PhoneApplicationPage is designed to accept a single element of content. This means that you can only have one layout control added directly to the page.

Page 38: 2 - Xaml, Phone Controls and Navigation (9t)

38

DONG NAI UNIVERSITY OF TECHNOLOGY

1.1 Layout Controls

Canvas is a container for applications where elements are drawn at arbitrary locations and may overlap

Canvas

<Canvas x:Name="LayoutRoot"> <Ellipse Name="myEllipse" Canvas.Left="97" Canvas.Top="73" Width="100" Height="100" Fill="LawnGreen" /></Canvas>

Page 39: 2 - Xaml, Phone Controls and Navigation (9t)

39

DONG NAI UNIVERSITY OF TECHNOLOGY

1.1 Layout Controls

Canvas

DispatcherTimer timer = new DispatcherTimer();private void Button_Click_1(object sender, RoutedEventArgs e){ timer.Interval = new TimeSpan(0, 0, 1); timer.Start(); timer.Tick += timer_Tick;}Random rd = new Random();void timer_Tick(object sender, EventArgs e){ myEllipse.RenderTransform = new TranslateTransform() {X=rd.Next(0,300),Y=rd.Next(0,300) };}

Added a Button to process change location for myEllipse:

Page 40: 2 - Xaml, Phone Controls and Navigation (9t)

40

DONG NAI UNIVERSITY OF TECHNOLOGY

1.1 Layout Controls

Canvas - overlap <Canvas x:Name="LayoutRoot"> <Ellipse Canvas.Left="38" Canvas.Top="81" Canvas.ZIndex="0" Width="100" Height="100" Fill="Green"/> <Ellipse Canvas.Left="84" Canvas.Top="48" Width="100" Height="100" Canvas.ZIndex="1" Fill="Yellow"/> <Ellipse Canvas.Left="24" Canvas.Top="10" Width="100" Height="100" Fill="Red" /></Canvas>

Page 41: 2 - Xaml, Phone Controls and Navigation (9t)

41

DONG NAI UNIVERSITY OF TECHNOLOGY

1.1 Layout Controls

StackPanel

StackPanel arranges child objects in a horizontal or vertical series. By default, the StackPanel Orientationis Vertical and places child elements from top to bottom.

<StackPanel x:Name="LayoutRoot" > <Ellipse Canvas.Left="38" Canvas.Top="81" Canvas.ZIndex="0" Width="100" Height="100" Fill="Green"/> <Ellipse Canvas.Left="84" Canvas.Top="48" Width="100" Height="100" Canvas.ZIndex="1" Fill="Yellow"/> <Ellipse Canvas.Left="24" Canvas.Top="10" Width="100" Height="100" Fill="Red" /></StackPanel> Orientation="Horizontal"

Page 42: 2 - Xaml, Phone Controls and Navigation (9t)

42

DONG NAI UNIVERSITY OF TECHNOLOGY

1.1 Layout Controls

WrapPanel

WrapPanel is similar to StackPanel, but adds the ability to wrap overflowing content to the next row or column. WrapPanel can arrange child items in Vertical or Horizontal

Right click on the References/Manage NuGet Packages

Page 43: 2 - Xaml, Phone Controls and Navigation (9t)

43

DONG NAI UNIVERSITY OF TECHNOLOGY

1.1 Layout Controls

WrapPanel

Page 44: 2 - Xaml, Phone Controls and Navigation (9t)

44

DONG NAI UNIVERSITY OF TECHNOLOGY

1.1 Layout Controls

WrapPanel

xmlns:toolkit="clr-namespace: Microsoft.Phone.Controls; assembly=Microsoft.Phone.Controls.Toolkit"

To use the toolkit within a XAML page, the XML namespace must be referenced for the PhoneApplicationPage.

This is achieved by adding the xmlns:toolkit reference to the page as shown below:

Page 45: 2 - Xaml, Phone Controls and Navigation (9t)

45

DONG NAI UNIVERSITY OF TECHNOLOGY

1.1 Layout Controls

WrapPanel

The toolkit provides the following components:

•AutoCompleteBox•ContextMenu•CustomMessageBox•DateTimeConverters•DateTimePickers•Effects – SlideInEffect, TiltEffect and TurnstileFeatherEffect•ExpanderView•HubTile

•ListPicker•LongListMultiSelector•Map extensions•PhoneTextBox•RatingControl•ToggleSwitch•TransferControl•Navigation transitions•WrapPanel

Page 46: 2 - Xaml, Phone Controls and Navigation (9t)

46

DONG NAI UNIVERSITY OF TECHNOLOGY

1.1 Layout Controls

WrapPanel

<toolkit:WrapPanel x:Name="LayoutRoot" Orientation="Vertical"ItemHeight="130" ItemWidth="130"> <Ellipse > <Ellipse.Fill> ??? </Ellipse.Fill> </Ellipse>??????</toolkit:WrapPanel>

Page 47: 2 - Xaml, Phone Controls and Navigation (9t)

47

DONG NAI UNIVERSITY OF TECHNOLOGY

1.1 Layout Controls

Grid

The Grid arranges elements in rows and columns. By default, the Grid is used for new pages. Grid is easy to extend when you need to add new elements and is conceptually similar to an HTML table.

Without setting any RowDefinition and ColumnDefinition properties, each element in the Grid takes up the same amount of space

Page 48: 2 - Xaml, Phone Controls and Navigation (9t)

48

DONG NAI UNIVERSITY OF TECHNOLOGY

1.1 Layout Controls

Grid: Row and Column Definitions

To get any mileage out of the Grid you need to define columns and rows. ColumnDefinitions and RowDefinitions collections are somewhat similar to HTML row <tr> and cell <td> elements.

<Grid x:Name="LayoutRoot" > <Button Content="Click Me!" Background="BlueViolet" /></Grid>

Page 49: 2 - Xaml, Phone Controls and Navigation (9t)

49

DONG NAI UNIVERSITY OF TECHNOLOGY

1.1 Layout Controls

Grid: Row and Column Definitions

<Grid x:Name="LayoutRoot" > <Grid.Resources > <Style x:Key="ButtonStyle" TargetType="Button"> <Setter Property="FontSize" Value="50"/> <Setter Property="FontWeight" Value="Bold"/> <Setter Property="Background" Value="BlueViolet"/> </Style> </Grid.Resources>

Page 50: 2 - Xaml, Phone Controls and Navigation (9t)

50

DONG NAI UNIVERSITY OF TECHNOLOGY

1.1 Layout Controls

Grid: Row and Column Definitions

<Grid.ColumnDefinitions> <ColumnDefinition Width="150" /> <ColumnDefinition Width="170"/> <ColumnDefinition Width="160"/></Grid.ColumnDefinitions><Grid.RowDefinitions> <RowDefinition Height="150" /> <RowDefinition Height="100" /> <RowDefinition Height="200"/></Grid.RowDefinitions>

Page 51: 2 - Xaml, Phone Controls and Navigation (9t)

51

DONG NAI UNIVERSITY OF TECHNOLOGY

1.1 Layout Controls

<Button Content="0,0" Grid.Row="0" Grid.Column="0" Style="{StaticResource ButtonStyle}"/> <Button Content="0,1" Grid.Row="0" Grid.Column="1" Style="{StaticResource ButtonStyle}"/> <Button Content="0,2" Grid.Row="0" Grid.Column="2" Style="{StaticResource ButtonStyle}"/> <Button Content="1,0" Grid.Row="1" Grid.Column="0" Style="{StaticResource ButtonStyle}"/> <Button Content="1,1" Grid.Row="1" Grid.Column="1" Style="{StaticResource ButtonStyle}"/> <Button Content="1,2" Grid.Row="1" Grid.Column="2" Style="{StaticResource ButtonStyle}"/> <Button Content="2,0" Grid.Row="2" Grid.Column="0" Style="{StaticResource ButtonStyle}"/> <Button Content="2,1" Grid.Row="2" Grid.Column="1" Style="{StaticResource ButtonStyle}"/> <Button Content="2,2" Grid.Row="2" Grid.Column="2" Style="{StaticResource ButtonStyle}"/></Grid>

Page 52: 2 - Xaml, Phone Controls and Navigation (9t)

52

DONG NAI UNIVERSITY OF TECHNOLOGY

1.1 Layout Controls

BorderBorder is not a layout control itself, but is used to create a border and background for a single element. Border is often used to surround a Grid or StackPanel<Border BorderThickness="8,4,2,1" > <Border.BorderBrush> <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> <GradientStop Color="???" Offset="0"/> <GradientStop Color="???" Offset="1"/></LinearGradientBrush></Border.BorderBrush> <Grid x:Name="ContentPanel" >??? </Grid></Border>

Page 53: 2 - Xaml, Phone Controls and Navigation (9t)

53

DONG NAI UNIVERSITY OF TECHNOLOGY

1.1 Layout Controls

ScrollViewer

Page 54: 2 - Xaml, Phone Controls and Navigation (9t)

54

DONG NAI UNIVERSITY OF TECHNOLOGY

1.1 Layout Controls

ScrollViewer

<phone:PhoneApplicationPage.Resources><Style x:Name="MyTextBlockStyle" TargetType="TextBlock"> <Setter Property="TextWrapping" Value="Wrap" /> <Setter Property="Margin" Value="0,10,0,10" /> </Style></phone:PhoneApplicationPage.Resources>

Page 55: 2 - Xaml, Phone Controls and Navigation (9t)

55

DONG NAI UNIVERSITY OF TECHNOLOGY

1.1 Layout Controls

ScrollViewer<ScrollViewer Margin="20" Height="550" x:Name="myscrollview" VerticalAlignment="Top"> <StackPanel Orientation="Vertical" > <TextBlock Style="{StaticResource MyTextBlockStyle}" > Website Khoa Công Nghệ Thông Tin – Đại Học Công Nghệ ĐôVng Nai: <LineBreak/> <Run Foreground="Red">http://it.dntu.edu.vn</Run> <LineBreak/> Đây là trang thông tin của Khoa Công Nghệ Thông Tin trường Đại học Công Nghệ Đồng Nai (DNTU) dành cho </StackPanel></ScrollViewer>

Page 56: 2 - Xaml, Phone Controls and Navigation (9t)

56

DONG NAI UNIVERSITY OF TECHNOLOGY

1.1 Layout Controls

ScrollViewer- Scrolling Programmatically

To scroll to the top or bottom of the ScrollViewer programmatically, use the ScrollToVerticalOffset() and ScrollToHorizontalOffset() methods,

myscrollview.ScrollToVerticalOffset(5);

myscrollview. ScrollToHorizontalOffset(5);

Page 57: 2 - Xaml, Phone Controls and Navigation (9t)

57

DONG NAI UNIVERSITY OF TECHNOLOGY

1.1 Layout Controls

ScrollViewer- Scrolling Programmatically private void btnScrollTop_Click(object sender, RoutedEventArgs e) { if (myscrollview.ScrollableHeight +

myscrollview.VerticalOffset < myscrollview.ExtentHeight)

myscrollview.ScrollToVerticalOffset (5 + myscrollview.VerticalOffset);

}private void btnScrollBottom_Click(object sender, RoutedEventArgs e) { if (myscrollview.VerticalOffset >=0)

myscrollview.ScrollToVerticalOffset(myscrollview.VerticalOffset-5);

}

Page 58: 2 - Xaml, Phone Controls and Navigation (9t)

58

DONG NAI UNIVERSITY OF TECHNOLOGY

1.2 Button & TextBlock Controls

Class Diagram of Button Classes

Page 59: 2 - Xaml, Phone Controls and Navigation (9t)

59

DONG NAI UNIVERSITY OF TECHNOLOGY

1.2 Button & TextBlock Controls

Example to Search

using Microsoft.Phone.Tasks;

private void btnSearch_Click(object sender, RoutedEventArgs e){ SearchTask searchTask = new SearchTask(); searchTask.SearchQuery = "duythanhcse"; searchTask.Show();}

Page 60: 2 - Xaml, Phone Controls and Navigation (9t)

60

DONG NAI UNIVERSITY OF TECHNOLOGY

1.2 Button & TextBlock Controls

TextBlock

Static text, standard font properties: FontFamily, FontSize, FontStyle, FontWeight: for using simple static text <LineBreak/> to inject line break Using <Run> : each run have its own formatting

<TextBlock > NEVER STOP LEARNING. <LineBreak/> NEVER <Run Foreground="red" x:Name="mystop" FontSize="35">STOP </Run> SEARCHING</TextBlock>

Page 61: 2 - Xaml, Phone Controls and Navigation (9t)

61

DONG NAI UNIVERSITY OF TECHNOLOGY

1.2 Button & TextBlock Controls

TextBlock

private void TextBlock_MouseLeftButtonDown_1 (object sender, System.Windows.Input.MouseButtonEventArgs e){ mystop.Foreground = new

SolidColorBrush(Colors.Yellow);}

Page 62: 2 - Xaml, Phone Controls and Navigation (9t)

62

DONG NAI UNIVERSITY OF TECHNOLOGY

1.3 Input Controls

TextBox

TextBox is a one-size-fits-all data input control where the pop-up keyboard characteristics are controlled by the InputScope property. Name Text SelectedText IsReadOnly MaxLength TextAlignment: Center|Left| Right| Justify InputScope AcceptsReturn TextWrapping

Methods Select(start, length) SelectAll()

Page 63: 2 - Xaml, Phone Controls and Navigation (9t)

63

DONG NAI UNIVERSITY OF TECHNOLOGY

1.3 Input Controls

TextBox

Windows Phone 8 doesn’t have a “text area” or a control with a multi-line property. Instead, increase the Height of the control, turn on AcceptsReturn and TextWrapping properties

<TextBox AcceptsReturn="True" TextWrapping="Wrap" Height="150“ Text="This is text that will appear on several lines. This will also handle carriage returns." />

Page 64: 2 - Xaml, Phone Controls and Navigation (9t)

64

DONG NAI UNIVERSITY OF TECHNOLOGY

1.3 Input Controls

TextBox

Input Keyboards

Page 65: 2 - Xaml, Phone Controls and Navigation (9t)

65

DONG NAI UNIVERSITY OF TECHNOLOGY

1.3 Input Controls

PasswordBox

PasswordBox is a simple control that does not have an InputScope property and shows the default keyboard layout as below:

NamePasswordPasswordChar

Page 66: 2 - Xaml, Phone Controls and Navigation (9t)

66

DONG NAI UNIVERSITY OF TECHNOLOGY

1.3 Input Controls

RichTextBox

RichTextBox holds formatted text, hyperlinks, inline images, and other rich content. The Paragraphs element contains Runs of Text, Hyperlink, and InlineUIContainer.

Page 67: 2 - Xaml, Phone Controls and Navigation (9t)

67

DONG NAI UNIVERSITY OF TECHNOLOGY

1.3 Input Controls RichTextBox

<RichTextBox > <Paragraph> <InlineUIContainer> <Image Stretch="Fill" Width="300" Height="200"> <Image.Source> <BitmapImage UriSource="http://it.dntu.edu.vn/wp- content/uploads/2013/12/post1.png" /> </Image.Source> </Image> </InlineUIContainer> <Hyperlink NavigateUri="http://it.dntu.edu.vn/?p=963" TargetName="_blank"> <Span Foreground="Blue" TextDecorations="Underline"> <Run Text= "Xem chi tiếZt" /> </Span> </Hyperlink> </Paragraph><Paragraph> <Run Text=" Để tạo sân chơi Công Nghệ mang tầm cỡ thế giới…"/></Paragraph></RichTextBox>

Page 68: 2 - Xaml, Phone Controls and Navigation (9t)

68

DONG NAI UNIVERSITY OF TECHNOLOGY

1.3 Input Controls

AutoCompleteBox

AutoCompleteBox is like the TextBox, but has a list of possible values that display automatically. AutoCompleteBox is currently included in the Toolkit download<toolkit:AutoCompleteBox x:Name="autocompletebox1" ></toolkit:AutoCompleteBox> autocompletebox1.ItemsSource=new List<string>() { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };

Page 69: 2 - Xaml, Phone Controls and Navigation (9t)

69

DONG NAI UNIVERSITY OF TECHNOLOGY

1.3 Input Controls

AutoCompleteBox

If the ItemsSource is a complex object, assign the property to display in the ValueMemberPath.

public class AutoData { public string Id { get; set; } public string Name { get; set; } public override string ToString() { return this.Name; } }

Page 70: 2 - Xaml, Phone Controls and Navigation (9t)

70

DONG NAI UNIVERSITY OF TECHNOLOGY

1.3 Input Controls

AutoCompleteBoxList<AutoData> ds = new List<AutoData>();ds.Add(new AutoData() { Id = "1", Name = "Hà Nội"});ds.Add(new AutoData() { Id = "2", Name = "HuếZ" });ds.Add(new AutoData() { Id = "3", Name = "Sài Gòn" });ds.Add(new AutoData() { Id = "4", Name = "Hà Giang" });ds.Add(new AutoData() { Id = "5", Name = "Lâm ĐôVng" });ds.Add(new AutoData() { Id = "6", Name = "BếZn Tre" });autocompletebox2.ItemsSource = ds;autocompletebox2.ValueMemberPath = "Name";

Page 71: 2 - Xaml, Phone Controls and Navigation (9t)

71

DONG NAI UNIVERSITY OF TECHNOLOGY

1.3 Input Controls

Slider

Use the Sliders paringly in your user interface for quickly roughing in approximate values, not precision adjustments.

<TextBox x:Name="txtdata" Text="{Binding ElementName=slider1, Path=Value}"/>

<Slider x:Name="slider1" />

Page 72: 2 - Xaml, Phone Controls and Navigation (9t)

72

DONG NAI UNIVERSITY OF TECHNOLOGY

1.3 Input Controls

DatePicker and TimePicker

Using TextBox with Date input values is not particularly visual and a weak substitute for DatePicker and TimePicker controls. The picker controls display the standard date and time for the current culture. Both DatePicker and TimePicker are in the Windows Phone Toolkit available at CodePlex.

Page 73: 2 - Xaml, Phone Controls and Navigation (9t)

73

DONG NAI UNIVERSITY OF TECHNOLOGY

1.3 Input Controls

DatePicker and TimePickerOnce selected, both picker controls display a page with three columns of “rolling” elements that can be dragged to select values. Clicking the OK or Cancel buttons sets the Value and returns to the original picker display.

Page 74: 2 - Xaml, Phone Controls and Navigation (9t)

74

DONG NAI UNIVERSITY OF TECHNOLOGY

1.3 Input Controls

DatePicker and TimePicker<Grid x:Name="LayoutRoot" Background="Transparent"> <toolkit:DatePicker x:Name="txtDate" Header="Project Start Date“ Value="01/01/2013" ValueStringFormat="{}{0:D}"/>

<toolkit:TimePicker x:Name="txtTime" Header="Project Start Time " />

<Button x:Name="btnOK" Content="Click OK" Click="btnOK_Click"/>

</Grid>

Page 75: 2 - Xaml, Phone Controls and Navigation (9t)

75

DONG NAI UNIVERSITY OF TECHNOLOGY

1.3 Input Controls

DatePicker and TimePicker

private void btnOK_Click(object sender, RoutedEventArgs e){ MessageBoxResult ret= MessageBox.Show( "Date="+txtDate.Value.ToString()+"\n"+ "Time="+txtTime.Value.ToString(), "Thông báo",MessageBoxButton.OKCancel); if (ret == MessageBoxResult.OK) { //làm cái gì đó }}

Page 76: 2 - Xaml, Phone Controls and Navigation (9t)

76

DONG NAI UNIVERSITY OF TECHNOLOGY

1.4 Radio and Checkbox Controls

RadioButtonRadioButton is a ToggleButton descendant that uses the GroupName property to work in concert with other RadioButtons in the user interface.<RadioButton x:Name="radRatNgon" Content="RâZt ngon" IsChecked="True" GroupName="groupchon"/><RadioButton x:Name="radNgon" Content="Ngon" GroupName="groupchon"/>

if (radRatNgon.IsChecked == true) { }

Page 77: 2 - Xaml, Phone Controls and Navigation (9t)

77

DONG NAI UNIVERSITY OF TECHNOLOGY

1.4 Radio and Checkbox Controls

CheckboxCheckBox is also a ToggleButton descendant with the standard check box appearance.

if (chkJava.IsChecked==true){ }

<CheckBox x:Name="chkJava" Content="Java"/><CheckBox x:Name="chkCSharp" Content="C#"/>

Page 78: 2 - Xaml, Phone Controls and Navigation (9t)

78

DONG NAI UNIVERSITY OF TECHNOLOGY

1.5 List Controls

List controls display a series of data vertically in an open list or in a drop-down control. These lists allow binding data and the ability to setup a template for each item in the list.

LongListSelector

ListPicker

Page 79: 2 - Xaml, Phone Controls and Navigation (9t)

79

DONG NAI UNIVERSITY OF TECHNOLOGY

1.5 List Controls

LongListSelector displays lengthy lists of data as flat lists or displayed in grouped sections “jump list” style, similar to the standard “People” contacts application.

Bind a Simple List

Grouping

Grouping Complex Objects

Page 80: 2 - Xaml, Phone Controls and Navigation (9t)

80

DONG NAI UNIVERSITY OF TECHNOLOGY

1.5 List Controls

Bind a Simple List

To use LongListSelector without grouping, in a “flat” list, you only need to assign data to the ItemsSource property and an ItemTemplate to tell LongListSelector where to display the data

public class MyObject { public string

Category { get; set; } public string

Data { get; set; } } Coding behind

Page 81: 2 - Xaml, Phone Controls and Navigation (9t)

81

DONG NAI UNIVERSITY OF TECHNOLOGY

1.5 List Controls

Bind a Simple List private void Button_Click_1(object sender, RoutedEventArgs e) {

var flatList = new List<MyObject>() {new MyObject() { Category = "A", Data = "some data 1" },new MyObject() { Category = "A", Data = "some data 2" },new MyObject() { Category = "B", Data = "some data 3" },new MyObject() { Category = "C", Data = "some data 4" },new MyObject() { Category = "C", Data = "some data 5" },new MyObject() { Category = "C", Data = "some data 6" }};

longlistselector1.ItemsSource = flatList;}

private void TextBlock_MouseLeftButtonDown_1(object sender, System.Windows.Input.MouseButtonEventArgs e){ TextBlock t = sender as TextBlock; t.Foreground = new SolidColorBrush(Colors.Red);} Coding behind

Page 82: 2 - Xaml, Phone Controls and Navigation (9t)

82

DONG NAI UNIVERSITY OF TECHNOLOGY

1.5 List Controls

Bind a Simple List

<phone:LongListSelector x:Name="longlistselector1" > <phone:LongListSelector.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Data}" MouseLeftButtonDown ="TextBlock_MouseLeftButtonDown_1"/> </DataTemplate> </phone:LongListSelector.ItemTemplate></phone:LongListSelector>

XAML

Page 83: 2 - Xaml, Phone Controls and Navigation (9t)

83

DONG NAI UNIVERSITY OF TECHNOLOGY

1.5 List Controls

GroupingAt a minimum, grouped lists require that you configure and bind grouped data, assign templates, and set group-related Properties, Steps: Arrange the data to form a list of groups of objects.

Massaging this data is the most involved part of setting up LongListSelector.

Bind the grouped data to the LongListSelector ItemsSource Assign the ItemTemplate to define layout for each data

item: GroupHeaderTemplate for the layout that appears above groups of items and JumpListStyle that configures the jump list.

Set group-related properties.

Page 85: 2 - Xaml, Phone Controls and Navigation (9t)

85

DONG NAI UNIVERSITY OF TECHNOLOGY

1.5 List Controls

Grouping

public class MyObject { public string Category { get; set; } public string Data { get; set; } }

public class Group<TKey, T> : List<T> { public Group(TKey key, IEnumerable<T> items) : base(items) { this.Key = key; } public TKey Key { get; set; } }

Page 86: 2 - Xaml, Phone Controls and Navigation (9t)

86

DONG NAI UNIVERSITY OF TECHNOLOGY

1.5 List Controls

Grouping<phone:PhoneApplicationPage.Resources> <DataTemplate x:Key="MyObjectItemTemplate"> <TextBlock Text="{Binding Data}" Style="{StaticResource PhoneTextLargeStyle}"/> </DataTemplate> <phone:JumpListItemBackgroundConverter x:Key="BackgroundConverter"/> <phone:JumpListItemForegroundConverter x:Key="ForegroundConverter"/> <DataTemplate x:Key="GroupTile"> <Grid HorizontalAlignment="Left" Width="100" Height="100" Margin="5,20,5,5" Background="{Binding Converter={StaticResource BackgroundConverter}}"> <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Margin="5" Text="{Binding Title}" Style="{StaticResource PhoneTextExtraLargeStyle}" Foreground="{Binding Converter={StaticResource ForegroundConverter}}"/> </Grid> </DataTemplate> <Style x:Key="MyObjectJumpListStyle" TargetType="phone:LongListSelector"> <Setter Property="GridCellSize" Value="120,120"/> <Setter Property="LayoutMode" Value="Grid" /> <Setter Property="ItemTemplate" Value="{StaticResource GroupTile}" /> </Style></phone:PhoneApplicationPage.Resources>

Page 87: 2 - Xaml, Phone Controls and Navigation (9t)

87

DONG NAI UNIVERSITY OF TECHNOLOGY

1.5 List Controls

Grouping

<Grid x:Name="LayoutRoot" Background="Transparent"> <phone:LongListSelector x:Name="LongListSelector1" ItemTemplate="{StaticResource MyObjectItemTemplate}" GroupHeaderTemplate="{StaticResource GroupTile}" JumpListStyle="{StaticResource MyObjectJumpListStyle}" IsGroupingEnabled="true" /></Grid>

Page 88: 2 - Xaml, Phone Controls and Navigation (9t)

88

DONG NAI UNIVERSITY OF TECHNOLOGY

1.5 List Controls

Groupingpublic void loadDataSample() { var flatList = new List<MyObject>() { new MyObject() { Category = "A", Data = "some data 1" }, new MyObject() { Category = "A", Data = "some data 2" }, new MyObject() { Category = "B", Data = "some data 3" }, new MyObject() { Category = "C", Data = "some data 4" }, new MyObject() { Category = "C", Data = "some data 5" }, new MyObject() { Category = "C", Data = "some data 6" }, new MyObject() { Category = "D", Data = "some data 7" }, new MyObject() { Category = "E", Data = "some data 8" }, new MyObject() { Category = "E", Data = "some data 9" }, new MyObject() { Category = "E", Data = "some data 10" }, }; var groups = (from obj in flatList group obj by obj.Category into g orderby g.Key select new Group<string, MyObject>(g.Key, g)); LongListSelector1.ItemsSource = groups.ToList(); }

public MainPage() { InitializeComponent(); loadDataSample(); }

Page 89: 2 - Xaml, Phone Controls and Navigation (9t)

89

DONG NAI UNIVERSITY OF TECHNOLOGY

1.5 List Controls

Grouping Complex Objects

Page 90: 2 - Xaml, Phone Controls and Navigation (9t)

90

DONG NAI UNIVERSITY OF TECHNOLOGY

1.5 List Controls

ListPicker

The ListPicker is the Windows Phone Toolkit answer to the combobox

<toolkit:ListPicker x:Name="RegionPicker"> <toolkit:ListPickerItem

Content="North America" /> <toolkit:ListPickerItem

Content="Asia" /> <toolkit:ListPickerItem

Content="Europe" /></toolkit:ListPicker>

Page 91: 2 - Xaml, Phone Controls and Navigation (9t)

91

DONG NAI UNIVERSITY OF TECHNOLOGY

1.5 List Controls

ListPicker

SelectedIndex;SelectedItem;Items.Add;Items.RemoveAt;Items.Remove;Items.Clear

RegionPicker.Items.Add( new ListPickerItem() { Content = "North America", Tag = 123});

if (RegionPicker.SelectedIndex != -1) { object objSelected = RegionPicker.SelectedItem; //proccess objSelected }

Page 92: 2 - Xaml, Phone Controls and Navigation (9t)

92

DONG NAI UNIVERSITY OF TECHNOLOGY

1.6 Menu Controls

Menu controls display a series of items where each item has text that describes some action, an icon, and an event handler used to execute the action. Menus typically appear in the ApplicationBar or as context menu that can appear above any element.

Page 93: 2 - Xaml, Phone Controls and Navigation (9t)

93

DONG NAI UNIVERSITY OF TECHNOLOGY

1.6 Menu Controls

ApplicationBar

The ApplicationBar is defined in the Microsoft.Phone.Shell namespace and is available to any new page using the “shell” XML namespace.

Page 94: 2 - Xaml, Phone Controls and Navigation (9t)

94

DONG NAI UNIVERSITY OF TECHNOLOGY

1.6 Menu Controls

ApplicationBar<phone:PhoneApplicationPage.ApplicationBar><shell:ApplicationBar> <shell:ApplicationBarIconButton IconUri="/assets/save.png" Text="save" Click="ApplicationBarIconButton_Click_1" /> <shell:ApplicationBarIconButton IconUri="/assets/cancel.png" Text="cancel" /> <shell:ApplicationBar.MenuItems> <shell:ApplicationBarMenuItem Text="Go to Google" Click="ApplicationBarMenuItem_Click_1" /> <shell:ApplicationBarMenuItem Text="Go to Media" /> <shell:ApplicationBarMenuItem Text="Go to Contact" /> </shell:ApplicationBar.MenuItems> </shell:ApplicationBar></phone:PhoneApplicationPage.ApplicationBar>

Page 95: 2 - Xaml, Phone Controls and Navigation (9t)

95

DONG NAI UNIVERSITY OF TECHNOLOGY

1.6 Menu Controls

ApplicationBar

private void ApplicationBarMenuItem_Click_1 (object sender, EventArgs e) { SearchTask task = new SearchTask(); task.SearchQuery = "drthanh"; task.Show(); }private void ApplicationBarIconButton_Click_1 (object sender, EventArgs e) {

}

Page 96: 2 - Xaml, Phone Controls and Navigation (9t)

96

DONG NAI UNIVERSITY OF TECHNOLOGY

1.6 Menu Controls

Context Menus

Use the ContextMenu attached property of ContextMenuService from the Windows Phone 8 toolkit to create menus that respond to tap-and-hold gestures on a given element. ContextMenu can be attached to any DependencyObject.

Page 97: 2 - Xaml, Phone Controls and Navigation (9t)

97

DONG NAI UNIVERSITY OF TECHNOLOGY

1.6 Menu Controls

Context Menus<TextBox VerticalAlignment="Top" HorizontalAlignment="Stretch"><toolkit:ContextMenuService.ContextMenu> <toolkit:ContextMenu> <toolkit:MenuItem Header="spell check" Tag="spellcheck" Click="Context_Menu_Click"> </toolkit:MenuItem> <toolkit:MenuItem Header="synonyms" Tag="synonyms" Click="Context_Menu_Click"> </toolkit:MenuItem> </toolkit:ContextMenu></toolkit:ContextMenuService.ContextMenu></TextBox>

Page 98: 2 - Xaml, Phone Controls and Navigation (9t)

98

DONG NAI UNIVERSITY OF TECHNOLOGY

1.7 Media Controls

Media controls present images, multi-scale images, sound, or video files. The Image, MultiScaleImage, and MediaElement controls allow you to incorporate rich media directly into your own application without having to invoke some other process. Image

The Image Source property knows how to convert data from multiple sources: external URLs, paths to images in your DLL, or paths within the project

Source Stretch Height Width

<Image Source= "http://drthanh.com/hinh.png"Stretch="Uniform" Height="200" Width="250" />

Page 99: 2 - Xaml, Phone Controls and Navigation (9t)

99

DONG NAI UNIVERSITY OF TECHNOLOGY

1.7 Media Controls

Image The Fill : Causes the Image to adopt the exact

width and height dimensions of the Image, while ignoring proportion.

The None : Displays the image in its original dimensions. This option retains the proportion and fidelity of the original image but clips the Image Width and Height boundaries.

The Uniform : Displays the entire graphic within Image boundaries while preserving proportions.

The UniformToFill : preserves proportions, fills to the dimensions of the Image, but may extend past the Image boundaries.

Page 100: 2 - Xaml, Phone Controls and Navigation (9t)

100

DONG NAI UNIVERSITY OF TECHNOLOGY

1.7 Media Controls

MediaElement

<MediaElement Source="/Assets/phim.wmv" AutoPlay="True" VerticalAlignment="Stretch" HorizontalAlignment="Stretch"/>

Page 101: 2 - Xaml, Phone Controls and Navigation (9t)

101

DONG NAI UNIVERSITY OF TECHNOLOGY

1.7 Media Controls

MediaElement Closed Opening Buffering Playing Stopped Individualizing AquiringLicense

Page 102: 2 - Xaml, Phone Controls and Navigation (9t)

102

DONG NAI UNIVERSITY OF TECHNOLOGY

1.7 Media Controls

MediaElement

private void btnPlay_Click(object sender, RoutedEventArgs e){ MediaWindow.Play();}

private void btnPause_Click(object sender, RoutedEventArgs e){ MediaWindow.Pause();}

private void btnForward_Click(object sender, RoutedEventArgs e){ TimeSpan current = MediaWindow.Position; MediaWindow.Position = current.Add(new TimeSpan(0, 0, 1));}

Page 103: 2 - Xaml, Phone Controls and Navigation (9t)

103

DONG NAI UNIVERSITY OF TECHNOLOGY

1.7 Media Controls

MediaElement - MediaPlayerLauncher

private void btnMediaPlayerLauncher_Click(object sender, RoutedEventArgs e) { MediaPlayerLauncher launcher = new MediaPlayerLauncher(); launcher.Media = new Uri("http://imgsrc.hubblesite.org/hu/gallery/db/video/hm_helix_twist/formats/hm_helix_twist_320x240.wmv", UriKind.Absolute); launcher.Show(); }

Page 104: 2 - Xaml, Phone Controls and Navigation (9t)

DONG NAI UNIVERSITY OF TECHNOLOGY

104

1.7 Media Controls

MultiScaleImage

Images have a 2000 x 2000 limit in Windows Phone 8, but there are circumstances that need larger images or that require “Deep Zoom” capability:High-resolution images over 2000 x 2000. Panoramas where a set of overlapping photographs form a

wide banner. Collections of images, such as photo albums or large sets

of tiles that represent business entities.

The MultiScaleImage control allows the user to zoom in on a particular part of the image while maintaining sharp clarity.

Page 106: 2 - Xaml, Phone Controls and Navigation (9t)

DONG NAI UNIVERSITY OF TECHNOLOGY

106

1.7 Media Controls

MultiScaleImageThe steps to creating a Deep Zoom application are:1. Create a Deep Zoom XML file and associated folders and images. We will discuss utilities that automate this step.2. Deploy the Deep Zoom format files and folders to a web site. You will need to provide a host site that can be accessed through HTTP.3. Assign the XML file to the MultiScaleImage Source property. You should be able to see the image in the Visual Studio design view if the path to the Source is valid.4. Add behaviors through code or XAML for zooming and panning.

Page 107: 2 - Xaml, Phone Controls and Navigation (9t)

107

DONG NAI UNIVERSITY OF TECHNOLOGY

1.8 Popups, MessageBox

Popup is an element that contains content in a Child property and has an IsOpen property that toggles the popup visibility.

Popups

private void Button_Click(object sender, RoutedEventArgs e) { MyPopup.IsOpen = true; }private void MyPopup_Tap(object sender, System.Windows.Input.GestureEventArgs e) { MyPopup.IsOpen = false; }

Page 108: 2 - Xaml, Phone Controls and Navigation (9t)

108

DONG NAI UNIVERSITY OF TECHNOLOGY

1.8 Popups, MessageBox

Popups<Button Content="Show Popup" Click="Button_Click"/> <Popup x:Name="MyPopup" VerticalOffset="150" HorizontalOffset="120"> <Popup.Child> <Border BorderBrush="Red" BorderThickness="3"> <StackPanel Margin="1" Tap="MyPopup_Tap" Orientation="Horizontal" Background="White"> <Image Margin="5" Source="/Assets/falafel_logo_48px.png" /> <TextBlock Margin="5" Text="Text for my popup" Foreground="Black"/> </StackPanel> </Border> </Popup.Child> </Popup>

Page 109: 2 - Xaml, Phone Controls and Navigation (9t)

109

DONG NAI UNIVERSITY OF TECHNOLOGY

1.8 Popups, MessageBox

MessageBox

MessageBoxResult ret = MessageBox.Show( "Nội dung thông báo", "Tiếu đếV", MessageBoxButton.OKCancel); if (ret == MessageBoxResult.OK) { }

Page 110: 2 - Xaml, Phone Controls and Navigation (9t)

110

DONG NAI UNIVERSITY OF TECHNOLOGY

3. Data binding

3.1 Binding Basics

3.2 Binding in Code

3.3 Binding Collections

3.4 Binding to ListBox

Page 111: 2 - Xaml, Phone Controls and Navigation (9t)

111

DONG NAI UNIVERSITY OF TECHNOLOGY

3. Data binding

Data binding is essentially a conversation between a Windows Phone element and a standard CLR object. FrameworkElement introduces the DataContext property and is the base class for elements that can be data bound. DataContext can be assigned any CLR object using XAML or directly in code.

Page 112: 2 - Xaml, Phone Controls and Navigation (9t)

112

DONG NAI UNIVERSITY OF TECHNOLOGY

3.1 Binding Basics

The key properties in a {Binding} statement are:

Source: The CLR object that provides the data. This object is assigned to the DataContext of the target framework element we’re binding to.

Path: The name of the property in the source CLR object. Mode: The data’s direction of travel.

o OneTime, where the target framework element is set initially from the source object.

o OneWay (the default), where the target framework element is updated by the source object,

o TwoWay where the target framework element also updates the source object.

Page 113: 2 - Xaml, Phone Controls and Navigation (9t)

113

DONG NAI UNIVERSITY OF TECHNOLOGY

3.1 Binding Basics

namespace LearnBindingBasic{ public class MyData { public int ID { get; set; } public string AppTitle { get; set; } public string PageName { get; set; } }} xmlns:local="clr-

namespace:LearnBindingBasic"

Page 114: 2 - Xaml, Phone Controls and Navigation (9t)

114

DONG NAI UNIVERSITY OF TECHNOLOGY

3.1 Binding Basics

<Grid x:Name="ContentPanel" > <TextBlock Text="{Binding Path=AppTitle, Source={StaticResource ResourceKey=xxx}}" /></Grid>

<phone:PhoneApplicationPage.Resources> <local:MyData x:Key="xxx" ID="113" AppTitle="Cagnh sát 113" PageName="page cagnh sát"/> </phone:PhoneApplicationPage.Resources>

Page 115: 2 - Xaml, Phone Controls and Navigation (9t)

115

DONG NAI UNIVERSITY OF TECHNOLOGY

3.2 Binding in Code

Binding requires three objects: the FrameworkElement to display the data, a CLR object to contain the data and a Binding object to manage the conversation between the two. The XAML binding expression obscures the existence of the binding object, but the Binding object is more apparent when binding in code.

public class BikeType { public string TypeName

{get;set;} public string TypeDescription

{ get; set; } }

<TextBox x:Name="BindInCodeTextBox" />

Page 116: 2 - Xaml, Phone Controls and Navigation (9t)

116

DONG NAI UNIVERSITY OF TECHNOLOGY

3.2 Binding in Code

using System.Windows.Data;// create a CLR object instanceBikeType bikeType = new BikeType() { TypeName = "Touring", TypeDescription = "Durable and comfortable bikes for long journeys." };// create a Binding objectBinding binding = new Binding() { Source = bikeType, Path = new PropertyPath("TypeName"), Mode = BindingMode.OneTime };// assign the binding object to the FrameworkElementBindInCodeTextBox.SetBinding(TextBox.TextProperty, binding);

Page 117: 2 - Xaml, Phone Controls and Navigation (9t)

117

DONG NAI UNIVERSITY OF TECHNOLOGY

3.3 Binding Collections

ItemsSource (or its descendant ListBox) can be assigned any Ienumerable implementation such as generic lists or arrays. By changing the MyData example and descending from a generic List<>, we can represent a list of Itemtypes.

namespace LearnBindingCollections{ public class Item { public string Title { get; set; } public string Description

{ get; set; } }}

Page 118: 2 - Xaml, Phone Controls and Navigation (9t)

118

DONG NAI UNIVERSITY OF TECHNOLOGY

3.3 Binding Collections

namespace LearnBindingCollections{ public class MyData : List<Item> { public int ID { get; set; } public string AppTitle { get; set; } public string PageName { get; set; } public MyData() { this.ID = 1; this.AppTitle = "Real Estate Explorer"; this.PageName = "Explorer"; this.Add(new Item { Title = "Open House", Description = "Open Houses in your area" }); this.Add(new Item { Title = "Price Reduction", Description = "New deals this week“ }); this.Add(new Item { Title = "Recently Sold", Description = "What's moving in the market" }); } }}

Page 119: 2 - Xaml, Phone Controls and Navigation (9t)

119

DONG NAI UNIVERSITY OF TECHNOLOGY

3.3 Binding Collections

xmlns:local="clr-namespace:LearnBindingCollections"

<phone:PhoneApplicationPage.Resources> <local:MyData x:Key="MyData"></local:MyData></phone:PhoneApplicationPage.Resources>

Page 120: 2 - Xaml, Phone Controls and Navigation (9t)

120

DONG NAI UNIVERSITY OF TECHNOLOGY

3.3 Binding Collections

<Grid x:Name="LayoutRoot" DataContext="{StaticResource MyData}"> <StackPanel x:Name="TitlePanel" > <TextBlock x:Name="ApplicationTitle" Text="{Binding Path=AppTitle}" Style="{StaticResource PhoneTextNormalStyle}" /> <TextBlock x:Name="PageTitle" Text="{Binding Path=PageName}" Style="{StaticResource PhoneTextTitle1Style}" /> </StackPanel> <Grid x:Name="ContentPanel" > <ItemsControl ItemsSource="{StaticResource MyData}" DisplayMemberPath="Title" /> </Grid></Grid>

Page 121: 2 - Xaml, Phone Controls and Navigation (9t)

121

DONG NAI UNIVERSITY OF TECHNOLOGY

3.4 Binding to ListBox

<Grid x:Name="ContentPanel" Grid.Row="1"> <ListBox x:Name="PriorityList" Height="100" HorizontalAlignment="Stretch" VerticalAlignment="Top" SelectedIndex="0"> <ListBoxItem Content="High" /> <ListBoxItem Content="Medium"/> <ListBoxItem Content="Low" /> </ListBox> <TextBox

Text="{Binding ElementName=PriorityList, Path=SelectedItem.Content}"HorizontalAlignment="Stretch"VerticalAlignment="Top" Grid.Row="1" />

</Grid>

Page 122: 2 - Xaml, Phone Controls and Navigation (9t)

122

DONG NAI UNIVERSITY OF TECHNOLOGY

4. MVVM

Page 123: 2 - Xaml, Phone Controls and Navigation (9t)

123

DONG NAI UNIVERSITY OF TECHNOLOGY

4. MVVM

Model-View-ViewModel

View

ViewModelCommands

Data Binding

Model

Page 124: 2 - Xaml, Phone Controls and Navigation (9t)

124

DONG NAI UNIVERSITY OF TECHNOLOGY

4. MVVM

Why MVVM?

Model

public class KittenObject{ public KittenObject() { } public string KittenImage { get; set; } public string KittenName { get; set; } public string KittenAge { get; set; }}

Page 125: 2 - Xaml, Phone Controls and Navigation (9t)

125

DONG NAI UNIVERSITY OF TECHNOLOGY

4. MVVM

Why MVVM?

ViewModel

public class MainViewModel : INotifyPropertyChanged{ public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(String propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (null != handler) { handler(this, new PropertyChangedEventArgs(propertyName)); } }}

Page 126: 2 - Xaml, Phone Controls and Navigation (9t)

126

DONG NAI UNIVERSITY OF TECHNOLOGY

4. MVVM

Why MVVM?

ViewModel

private string _sampleProperty = "my start value";public string SampleProperty{ get { return _sampleProperty; } set { _sampleProperty = value; NotifyPropertyChanged("SampleProperty"); }}

Page 127: 2 - Xaml, Phone Controls and Navigation (9t)

127

DONG NAI UNIVERSITY OF TECHNOLOGY

4. MVVM

Why MVVM?

View

<TextBox Text="{Binding SampleProperty, Mode=TwoWay}" />

Page 128: 2 - Xaml, Phone Controls and Navigation (9t)

128

DONG NAI UNIVERSITY OF TECHNOLOGY

4. MVVM

Why MVVM?

View

<phone:LongListSelector ItemsSource="{Binding MyListOfItems}" SelectedItem="{Binding MySelectedItem, Mode=TwoWay}" />

Page 129: 2 - Xaml, Phone Controls and Navigation (9t)

129

DONG NAI UNIVERSITY OF TECHNOLOGY

4. MVVM

Model-View-ViewModel

View

ViewModelCommands

Data Binding

Model

Page 130: 2 - Xaml, Phone Controls and Navigation (9t)

130

DONG NAI UNIVERSITY OF TECHNOLOGY

4. MVVM

Data Binding Modes

• The Mode property determines how changes are synchronized between the target control and data source

– OneTime – Control property is set once to the data value and any subsequent changes are ignored

– OneWay – Changes in the data object are synchronized to the control property, but changes in the control are not synchronized back to the data object

– TwoWay – Changes in the data object are synchronized to the control property and vice-versa

<TextBlock x:Name="ContentText" Text="{Binding LineThree, Mode=OneWay}"/>

Page 131: 2 - Xaml, Phone Controls and Navigation (9t)

131

DONG NAI UNIVERSITY OF TECHNOLOGY

4. MVVM

INotifyPropertyChanged

• ViewModels implement INotifyPropertyChanged public class ItemViewModel : INotifyPropertyChanged { private string lineOne; public string LineOne { get { return lineOne; } set { if (value != lineOne) { lineOne = value; NotifyPropertyChanged("LineOne"); } } }

public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(String propertyName) { if (null != PropertyChanged) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } }

Page 132: 2 - Xaml, Phone Controls and Navigation (9t)

132

DONG NAI UNIVERSITY OF TECHNOLOGY

4. MVVM

• In the XAML snippet, make sure that the DataContext is set to an instance of the ViewModel class.• The ViewModel class exposes an AddCommand property of type AddItemCommand• The ViewModel is responsible for actually adding a new item

Commands

<Button Command="{Binding AddCommand}" CommandParameter="Untitled" Content="Button" HorizontalAlignment="Center" VerticalAlignment="Center"/>

class AddItemCommand : ICommand{ ViewModel _viewModel; public AddItemCommand(ViewModel viewModel) { _viewModel = viewModel; } public event EventHandler CanExecuteChanged; public bool CanExecute(object parameter) { return true; }  public void Execute(object title) { _viewModel.AddItem(title as string); }}

Page 133: 2 - Xaml, Phone Controls and Navigation (9t)

133

DONG NAI UNIVERSITY OF TECHNOLOGY

4. MVVM

MVVM Benefits

• Reuse Model and View-Model code

• Test the ViewModel with unit tests

• Maintainability

• Can show design-time data in Expression Blend and the Visual Studio designer

Page 134: 2 - Xaml, Phone Controls and Navigation (9t)

134

DONG NAI UNIVERSITY OF TECHNOLOGY

4. MVVM

Demo

Page 135: 2 - Xaml, Phone Controls and Navigation (9t)

135

DONG NAI UNIVERSITY OF TECHNOLOGY

4. MVVM

MVVM Libraries

MVVM Light Caliburn Micro

http://caliburnmicro.codeplex.com/http://mvvmlight.codeplex.com/Rob EisenbergLaurent Bugnion

Page 136: 2 - Xaml, Phone Controls and Navigation (9t)

136

DONG NAI UNIVERSITY OF TECHNOLOGY

5. Navigation

5.1 Navigation between Pages

5.2 Navigation to external URIs

5.3 Navigation within Pages

Page 137: 2 - Xaml, Phone Controls and Navigation (9t)

137

DONG NAI UNIVERSITY OF TECHNOLOGY

5.1 Navigation between Pages

App.RootFrame.Navigate(new Uri("/SecondPage.xaml", UriKind.Relative));

Page 138: 2 - Xaml, Phone Controls and Navigation (9t)

138

DONG NAI UNIVERSITY OF TECHNOLOGY

5.1 Navigation between Pages

MainPage:App.RootFrame.Navigate(new Uri("/SecondPage.xaml#detail",

UriKind.Relative));

OnFragmentNavigation

SecondPage:protected override void OnFragmentNavigation(FragmentNavigationEventArgs e) { // displays "Fragment: Detail" MessageBox.Show("Fragment: " + e.Fragment); base.OnFragmentNavigation(e); }

A fragment is the part of a URI following a hash mark “#” and is typically used to specify detail within a document.

Page 139: 2 - Xaml, Phone Controls and Navigation (9t)

139

DONG NAI UNIVERSITY OF TECHNOLOGY

5.1 Navigation between Pages

OnNavigatingFrom

OnNavigatingFrom is an opportunity to prevent the user from leaving the page

protected override void OnNavigatingFrom(NavigatingCancelEventArgs e){ MessageBoxResult ret=MessageBox.Show( "You have unsaved data, do you want to exit?", "Unsaved data", MessageBoxButton.OKCancel); e.Cancel=(ret== MessageBoxResult.Cancel); base.OnNavigatingFrom(e);} MainPage

Page 140: 2 - Xaml, Phone Controls and Navigation (9t)

140

DONG NAI UNIVERSITY OF TECHNOLOGY

5.1 Navigation between Pages

OnNavigatedFromThis method is called when a page is no longer the active page in a frame. The NavigationEventArgs Content property represents the target page. This allows you to pass data from the page you’re leaving and send it to the page that is about to display.

protected override void OnNavigatedFrom(NavigationEventArgs e) { MainPage mainPage = e.Content as MainPage; if (mainPage != null) mainPage.StatusText.Text = "A message from

SecondPage OnNavigatedFrom"; base.OnNavigatedFrom(e);} SecondPage

Page 141: 2 - Xaml, Phone Controls and Navigation (9t)

141

DONG NAI UNIVERSITY OF TECHNOLOGY

5.1 Navigation between Pages

OnNavigatedTo

This method is called when a page becomes the active page in a frame

protected override void OnNavigatedTo(NavigationEventArgs e){ MessageBox.Show("Navigate to=" + e.Uri); base.OnNavigatedTo(e);}

Page 142: 2 - Xaml, Phone Controls and Navigation (9t)

142

DONG NAI UNIVERSITY OF TECHNOLOGY

5.1 Navigation between Pages

NavigationService

The NavigationService is a workhorse that tracks navigation history and provides navigation methods and events. It is kept as an instance within the Page class.

if (this.NavigationService.CanGoBack) { this.NavigationService.GoBack(); }

Page 143: 2 - Xaml, Phone Controls and Navigation (9t)

143

DONG NAI UNIVERSITY OF TECHNOLOGY

5.2 Navigation to external URIs

WebBrowserTask Task = new WebBrowserTask();

Task.Uri = new Uri("http://gooogle.com");Task.Show();

Or using WebBrower Control

browser.Navigate(new Uri("http://google.com"));

Page 144: 2 - Xaml, Phone Controls and Navigation (9t)

144

DONG NAI UNIVERSITY OF TECHNOLOGY

5.3 Navigation within Pages

Pivot and Panorama controls are used to navigate within a page and can be used in favor of tabbed interfaces.

Please Reading more: http://msdn.microsoft.com/en-us/library/windowsphone/develop/ff941104(v=vs.105).aspx

Page 145: 2 - Xaml, Phone Controls and Navigation (9t)

145

DONG NAI UNIVERSITY OF TECHNOLOGY

END