Upload
neversayloveyou
View
15
Download
4
Embed Size (px)
DESCRIPTION
2 - Xaml, Phone Controls and Navigation (9t)
Citation preview
1
DONG NAI UNIVERSITY OF TECHNOLOGY
5. Navigation
3. Data binding
1. Building The UI with XAML
4. MVVM
2. Phone controls
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
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
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>
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
6
DONG NAI UNIVERSITY OF TECHNOLOGY
1.1 Working with XAML
XAML Namespace syntax declare
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;
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"ệ />
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
10
DONG NAI UNIVERSITY OF TECHNOLOGY
1.1 Working with XAML
Syntax for Attribute
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
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
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.
14
DONG NAI UNIVERSITY OF TECHNOLOGY
1.1 Working with XAML Syntax for Attribute
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}" />
16
DONG NAI UNIVERSITY OF TECHNOLOGY
1.2 Using with Brush
Brush
SolidColorBrush GradientBrush TileBrush
LinearGradientBrush RadialGradientBrush
17
DONG NAI UNIVERSITY OF TECHNOLOGY
1.2 Using with Brush
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;
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
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;
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
22
DONG NAI UNIVERSITY OF TECHNOLOGY
1.2 Using with Brush
RadialGradientBrush
RadialGradientBrush br = new RadialGradientBrush(Colors.Red,Colors.Blue);button1.Background = br;
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;
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
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>
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;
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}" />
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
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
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"/>
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
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"/>
33
DONG NAI UNIVERSITY OF TECHNOLOGY
1.3 Resources and Style
Style Inheritance
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
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" />
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
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.
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>
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:
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>
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"
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
43
DONG NAI UNIVERSITY OF TECHNOLOGY
1.1 Layout Controls
WrapPanel
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:
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
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>
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
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>
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>
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>
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>
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>
53
DONG NAI UNIVERSITY OF TECHNOLOGY
1.1 Layout Controls
ScrollViewer
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>
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>
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);
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);
}
58
DONG NAI UNIVERSITY OF TECHNOLOGY
1.2 Button & TextBlock Controls
Class Diagram of Button Classes
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();}
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>
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);}
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()
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." />
64
DONG NAI UNIVERSITY OF TECHNOLOGY
1.3 Input Controls
TextBox
Input Keyboards
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
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.
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>
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" };
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; } }
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";
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" />
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.
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.
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>
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ì đó }}
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) { }
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#"/>
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
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
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
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
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
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.
84
DONG NAI UNIVERSITY OF TECHNOLOGY
1.5 List Controls
Grouping
http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj244365(v=vs.105).aspx
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; } }
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>
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>
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(); }
89
DONG NAI UNIVERSITY OF TECHNOLOGY
1.5 List Controls
Grouping Complex Objects
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>
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 }
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.
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.
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>
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) {
}
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.
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>
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" />
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.
100
DONG NAI UNIVERSITY OF TECHNOLOGY
1.7 Media Controls
MediaElement
<MediaElement Source="/Assets/phim.wmv" AutoPlay="True" VerticalAlignment="Stretch" HorizontalAlignment="Stretch"/>
101
DONG NAI UNIVERSITY OF TECHNOLOGY
1.7 Media Controls
MediaElement Closed Opening Buffering Playing Stopped Individualizing AquiringLicense
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));}
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(); }
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.
DONG NAI UNIVERSITY OF TECHNOLOGY
105
1.7 Media Controls
MultiScaleImage
Deep Zoom "Pyramid"
http://blogs.msdn.com/b/jaimer/archive/2008/06/23/working-with-collections-in-deep-zoom.aspx
http://msdn.microsoft.com/en-us/library/system.windows.controls.multiscaleimage(v=vs.95).aspx
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.
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; }
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>
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) { }
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
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.
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.
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"
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>
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" />
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);
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; } }}
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" }); } }}
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>
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>
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>
122
DONG NAI UNIVERSITY OF TECHNOLOGY
4. MVVM
123
DONG NAI UNIVERSITY OF TECHNOLOGY
4. MVVM
Model-View-ViewModel
View
ViewModelCommands
Data Binding
Model
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; }}
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)); } }}
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"); }}
127
DONG NAI UNIVERSITY OF TECHNOLOGY
4. MVVM
Why MVVM?
View
<TextBox Text="{Binding SampleProperty, Mode=TwoWay}" />
128
DONG NAI UNIVERSITY OF TECHNOLOGY
4. MVVM
Why MVVM?
View
<phone:LongListSelector ItemsSource="{Binding MyListOfItems}" SelectedItem="{Binding MySelectedItem, Mode=TwoWay}" />
129
DONG NAI UNIVERSITY OF TECHNOLOGY
4. MVVM
Model-View-ViewModel
View
ViewModelCommands
Data Binding
Model
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}"/>
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)); } }
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); }}
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
134
DONG NAI UNIVERSITY OF TECHNOLOGY
4. MVVM
Demo
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
136
DONG NAI UNIVERSITY OF TECHNOLOGY
5. Navigation
5.1 Navigation between Pages
5.2 Navigation to external URIs
5.3 Navigation within Pages
137
DONG NAI UNIVERSITY OF TECHNOLOGY
5.1 Navigation between Pages
App.RootFrame.Navigate(new Uri("/SecondPage.xaml", UriKind.Relative));
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.
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
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
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);}
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(); }
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"));
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
145
DONG NAI UNIVERSITY OF TECHNOLOGY
END