HO CHI MINH UNIVERSITY OF INDUSTRY
What's New in WPF Version 4.5?
HO CHI MINH UNIVERSITY OF INDUSTRY
Windows Presentation Foundation1
Benefits2
Tools3
Discussion of WPF applicability4
HO CHI MINH UNIVERSITY OF INDUSTRY
What is WPF? WPF is a new API for building Windows applications
The goal of Windows Presentation Foundation (WPF) is to provide these advances for Windows. Included in version 4.0 of the Microsoft .NET Framework, WPF allows building interfaces that incorporate documents, media, two- and three-dimensional graphics, animations, Web-like characteristics, and much more.
HO CHI MINH UNIVERSITY OF INDUSTRY
What Windows Presentation Foundation Provides?
Three most important: a unified platform for modern user interfaces the ability for developers and designers to
work together, and a common technology for Windows and
Web browser user interfaces.
HO CHI MINH UNIVERSITY OF INDUSTRY
What is WPF good for?To enable designers and developers to work
together To allow an easy way to customize the look
of controls without changing its behavior To allow 3D graphics more easily in
Windows applications To allow an easy way to do animations in
Windows applications To enable the creation of applications which
scale nicely to high resolution screens
HO CHI MINH UNIVERSITY OF INDUSTRY
Which of these UI have you worked with?
GDI (20 years), GDI+, WinForms DirectX (11 years), Direct3D Quartz, DirectShow (8 years) – Problems:
• Showing their age • Each API is different • Mixing APIs is challenging
HO CHI MINH UNIVERSITY OF INDUSTRY
Next Gen
WPF – replaces GDI Direct3D – large games, used by WPF Media Foundation – ultimately will replace
DirectShow MCML –markup language for Media
Center Edition applications XNA – small games
HO CHI MINH UNIVERSITY OF INDUSTRY
WPFDeclarative programming with XAML markup For Designers and Developers Rewritten from scratch
– Built on top of Direct3D – Hardware accelerated – Vector based – Resolution independent (1/96 inch) – Retained graphics
HO CHI MINH UNIVERSITY OF INDUSTRY
Overview of WPF Architecture
Most of WPF is written in managed code
milcore is the only unmanaged component of WPF
HO CHI MINH UNIVERSITY OF INDUSTRY
XAML: Extensible Application Markup Language Declarative object instantiation Not exclusive to WPF Separates UI and logic
– Common language for Designers and Developers • Demo: Blend and VS
– Parallel development – Localization, Branding – Targeted UI (devices, users, …)
Tool support Supports C# and VB.NET
HO CHI MINH UNIVERSITY OF INDUSTRY
Benefits
Markup/code-behind model (like ASP.NET) Excellent layout options and text flow features Access to powerful graphics hardware Certain otherwise-impossible effects are
made easy (skewing and rotating textboxes, etc.)
HO CHI MINH UNIVERSITY OF INDUSTRY
Tools• Cider • XAML Pad • 3D tools such as Light wave can generate XAML. – Electric Rain Zam 3D – Mobiform Aurora – Cinema 4D • Microsoft Expression – Graphics Designer – Interactive Designer
HO CHI MINH UNIVERSITY OF INDUSTRY
Comparisons: WPF vs. DirectX and GDI+
HO CHI MINH UNIVERSITY OF INDUSTRY
WPF Build Pipeline
HO CHI MINH UNIVERSITY OF INDUSTRY
Basic topics in WPF
WPF code and XAML Property & object in XAML: syntax Layout Basic control Basic property WPF Concepts
HO CHI MINH UNIVERSITY OF INDUSTRY
1. WPF code and XAML: first appWPF code – New consoles project (or Windows Apps) – Reference: PresentationCore, PresentationFramework, and WindowsBase
How to create this window?
HO CHI MINH UNIVERSITY OF INDUSTRYusing System.Windows;using System.Windows.Controls;namespace StudyWPFApplication{ public class Class1 { [STAThread]//Must insert before Main public static void Main(string[] aargs){ Window w = new Window(); Button btn = new Button(); btn.Width = btn.Height = 100; btn.Content = "Click Me!"; w.Content = btn; w.Title = "Khoa Công Nghệ Thông Tin"; Application A = new Application(); A.Run(w);} }}
HO CHI MINH UNIVERSITY OF INDUSTRY
1. WPF code and XAML: first app From VS template
App is inherited from Application
Window1 is inherited from Window
HO CHI MINH UNIVERSITY OF INDUSTRY
HO CHI MINH UNIVERSITY OF INDUSTRY1. WPF code and XAML: first app From VS template Write 2 example: code and Xaml
HO CHI MINH UNIVERSITY OF INDUSTRY1. WPF code and XAML: first app From VS template Write 2 example: code and Xaml
HO CHI MINH UNIVERSITY OF INDUSTRY
2. Basic Window properties
Title WindowStyle Content Foreground Background
Brush
SolidColorBrush GradientBrush TileBrush
LinearGradientBrush RadialGradientBrush
HO CHI MINH UNIVERSITY OF INDUSTRY
HO CHI MINH UNIVERSITY OF INDUSTRY
using System.Windows.MediaSolidColorBrush
Color cr = new Color();cr.B = cr.R = cr.G = 122;cr.A = 255;
SolidColorBrush br = new SolidColorBrush(cr);button1.Background = br;
HO CHI MINH UNIVERSITY OF INDUSTRY
SolidColorBrush
SolidColorBrush brush=new SolidColorBrush(Colors.Red);rect1.Fill = brush;
XAML CODE
HO CHI MINH UNIVERSITY OF INDUSTRY
SolidColorBrush
XAML
HO CHI MINH UNIVERSITY OF INDUSTRY
GradientBrush
HO CHI MINH UNIVERSITY OF INDUSTRY
LinearGradientBrushPoint p1 = new Point(0, 0); Point p2 = new Point(1, 1); LinearGradientBrush br = new LinearGradientBrush (Colors.Red,Colors.White, p1, p2);rect1.Fill = br;
HO CHI MINH UNIVERSITY OF INDUSTRY
LinearGradientBrushLinearGradientBrush br = new
LinearGradientBrush();br.GradientStops.Add(
new GradientStop(Colors.Yellow, 0.0));br.GradientStops.Add(
new GradientStop(Colors.Orange, 0.5));br.GradientStops.Add(
new GradientStop(Colors.Red, 1.0));rect1.Fill = br;
HO CHI MINH UNIVERSITY OF INDUSTRY
LinearGradientBrush
XAML
HO CHI MINH UNIVERSITY OF INDUSTRY
RadialGradientBrush
RadialGradientBrush br = newRadialGradientBrush(Colors.Blue,Colors.White);
HO CHI MINH UNIVERSITY OF INDUSTRY
RadialGradientBrush
RadialGradientBrush br = new RadialGradientBrush(Colors.Blue,Colors.Yellow);rect1.Fill = br;
HO CHI MINH UNIVERSITY OF INDUSTRY
RadialGradientBrush br = new RadialGradientBrush();br.GradientOrigin = new Point(0.75, 0.25);br.GradientStops.Add(
new GradientStop(Colors.Yellow, 0.0));br.GradientStops.Add(
new GradientStop(Colors.Orange, 0.5));br.GradientStops.Add(
new GradientStop(Colors.Blue, 1.0));rect1.Fill = br;
RadialGradientBrush
HO CHI MINH UNIVERSITY OF INDUSTRY
XAML
RadialGradientBrush
HO CHI MINH UNIVERSITY OF INDUSTRY
ImageBrush myBrush = new ImageBrush();myBrush.ImageSource =new BitmapImage( new Uri(@"E:\Pictures\IC151762.jpg", UriKind.Relative));rect1.Fill = myBrush;
ImageBrush
HO CHI MINH UNIVERSITY OF INDUSTRY
Config Brush from VS design
HO CHI MINH UNIVERSITY OF INDUSTRY
2. Handling Application Events
From Code
HO CHI MINH UNIVERSITY OF INDUSTRY
2. Handling Application Events
From XAML
HO CHI MINH UNIVERSITY OF INDUSTRY
2.Code-Behind and Object Names
<Button Name="myButton">Hello</Button>
Classes have a Name property
Classes don’t have a Name property
<Button x:Name="myButton">Hello</Button>
HO CHI MINH UNIVERSITY OF INDUSTRY
2. Logical Trees and Visual TreesLogical tree comprises the elements
as they are listed in the XAML. These include panels and controls you will generally use.
Visual tree includes the parts that make up the controls and panels.
HO CHI MINH UNIVERSITY OF INDUSTRY
HO CHI MINH UNIVERSITY OF INDUSTRY
2.Top-Level Elements
Three classes are used by WPF programs as top-level elements
– Application – Page – Window
• Only one Content
HO CHI MINH UNIVERSITY OF INDUSTRY
3. Syntax for Object
One element
Empty element tag
HO CHI MINH UNIVERSITY OF INDUSTRY
3. Syntax for ObjectNested- Multi elements
Logical tree with four WFP objects
XAML Tree With Four Elements
HO CHI MINH UNIVERSITY OF INDUSTRY
3. Syntax for Attribute
Object element syntax – Like object syntax • <button> FIT HUI </button>
Attribute syntax Property Element Syntax Attached Property Syntax
HO CHI MINH UNIVERSITY OF INDUSTRY
3. Syntax for Attribute
HO CHI MINH UNIVERSITY OF INDUSTRY
3. 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
HO CHI MINH UNIVERSITY OF INDUSTRY
<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>
3. Syntax for AttributeProperty Element Syntax
HO CHI MINH UNIVERSITY OF INDUSTRY
3. Syntax for AttributeAttached Property Syntax – Attached properties are a special type of property that is defined in one class but used in another.
HO CHI MINH UNIVERSITY OF INDUSTRY
3. Syntax for AttributeReviewing the XAML Syntax
HO CHI MINH UNIVERSITY OF INDUSTRY<Window> <StackPanel > <StackPanel.Background> <RadialGradientBrush> <GradientStop Color="Black" Offset="0" /> <GradientStop Color="#FF56933A" Offset="1" /> <GradientStop Color="#FF2B2B2B" Offset="0.169" /> </RadialGradientBrush> </StackPanel.Background> <Grid Height="141" Name="grid1" Width="260"> <Grid.RowDefinitions> <RowDefinition Height="61*" /> <RowDefinition Height="80*" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="118*" /> <ColumnDefinition Width="142*" /> </Grid.ColumnDefinitions> <TextBlock Grid.RowSpan="2" Height="23" /> <Button Content="Button" Grid.Row="1"> <Button.BorderBrush> <LinearGradientBrush EndPoint="1,0.5" StartPoint="0,0.5"> <GradientStop Color="Black" Offset="0" /> <GradientStop Color="#FFB44E4E" Offset="1" /> </LinearGradientBrush> </Button.BorderBrush> </Button> <CheckBox Content="CheckBox" Grid.Column="1" Grid.Row="1" /> </Grid> </StackPanel></Window>
4. Example
HO CHI MINH UNIVERSITY OF INDUSTRY
5. XAML NamespaceTo create objects of these types, the XAML
parser must know where to find their definitions
HO CHI MINH UNIVERSITY OF INDUSTRY
5. XAML Namespace
HO CHI MINH UNIVERSITY OF INDUSTRY
5. XAML Namespace: Classes from Other Namespaces
HO CHI MINH UNIVERSITY OF INDUSTRY
using System;using System.Windows;using System.Windows.Controls;using System.Windows.Media;namespace StudyWPFApplication{ public class MyButton:Button{ public MyButton(){ Background = new LinearGradientBrush( Colors.Yellow,Colors.Blue,
new Point(0,0),new Point(1,1)); } }}
Create MyButton extend from class Button
HO CHI MINH UNIVERSITY OF INDUSTRY
xmlns:local="clr-namespace:StudyWPFApplication"
Declare prefix:
In XAML
<local:MyButton Content="Hello" ></local:MyButton>
Instantiate the button:
HO CHI MINH UNIVERSITY OF INDUSTRY
5. Markup Extensionhook to a class outside the XAML class designed to be used by a markup extension is
called an extension class xmlns:local="clr-namespace:StudyWPFApplication"
using System;using System.Windows.Markup;namespace StudyWPFApplication{public class MyMarkupExtension:MarkupExtension{public MyMarkupExtension() { }public override object ProvideValue
(IServiceProvider serviceProvider) { return DateTime.Now.ToShortDateString(); } }}
<TextBox Name="txt" Text="{local:MyMarkupExtension}"/>
HO CHI MINH UNIVERSITY OF INDUSTRY
6. Layout: Layout in WPFBefore WPF, user interfaces generally
consisted of windows with statically placed controls.
WPF: layout systemconsist of one or more panels that contain
visual elements
HO CHI MINH UNIVERSITY OF INDUSTRY
Layout in Windows From Control have fix coordinates: X,Y Dock, Anchor Using FlowLayoutPanel to arrange
controls in a flow panel Using TableLaoutPanel to arrange
controls in table format
6. Layout Basic Principle
HO CHI MINH UNIVERSITY OF INDUSTRY
6. Layout Basic Principle
XAML Layout Flow-based layout
• Support coordinate Contain is organizaed into containers Resolution and size independent interfaces Automatically adjust if screen resolution
changes
HO CHI MINH UNIVERSITY OF INDUSTRY
6. Layout in WPFLayout in WPF
Alignment Padding and Margins
Containers (Panels) StackPanel WrapPanel DockPanel Grid Canvas UniformGrid
HO CHI MINH UNIVERSITY OF INDUSTRY
6. XAML Layout: Align & Padding
Alignment describes how child elements should be posisioned within parent’s space HorizontalAlignment: Left, Center, Right,
or Stretch VerticalAlignment: Top, Center, Bottom, or
Stretch
HO CHI MINH UNIVERSITY OF INDUSTRY
Margin Distance between an elenment and its
child or peers Left, top, right, bottom, or uniform
(Margin=“5”) Padding
Enlarges a child element by specified thickness
6. XAML Layout: Align & Padding
HO CHI MINH UNIVERSITY OF INDUSTRY
6. XAML Layout: Align & Padding
HO CHI MINH UNIVERSITY OF INDUSTRY
6. Layout Panels Canvas
for specific (X,Y) positioning
HO CHI MINH UNIVERSITY OF INDUSTRY
6. Layout Panels StackPanelArranges content either horizontally or
vertically
HO CHI MINH UNIVERSITY OF INDUSTRY
6. Layout Panels WrapPanel
Arranges item sequentially
HO CHI MINH UNIVERSITY OF INDUSTRY
6. Layout Panels DockPanelAnchor elements to the edges of the
container
HO CHI MINH UNIVERSITY OF INDUSTRY6. Layout Panels GridTable-style layout of rows and columns
HO CHI MINH UNIVERSITY OF INDUSTRY6. Layout Panels UniformGrid
All rows and columns are the same size Contains two properties, Rows and Columns
HO CHI MINH UNIVERSITY OF INDUSTRY
Types of ContainersBasic controls Resource Style Control template Binding Graphic element
HO CHI MINH UNIVERSITY OF INDUSTRY
Types of Containers
HO CHI MINH UNIVERSITY OF INDUSTRY Types of Containers : ExampleSingle item
Collection items
Single item and Collection items
<Button>Click me</Button>
<ListBox> <ListBoxItem>a</ListBoxItem> <ListBoxItem>b</ListBoxItem>
<TextBox>FIT HUI</TextBox> <Button>Click me</Button></ListBox>
<ListBox > <ListBoxItem>a</ListBoxItem> <ListBoxItem>b</ListBoxItem> <ListBoxItem>c</ListBoxItem></ListBox>
HO CHI MINH UNIVERSITY OF INDUSTRY
7. Basic controls
Simplest controls Border CheckBox Button RadioButton
More controls
HO CHI MINH UNIVERSITY OF INDUSTRY
7.1 Border control
Container control can contains controls Without border using Border control
Accept single child control Display border around child control Property
Backgound : Brush BorderBrush BorderThickness CornerRadius
HO CHI MINH UNIVERSITY OF INDUSTRY
<Border Margin="20,20,20,20" BorderBrush="Blue" BorderThickness="1,1,2,2" CornerRadius="20" Height="88"
Background="WhiteSmoke"> <Button Height="32" Width="76">Border</Button></Border>
7.1 Border control
How to make border???
HO CHI MINH UNIVERSITY OF INDUSTRY
7.1 RadioButton -CheckBox
<StackPanel> <RadioButton GroupName="Os" Content="Windows 7" IsChecked="True"/> <RadioButton GroupName="Os" Content="Windows 8" /> <RadioButton GroupName="Office" Content="Microsoft Office 2010" IsChecked="True"/> <RadioButton GroupName="Office" Content="Open Office"/></StackPanel>
RadioButton Properties GroupName IsChecked
HO CHI MINH UNIVERSITY OF INDUSTRY
7.1 RadioButton -CheckBox Checkbox Properties
IsChecked <Border Margin="20,20,20,20" BorderBrush="Red" BorderThickness="1,1,2,2" CornerRadius="25" Height="88" Background="Lavender"> <StackPanel> <CheckBox IsChecked="True" Content="RấRt Hài Lòng" Height="21" Width="145"></CheckBox> <CheckBox Content="Hài Lòng" Height="21" Width="145"></CheckBox> <CheckBox Content="Tạm ChấRp Nhận" Height="21" Width="145"></CheckBox> <CheckBox Content="Không ChấRp Nhận" Height="21" Width="145"></CheckBox> </StackPanel></Border>
HO CHI MINH UNIVERSITY OF INDUSTRY
7.1 Basic Controls: Text, date, miscText entry controls
TextBlock, Label, Textbox, PasswordBox • View – edit text TextBlock vs Label
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>FIT <LineBreak/>HUI <Run Background="Blue" FontSize="20" Foreground="red"> Hello. </Run> H.a.you?</TextBlock>
HO CHI MINH UNIVERSITY OF INDUSTRY
7.1 Basic Controls: Text, date, misc
How to fill background for result text???
And How to change font style when mouse down???
HO CHI MINH UNIVERSITY OF INDUSTRY
7.1 Basic Controls: LabelLabel: target, underscore _, content When you want to display text by itself use
the TextBlock. The benefit is a light, performant way to display text.
When you want to associate text with another control like a TextBox use the Label control. The benefits are access keys and references to target control.
HO CHI MINH UNIVERSITY OF INDUSTRY
7.1 Basic Controls: LabelLabel: target, underscore _, content <StackPanel> <Label Target="txta">Nhập _a</Label> <TextBox Name="txta"></TextBox> <Label Target="{Binding
ElementName=txtb, Mode=Default}">Nhập _b</Label>
<TextBox Name="txtb"></TextBox> </StackPanel>
HO CHI MINH UNIVERSITY OF INDUSTRY
7.1 Basic Controls: Textbox controlProperties
TextWrapping AccepsReturn IsEnabled ReadOnly VerticalScrollbarVisibility,
HortizontalScrollbarVisibility SpellCheck.IsEnabled (Language)
Events – KeyDown, KeyUp, TextChanged
HO CHI MINH UNIVERSITY OF INDUSTRY
7.1 Basic Controls: Textbox control Examples
<TextBox
VerticalScrollBarVisibility="Visible" TextWrapping="Wrap" Margin="0,0,0,0" SpellCheck.IsEnabled="True"AcceptsReturn="True" Text="FIT
HUI" Height="41" Width="276">
</TextBox>
HO CHI MINH UNIVERSITY OF INDUSTRY
7.1 Basic Controls: Passwordbox
Like Textbox Property: PasswordChar No Text property, rereive Password Do not support clipboard
<PasswordBox Name="txtPassword" ToolTip="Password" PasswordChar="*" Height="30" Width="224" />
HO CHI MINH UNIVERSITY OF INDUSTRY
7.1 Date control: Calendar controlTag <Calendar> SelectionMode: select single day, range
date.. DiplayMode: Month, Year, Decade BlackOutDates : set black out dates DisplayDateStart, DisplayDateEnd: range
of available dates
HO CHI MINH UNIVERSITY OF INDUSTRY
7.1 Date control: Calendar control
<Calendar DisplayDateStart="2012-01-1" DisplayDateEnd="2012-1-30"> <Calendar.BlackoutDates> <CalendarDateRange Start="2012-1-5" End="2012-1-10"/> </Calendar.BlackoutDates></Calendar>
HO CHI MINH UNIVERSITY OF INDUSTRY
7.1 Date control: DatePicker control
Allow to select a single date using dropdown calendar
IsDropDownOpen SelectedDateFormat, BlackOutDates,
DisplayDateStart, DisplayDateEnd SelectedDateChanged event
HO CHI MINH UNIVERSITY OF INDUSTRY
7.1 Date control: DatePicker control<DatePicker DisplayDateStart="2012-1-1"
DisplayDateEnd="2012-1-31" SelectedDate="2012-1-15">
<DatePicker.BlackoutDates> <CalendarDateRange
Start="1/1/2012" End="1/5/2012" />
</DatePicker.BlackoutDates></DatePicker>
HO CHI MINH UNIVERSITY OF INDUSTRY
7.1 Miscellaneous controlSlider, ProgressBar, MediaElement Slider Minimum, Maximum, Orientation, Value,
SmallChange, LargeChange, IsDerectionReversed ProgressBar Minimun, Maximun Change Value, or using IsInDeterminate property Check out
System.Windows.Threading.DispatcherTimer to run code at regular intervals • Demo
Image Source Stretch
HO CHI MINH UNIVERSITY OF INDUSTRY
7.1 Miscellaneous control <StackPanel> <Slider Minimum="0" Maximum="10" Value="5"></Slider> <ProgressBar Minimum="0" Maximum="100" Name="prb" Height="20"/> <Image Source="E:\Pictures\a.jpg" Height="120.83" Stretch="Fill" Width="129.846" /> <Button Click="btn_Click" >Demo progressbar</Button> <Button Click="btn1_Click" >Demo gressbar – IsInDetermine</Button></StackPanel>
XAML
HO CHI MINH UNIVERSITY OF INDUSTRY
7.1 Miscellaneous control
System.Windows.Threading.DispatcherTimer timer;private void btn_Click(object sender, RoutedEventArgs e) { timer=new System.Windows.Threading.DispatcherTimer(); timer.Tick += new EventHandler(my_tick); timer.Interval = new TimeSpan(0, 0, 1); timer.Start(); }public void my_tick(object sender, EventArgs e) { if (prb.Value >= prb.Maximum) timer.Stop(); prb.Value += 1;} Example code 1
HO CHI MINH UNIVERSITY OF INDUSTRY
7.1 Miscellaneous control
Example code 2
private void btn_Click(object sender, RoutedEventArgs e)
{System.Windows.Threading.DispatcherTimer timer = new System.Windows.Threading.DispatcherTimer();timer.Tick += delegate { if (prb.Value >= prb.Maximum) timer.Stop(); prb.Value += 10; };timer.Interval = new TimeSpan(0, 0, 1);//h,m,stimer.Start();}
HO CHI MINH UNIVERSITY OF INDUSTRY
7.1 Miscellaneous controlMediaElement
Display media Souce property: URI LoadedBehavior="Manual“ for using
control methods IsMuted Position, Volume Call Play, Pause, Stop methods Invisible until playing video file
HO CHI MINH UNIVERSITY OF INDUSTRY
<Window …> <StackPanel> <MediaElement Source="music.mp3"/> </StackPanel> </Window>
This program loads the media file and immediately starts playing it.
7.1 Miscellaneous controlMediaElement
Example 1
HO CHI MINH UNIVERSITY OF INDUSTRY
<StackPanel> <MediaElement Name="player" LoadedBehavior="Manual" /> <StackPanel Orientation="Horizontal"
VerticalAlignment="Top"> <Button Click="Play_Click" Margin="3" Padding="6,3">Play</Button> <Button Click="Pause_Click" Margin="3" Padding="6,3">Pause</Button> <Button Click="Stop_Click" Margin="3" Padding="6,3">Stop</Button> </StackPanel></StackPanel>
7.1 Miscellaneous control
Example 2 - XAML
HO CHI MINH UNIVERSITY OF INDUSTRY
7.1 Miscellaneous control
Example 2 - Code
public partial class SampleMediaElement : Window { public SampleMediaElement() { InitializeComponent();
player.Source = new Uri(@"Hello.mp3"); }
private void Play_Click(object sender, RoutedEventArgs e) {
player.Play(); }
private void Pause_Click(object sender, RoutedEventArgs e) {
player.Pause(); }
private void Stop_Click(object sender, RoutedEventArgs e) {
player.Stop(); } }
HO CHI MINH UNIVERSITY OF INDUSTRY
7.2 List controls Listbox/Combobox Are container elements: <ListBoxItem> SelectedIndex SelectedItem (return element type) SelectionChanged event (Listbox) SelectionMode: single,
expand… Can contains others control: textbox,
image…
HO CHI MINH UNIVERSITY OF INDUSTRY
7.2 List controls Example <ListBox Name="lst" Width="374"> <ListBoxItem>a</ListBoxItem> <ListBoxItem>b</ListBoxItem> <ListBoxItem>c</ListBoxItem> <TextBox>Hello</TextBox> <Button>Button here</Button> <StackPanel Orientation="Horizontal"> <Image Width="71" Height="84"
Source="E:\a.jpg" Stretch="Fill"> </Image> <Label Background="Wheat">Hình nè</Label> </StackPanel></ListBox>
HO CHI MINH UNIVERSITY OF INDUSTRY
7.3 TreeView
Contains TreeViewItems TreeViewItem
– Header – Tag
SelectedItemChanged event: when select node
Can contain image, text Demo: item with text & image
HO CHI MINH UNIVERSITY OF INDUSTRY
7.3 TreeView
HO CHI MINH UNIVERSITY OF INDUSTRY
7.3 TreeView
HO CHI MINH UNIVERSITY OF INDUSTRY
7.4 Menu
Place everywhere you want Use Grid of DockPanel Set IsMainMenu = true when Top level menu MenuItem
• Container control • Header property • Icon property • Click event
HO CHI MINH UNIVERSITY OF INDUSTRY
7.4 Menu<StackPanel Margin="0" > <Menu Name="cm"> <MenuItem Header="File"> <MenuItem Header="open"/> <MenuItem Header="exit"/> <MenuItem Header="Last open"> <MenuItem Header="file1" IsCheckable="True"/> <MenuItem Header="file2" IsCheckable="True"/> </MenuItem> </MenuItem> </Menu></StackPanel>
HO CHI MINH UNIVERSITY OF INDUSTRY
7.5 Context Menu : ContextMenu property<Button>Button with Context menu <Button.ContextMenu> <ContextMenu Name="cmd"> <MenuItem Header="Copy" > <MenuItem.Icon> <Image Source="copy.png"></Image> </MenuItem.Icon> </MenuItem> <MenuItem Header="Paste" > <MenuItem.Icon> <Image Source="paste.png"></Image> </MenuItem.Icon> </MenuItem> </ContextMenu> </Button.ContextMenu></Button>
HO CHI MINH UNIVERSITY OF INDUSTRY
7.6 ScrollViewer
Contain control with both horizontal and vertical bars built-in
Use it when content may not fir a window and you want to enable scrolling (example: StackPanel)
VerticalScrollBar and HorizontalScrollBar – Auto: scroll bar auto apprear
HO CHI MINH UNIVERSITY OF INDUSTRY
7.6 ScrollViewer
HO CHI MINH UNIVERSITY OF INDUSTRY
7.6 ScrollViewer
<ScrollViewer
HorizontalScrollBarVisibility="Auto" Width="800" Height="500"> <StackPanel VerticalAlignment="Top"
HorizontalAlignment="Left" > <Image Source="baby1.jpg" /> <Image Source="bird1.jpg" /> </StackPanel></ScrollViewer>
HO CHI MINH UNIVERSITY OF INDUSTRY
7.7 TabControl and TabItemSeparate pages TabItem – Header property
<TabControl> <TabItem Header="tabpage 1"> <Button>Tab 1 nè</Button> </TabItem> <TabItem Header="tabpage 2"> <WrapPanel> <Button>Tab 2 nè</Button> <TextBlock>Thô�ng tin ở đay</TextBlock> </WrapPanel> </TabItem></TabControl>
HO CHI MINH UNIVERSITY OF INDUSTRY
7.8 GroupBoxHeader property Common: contains checkbox, radio buttons.
<GroupBox Header="Student information" BorderBrush="Red" BorderThickness="2"> <StackPanel> <WrapPanel> <TextBlock Width="90">Student ID:</TextBlock> <TextBox Width="150"></TextBox> <TextBlock Width="90">Student Name:</TextBlock> <TextBox Width="150"></TextBox> </WrapPanel> </StackPanel></GroupBox>
HO CHI MINH UNIVERSITY OF INDUSTRY
7.9 Expander controlHeader and collapsible content region Expanded and Collapsed events ExpandDirection property:
Down, up, left, right
<Expander Header="expander FIT HUI example"
ExpandDirection="Down"> <TabControl> <TabItem Header="tabpage1"> <Button>Hello</Button> </TabItem> </TabControl></Expander>
HO CHI MINH UNIVERSITY OF INDUSTRY
8. ResourcesType of resouces Assembly resources (binary resources) • compiled into the binary • Example: image, icon… • Resource—not Embedded Resource Logical resources (object resources,
XAML resources) • associated with XAML markup
HO CHI MINH UNIVERSITY OF INDUSTRY<StackPanel Name="sp"> <TextBlock FontFamily="Arial Black" Margin="7">
Some Buttons</TextBlock> <Button Height="40" Name="btn1" FontWeight="Bold"> <Button.Background>← Defining the Background <LinearGradientBrush StartPoint="0, 0" EndPoint="1,1"> <GradientStop Color="White" Offset="0" /> <GradientStop Color="Blue" Offset="1"/> </LinearGradientBrush> </Button.Background> Button 1 </Button> <Button Height="40" Name="btn2" FontWeight="Bold"> <Button.Background>← Defining the Background Again <LinearGradientBrush StartPoint="0, 0" EndPoint="1,1"> <GradientStop Color="White" Offset="0" /> <GradientStop Color="Blue" Offset="1"/> </LinearGradientBrush> </Button.Background> Button 2 </Button></StackPanel>
Why ???
HO CHI MINH UNIVERSITY OF INDUSTRY
Resources store reference to an object within a collection
most objects in the WPF framework have a Resources collection: Application, Window, Button, …
A resource can be anything: Brush, a control template …
Find resource: navigates up
8. Resources
HO CHI MINH UNIVERSITY OF INDUSTRY
<Window …><Window.Resources> <RadialGradientBrush x:Key="btnbrush"> <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></Window.Resources><Button Background="{DynamicResource ResourceKey=btnbrush}" Width="100" Height="100"></Button></Window>
8. Resources: Example
HO CHI MINH UNIVERSITY OF INDUSTRY
8. Resources: Example StaticResource vs DynamicResource
Static resources are resolved at compile time, whereas dynamic resources are resolved at runtime.
Use DynamicResources when the value of the resource could change during the lifetime of the Application.
Use StaticResources when it’s clear that you don’t need your resource re-evaluated when fetching it – static resources perform better than dynamic resources.
HO CHI MINH UNIVERSITY OF INDUSTRY
8. Resources: Visual Tree DynamicBackground="{DynamicResource ResourceKey=keyBrush}"
HO CHI MINH UNIVERSITY OF INDUSTRY
8. Resources: Visual Tree StaticBackground="{StaticResource ResourceKey=gradBrush}"
HO CHI MINH UNIVERSITY OF INDUSTRY
8. Resources dictionaryStored in a central place (file) Is a collection of resources that can be
easily incorporated into an application Can be used to contain a single reference
to all the assemblies in a single or multiple applications better for re_using
Example in next slide
HO CHI MINH UNIVERSITY OF INDUSTRY
<ResourceDictionary …> <LinearGradientBrush x:Key="btnbrush"> <GradientStop Color="AliceBlue" Offset="0" /> <GradientStop Color="Blue" Offset=".7" /> </LinearGradientBrush></ResourceDictionary>
Dictionary2.xaml
<Window.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="Dictionary2.xaml"/> </ResourceDictionary.MergedDictionaries> </ResourceDictionary></Window.Resources><Button Background="{DynamicResource ResourceKey= btnbrush}" Width="100" Height="50">Hello</Button>
Using Dictionary2.xaml
HO CHI MINH UNIVERSITY OF INDUSTRY
9. Stylegroup 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
HO CHI MINH UNIVERSITY OF INDUSTRY
Key Style Name Suffix ↓ ↓ <Style x:Key="buttonStyle"> <Setter Property="Button.Height" Value="40" /> <Setter Property="Button.Width" Value="110"/> <Setter Property="Button.FontSize" Value="16"/> <Setter Property="Button.FontWeight" Value="Bold"/> </Style> ↑ ↑ ↑ Property Setters for a Named Value Attribute Style Must Include a Attribute Class Name
9. Style: named style
<Button Style="{StaticResource buttonStyle}">Button 1</Button>
HO CHI MINH UNIVERSITY OF INDUSTRY
9. Style<Button Content="Button 1"> <Button.Style> <Style> <Setter Property="Button.Height" Value="40" /> <Setter Property="Button.Width" Value="110" /> <Setter Property="Button.FontSize" Value="16" /> <Setter Property="Button.FontWeight" Value="Bold" /> </Style> </Button.Style></Button> <Window.Resources>
<Style …> <Setter …/> <Setter …/> </Style> </Window.Resources>
HO CHI MINH UNIVERSITY OF INDUSTRY
9. Style
Declare in Resource Two ways Named styles –give the style a name when declare. Targeted styles –give the style a target type when declare. The style is then automatically applied to elements of that type.
HO CHI MINH UNIVERSITY OF INDUSTRY
9. Style: example TargetType<ResourceDictionary …> <Style TargetType="{x:Type Button}"> <Setter Property="Background"> <Setter.Value> <LinearGradientBrush StartPoint="0,0" EndPoint="0,1"> <GradientStop Color="AliceBlue" Offset="0" /> <GradientStop Color="Blue" Offset="1" /> </LinearGradientBrush> </Setter.Value> </Setter> <Setter Property="FontSize" Value="20" /> <Setter Property="Width" Value="150"/> <Setter Property="Height" Value="50"/> </Style></ResourceDictionary>
targetstyle.xaml
HO CHI MINH UNIVERSITY OF INDUSTRY
9. Style: example TargetType<Window.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="targetstyle.xaml"/> </ResourceDictionary.MergedDictionaries> </ResourceDictionary></Window.Resources><Button Content="FIT HUI"/>
HO CHI MINH UNIVERSITY OF INDUSTRY
9. Style: named style
HO CHI MINH UNIVERSITY OF INDUSTRY
9. Style: named style
HO CHI MINH UNIVERSITY OF INDUSTRY
9. Style: Targeted Styles
Set TargetType attribute to the exact type of the elements on which to apply the style.
– The style will not be applied to elements of types derived from the specified type. Do not set the x:Key attribute. The Setters do not require a class name
with the property name.
HO CHI MINH UNIVERSITY OF INDUSTRY
9. Style: Targeted Styles<Window.Resources> Set the target type. ↓ <Style TargetType="Button"> <Setter Property="FontSize" Value="16" /> <Setter Property="FontWeight" Value="Bold"/> </Style> ↑ No Class Name</Window.Resources><GroupBox Header="Some Buttons" BorderBrush="Black" Margin="5"> <StackPanel> <Button>Button 1</Button> ← No Explicit Application of the Style <Button>Button 2</Button> ← No Explicit Application of the Style </StackPanel></GroupBox>
HO CHI MINH UNIVERSITY OF INDUSTRY
9. Style: Comparing
HO CHI MINH UNIVERSITY OF INDUSTRY
9. Style: The Collections in a Style
Trigger: “conditional” styles Resources property to store logical
resources used by the Setters and Triggers.
HO CHI MINH UNIVERSITY OF INDUSTRY
9. Style: Property TriggersThe condition is based on the value of a
property. When (and while) that property has a certain value, the style is applied
<Window.Resources> <Style TargetType="Button"> <EventSetter Event="Click" Handler="btn_click"/> <Style.Triggers> <Trigger Property="IsMouseOver" Value="true"> <Setter Property="Background" Value="Red"/> <Setter Property="FontWeight" Value="Bold"/> </Trigger> </Style.Triggers> </Style></Window.Resources><Button Content="Hello" ></Button>
HO CHI MINH UNIVERSITY OF INDUSTRY
9. Style: EventSettersEventSetters allow to attach event
handlers to a style <Window.Resources> <Style TargetType="Button"> <EventSetter Event="Click" Handler="btn_click"/> </Style></Window.Resources>public void btn_click
(object o, RoutedEventArgs e) { ((Button)o).Content = "Clicked"; }
HO CHI MINH UNIVERSITY OF INDUSTRY
10. Control templateOverride the default user interface for
common Windows controls are XAML declarations of a "visual tree"
for a control replace the default look & feel define the functionality behind the control
HO CHI MINH UNIVERSITY OF INDUSTRY
10. Control template: example<Window.Resources> <ControlTemplate x:Key= "tmpl" TargetType="{x:Type Button}"> <Border BorderBrush="Navy" BorderThickness="1" CornerRadius="5" Background="CornflowerBlue"> <Border BorderBrush="White" BorderThickness="3"> <Grid> <Grid.RowDefinitions> <RowDefinition/> <RowDefinition/>
</Grid.RowDefinitions> <Label Content="My button" Grid.Row="0" Margin="0" /> <ContentPresenter Grid.Row="1"/> </Grid> </Border> </Border> </ControlTemplate></Window.Resources><Button Content="More text" Template="{DynamicResource tmpl}"/>
HO CHI MINH UNIVERSITY OF INDUSTRY
11. Data bindingIs the process that establishes a connection
between the application UI and businesslogic. Automatically updated to reflect the change
HO CHI MINH UNIVERSITY OF INDUSTRY
11. Simple bindingBinding from one control to another Property to property
– ElementName, Path Example
<StackPanel> <TextBox Name="txt" Text="{Binding ElementName=slider , Path=Value}"/> <Label Content ="{Binding ElementName=txt , Path=Text}"/> <Slider Name="slider"></Slider></StackPanel>
HO CHI MINH UNIVERSITY OF INDUSTRY
11. Binding structure
HO CHI MINH UNIVERSITY OF INDUSTRY
11. Simple binding: example 2<StackPanel><TextBlock Text="Colors:"/> <ListBox x:Name="lbColor"> <ListBoxItem Content="Blue"/> <ListBoxItem Content="Green"/> <ListBoxItem Content="Red"/> </ListBox> <TextBlock Text="You selected color:"/> <TextBlock Background="{Binding ElementName=lbColor, Path =SelectedItem.Content}"> <TextBlock.Text> <Binding ElementName="lbColor" Path="SelectedItem.Content"/> </TextBlock.Text> </TextBlock></StackPanel>
HO CHI MINH UNIVERSITY OF INDUSTRY
11. Binding DirectionOneWay: Updates the target when the source
changes. TwoWay: Updates in both directions. Updates the
target when the source changes and updates the source when the target changes.
OneWayToSource: Updates the source when the target changes.
OneTime: Updates the target property once, with the source’s initial value. After that, the target isn’t updated again.
Default: Uses the default binding mode of the target.
HO CHI MINH UNIVERSITY OF INDUSTRY
11. Binding Direction
HO CHI MINH UNIVERSITY OF INDUSTRY
11. Binding Direction:Triggers
The behavior for updating depends on the direction of the update, as follows: When the direction of the update is from
the source to the target, the update always happens immediately.
When the direction of the update is from the target to the source, then when the update occurs depends on the value of the UpdateSourceTrigger property of the Binding.
HO CHI MINH UNIVERSITY OF INDUSTRY
11. Binding Direction:TriggersSummary of the update behavior based on direction of the update
HO CHI MINH UNIVERSITY OF INDUSTRY
11. Binding Direction:Triggers
<StackPanel><TextBox Margin="10" Text="{Binding ElementName=sldrSlider, Path=Value, UpdateSourceTrigger=PropertyChanged}" /><Slider Name="sldrSlider" TickPlacement="TopLeft" Margin="10"/></StackPanel>
HO CHI MINH UNIVERSITY OF INDUSTRY
12. Graphic objectsTransforms – Transforms allow you to modify the appearance of an element in specific ways. BitmapEffects Shapes
HO CHI MINH UNIVERSITY OF INDUSTRY
12. Graphic objectsRotateTransform
<Button Content="Rotate Me" > <Button.RenderTransform> <RotateTransform Angle="45"/> </Button.RenderTransform></Button>
HO CHI MINH UNIVERSITY OF INDUSTRY
12. Graphic objectsTranslateTransform
Moves an element to a different position
<StackPanel HorizontalAlignment="Center"> <Button Width="70">Button 1</Button> <Button Width="70"> Move Right 30 <Button.RenderTransform>↓ <TranslateTransform X="30" Y="10"/> </Button.RenderTransform> ↑
Move Down 10 Button 2 </Button> <Button Width="70">Button 3</Button></StackPanel>
HO CHI MINH UNIVERSITY OF INDUSTRY
12. Graphic objectsSkewTransform
Skews an element at an angle. Can skew the X or Y coordinates
HO CHI MINH UNIVERSITY OF INDUSTRY
12. Graphic objectsSkewTransform
<StackPanel HorizontalAlignment="Center"> <Button>No Skew</Button> <Button Width="90" FontWeight="Bold" Margin="2"> <Button.RenderTransform> <SkewTransform AngleX="30"/> </Button.RenderTransform> AngleX="30" </Button> <Button Width="90" FontWeight="Bold" Margin="2"> <Button.RenderTransform> <SkewTransform AngleY="30"/> </Button.RenderTransform> AngleY="30" </Button></StackPanel>
HO CHI MINH UNIVERSITY OF INDUSTRY
12. Graphic objectsSkewTransform<Button Name="SkewButton" Width="122" Content="Skew Me!" Click="btn_click"> <Button.RenderTransform> <SkewTransform x:Name="Trans_SkewButton"
CenterX="75" CenterY="37" AngleX="0" AngleY="0" /> </Button.RenderTransform></Button>public void btn_click(object sender, System.Windows.RoutedEventArgs e){ double skew = 30; if (Trans_SkewButton.AngleX == 30) skew = 0; Trans_SkewButton.AngleX = skew; Trans_SkewButton.AngleY = skew;}
HO CHI MINH UNIVERSITY OF INDUSTRY
12. Graphic objectsScaleTransform
Transform changes the size of an element<StackPanel HorizontalAlignment="Center"> <Button Width="70">Button 1</Button> <Button Width="70"> <Button.LayoutTransform> <ScaleTransform ScaleX="1.75" ScaleY="1.5"/> </Button.LayoutTransform> Button 2</Button><Button Width="70">Button 3</Button></StackPanel>
HO CHI MINH UNIVERSITY OF INDUSTRY
12. Graphic objects: BitmapEffects <Button Content="Button"> <Button.BitmapEffect> <EmbossBitmapEffect /> </Button.BitmapEffect></Button>
HO CHI MINH UNIVERSITY OF INDUSTRY
12. Graphic objects: Shapes6 basic typed
HO CHI MINH UNIVERSITY OF INDUSTRY
12. Graphic objects: Shapes6 basic typed
HO CHI MINH UNIVERSITY OF INDUSTRY12. Graphic objects: Shapes<StackPanel Orientation="Vertical" HorizontalAlignment="Center"> <Rectangle Stroke="Black" StrokeThickness="2" Margin="10" Height="30" Width="40"Fill="AliceBlue"/><Ellipse Stroke="Black" StrokeThickness="2" Margin="10" Height="30" Width="40" Fill="AliceBlue"/> <Line Stroke="Black" StrokeThickness="2" Margin="10" X1="0" Y1="0" X2="40" Y2="30"/> <Polyline Stroke="Black"
StrokeThickness="2" Margin="10" Points="0,0 30,0 10,30 40,30"/> <Polygon Stroke="Black" StrokeThickness="2" Margin="10" Points="0,0 30,0 10,30 40,30"/></StackPanel>
HO CHI MINH UNIVERSITY OF INDUSTRY
13. MS Expression Blend
IntrodutionMicrosoft Expression Blend 4 Step by Step
http://www.mediafire.com/?ckv9wv1qkdnl45a
HO CHI MINH UNIVERSITY OF INDUSTRY
Exercise WPF:1. Tạo contact application – Sử dụng VS kết hợp Blend thiết kế giao diện • Listbox danh sách /button: thêm, sửa, xóa,lưu • Dùng style để thay đổi giao diện tất cả button giống nhau, tất cả textbox giống nhau. • Dùng Style/trigger thay đổi giao diện các textbox (background, fontsize) khi di chuyển chuột trên các textbox này • Dùng Trigger để màu các textbox thay đổi khi thay đổi chế độ soạn thảo • Thay đổi Style, transform, BitmapEffect thay đổi giao diện button • Bổ sung một đồng hồ kim giờ - phút – giây phía trái màn hình
HO CHI MINH UNIVERSITY OF INDUSTRY
Exercise WPF: Using WPF app (con’t) – Display contact app. – Next/Pre/First/Last menu using icon – Display contact list with same icon in Listbox, Treeview Using Expression Blend – Change Style – Change template – Using transform, BitmapEffect for buttons
HO CHI MINH UNIVERSITY OF INDUSTRY
END