Beruflich Dokumente
Kultur Dokumente
Foundation (WPF)
Deep Sengupta
Associate Software Engineer
JDA Software
Agenda
• Enhanced ClearType text rendering. ClearType text rendering delivers text with improved legibility
and y-direction anti-aliasing.
• sub pixel rendering improves text clarity as the texts can occupy the sub-pixel position leading to
high resolution texts.
• y- direction anti-aliasing smoothens the uneven surface of the top and bottom of the text.
• Can use visual effects such as shadow, glow, blur and transformations(move, rotate, skew)
• OpenType font format provides wide variety of fonts, font styles.
• WPF 3.5 supports Indian scripts and languages. Example. Devanagiri,Gurmukhi.
• Large amount of text are handled using XML Paper Specifications(XPS) and flow documents.
• Enhanced support for 2-D,3-D Graphics and animations and multimedia.
• Example,UIElement3D class has properties that can be used to create and work with 3D content.
Scalable Graphics
3D Graphics
Resolution independence
• All sizes in WPF are specified in logical units, not in pixels. A logical
unit is a 1/96 of an inch. If you increase the resolution of your screen,
the user interface stays the same size - if just gets crispier. Since
WPF builds on a vector based rendering engine it has never been so
easy to build scaleable user interfaces.
Scenarios for using WPF
•project requires collaboration with designers. The use of XAML and its supporting
tools can really help out here.
•Your application is media aware. If you need to integrate video and audio into
your product, you’ll definitely want to consider WPF.
•The anticipated hardware for your application has support for DirectX 9 or
greater. WPF is built on top of DirectX, and your applications will benefit from
the hardware acceleration.
•Your application needs support for advanced typography. WPF has support for
OpenType and many other features that are not available with Windows
Forms.
Tools for WPF
PresentationFramework
PresentaionCore WindowsBase
milcore WindowsCodecs
User32 DirectX
Kernel
Presentation Framework
• Implemented as WindowsBase.dll.
• Provides features such as threading, type converters
and dependencyproperties.
• Some of these features can be accessed and used
outside of the WPF domain.
MIL or Milcore
System.Windows.Threading.DispatcherObject
System.Windows.DependencyObject
System.Windows.UIElement
System.Windows.FrameworkElement
• Allows to work with objects that have editable and read only states.
• Support for change notifications whenever changes in Objects.
• Freezable objects can have two states: Unfrozen(editable) and frozen(read only).
• By default freezable objects are in unfrozen states. Whenever they are changed
notifications are generated to bring changes into effect.
• Freezable objects improve performance as system resources are not used for
change notifications.
• Freezable objects cannot be frozen under following conditions:
a. The object contains any data bound or animated properties.
b. The object contains any properties that are set by dynamic resources.
c. The object contains any other object that cannot be frozen.
System.Windows.Media.Visual class
XAML C# VB.NET
<Button Width="100"> OK Button b1 = new Button(); Dim b1 As New Button
<Button.Background> b1.Content = "OK"; b1.Content = "OK"
LightBlue b1.Background = new b1.Background = New _
</Button.Background> SolidColorBrush(Colors.LightBlue); SolidColorBrush(Colors.LightBlue)
</Button> b1.Width = 100; b1.Width = 100
Properties in WPF
• Dependency Properties.
• Attached Properties.
Dependency Properties
• Value inheritance
When you access a dependency property the value is resolved by using a value
resolution strategy. If no local value is set, the dependency property navigates up the
logical tree until it finds a value. When you set the FontSize on the root element it
applies to all textblocks below except you override the value.
• Change notification
Dependency properties have a built-in change notification mechanism. By registering
a callback in the property metadata you get notified, when the value of the property
has been changed. This is also used by the databinding.
Value resolution strategy
of Dependency Properties
• Every time you access a dependency property, it internally resolves the value by
following the precedence from high to low. It checks if a local value is available, if not
if a custom style trigger is active,... and continues until it founds a value. At last the
default value is always available.
The magic behind it
• Some dependency property of WPF controls are readonly. They are often used to report the state
of a control, like the IsMouseOver property. This does not make sense to provide a setter for this
value.
// Register the private key to set the value
private static readonly DependencyPropertyKey IsMouseOverPropertyKey =
DependencyProperty.RegisterReadOnly ("IsMouseOver", typeof(bool), typeof
(MyClass), new FrameworkPropertyMetadata(false));
// Register the public property to get the value public static readonly
DependencyProperty IsMouseoverProperty =
IsMouseOverPropertyKey.DependencyProperty;
// .NET Property wrapper
public int IsMouseOver
{ get { return (bool) GetValue (IsMouseoverProperty); }
private set { SetValue (IsMouseOverPropertyKey, value); }
}
Attached Properties
• Routed events are events who navigate up or down the visual tree acording to their
RoutingStrategy.
• Tunneling The event is raised on the root element and navigates down to the visual
tree until it reaches the source element or until the tunneling is stopped by marking
the event as handeld. By naming convention it is called Preview... and appears
before corresponding bubbling event.
• Bubbling The event is raised on the source element and navigates up to the visual
tree until it reaches the root element or until the bubbling is stopped by marking the
event as handled. The bubbling event is raised after the tunneling event.
• Direct The event is raised on the source element and must be handled on the source
element itself. This behavior is the same as normal .NET events.
How Routed Events Work?
<Grid PreviewKeyDown="Grid_PreviewKeyDown" KeyDown="Grid_KeyDown">
<Button Content="Click me" HorizontalAlignment="Stretch" VerticalAlignment="Center" KeyDown="Button_KeyDown"
PreviewKeyDown="Button_PreviewKeyDown"/>
</Grid>
Copy in Windows1.xaml.cs
The Microsoft home page doesn’t take advantage of the extra width.
Types of Layouts
Panels:
• Canvas
• StackPanel
• WrapPanel
• DockPanel
• Grid
(Note: All Panels present in Sytem.Windows.Controls in
PresentationFramework assembly)
Common layout properties
• With no attached properties for arranging children, there is just have one
way to customize the behavior of StackPanel—setting its Orientation
property (of type System.Windows.Controls.Orientation) to Horizontal or
Vertical. Vertical is the default Orientation.
Code
<StackPanel Background="#ECE9D8">
<TextBlock Margin="3">Look for:</TextBlock>
<ComboBox Margin="3"/>
<TextBlock Margin="3">Filtered by:</TextBlock>
<ComboBox Margin="3"/>
<Button Margin="3,5">Search</Button>
<CheckBox Margin="3">Search in titles only</CheckBox>
<CheckBox Margin="3">Match related words</CheckBox>
<CheckBox Margin="3">Search in previous results</CheckBox>
<CheckBox Margin="3">Highlight search hits (in topics)</CheckBox>
</StackPanel>
WrapPanel
Code
<WrapPanel Background="Beige">
<Button>One</Button>
<Button>Two</Button>
<Button>Three</Button>
<Button>Four</Button>
<Button>Five</Button>
<Button>Six</Button>
<Button>Seven</Button>
<Button>Eight</Button>
</WrapPanel>
DockPanel
• WrapPanel and StackPanel really are useful only for small-scale layout. You
will need to use a more powerful panel to define the overall layout of your
application, such as DockPanel.
• DockPanel is useful for describing the overall layout of a simple user
interface.
• A DockPanel arranges each child element so that it fills a particular edge of
the panel. If multiple children are docked to the same edge, they simply
stack up against that edge in order. By default, the final child fills any
remaining space not occupied by controls docked to the panel’s edges.
DockPanel (Important Properties)
• Code
<Grid Background="Beige" ShowGridLines="True">
<!-- ShowGridLines for testing only -->
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock Grid.Column="0" Grid.Row="0">Protocol:</TextBlock>
<TextBlock Grid.Column="1" Grid.Row="0">HyperText Transfer Protocol</TextBlock>
<TextBlock Grid.Column="0" Grid.Row="1">Type:</TextBlock>
<TextBlock Grid.Column="1" Grid.Row="1">HTML Document</TextBlock>
<TextBlock Grid.Column="0" Grid.Row="2">Connection:</TextBlock>
<TextBlock Grid.Column="1" Grid.Row="2">Not encrypted</TextBlock>
</Grid>
Custom Panel
• You can use both the RenderTransform and LayoutTransform properties to apply a transform,
such as scaling or rotation, to an element and all of its children.
A Small Example
• <StackPanel Orientation="Horizontal">
• <TextBlock>
• <TextBlock.RenderTransform>
• <TransformGroup>
• <ScaleTransform ScaleX="8" ScaleY="4" />
• <RotateTransform Angle="10" />
• </TransformGroup>
• </TextBlock.RenderTransform>
• Hello,
• </TextBlock>
• <TextBlock>world</TextBlock>
• </StackPanel>
• Clipping
• Scrolling
• Scaling
Clipping
• Clipping (that is, truncating or cropping) children is the default way that panels handle
them when they are too large. Clipping can happen at the edges of a panel or within a
panel (such as at the edges of a Grid cell or the fill area of a DockPanel).
• All UIElements have a Boolean ClipToBounds property that controls whether child
elements can be rendered outside of its bounds.
• Despite the fact that all panels inherit a ClipToBounds property, Canvas is the only
one that respects it.
ClipToBounds=“False” ClipToBounds=“True”
Scrolling
• Although scrolling is a popular and long-standing way to deal with large content, dynamically shrinking
or enlarging content to “just fit” in a given space is more appropriate for several scenarios.
• System.Windows.Controls.Viewbox provides an easy mechanism to scale arbitrary content within a
given space.
Code
<Viewbox>
<StackPanel>
<Button Background="Black"></Button>
<Button Background="Black"></Button>
<Button Background="Black"></Button>
<Button Background="Black"></Button>
</StackPanel>
</Viewbox>
Best Practices in Layout design
• Avoid fixed positions - use the Alignment properties in combination with Margin to
position elements in a panel
• Avoid fixed sizes - set the Width and Height of elements to Auto whenever
possible. A better way is to use the MinHeight, MaxHeight, MinWidth and
MaxWidth properties to define a acceptable range.
• Don't abuse the canvas panel to layout elements. Use it only for vector graphics.
• Use a GridPanel to layout a static data entry form. Create a Auto sized column for
the labels and a Star sized column for the TextBoxes.
Data Binding
<StackPanel>
<TextBox x:Name="txtInput" />
<Label Content="{Binding Text, ElementName=txtInput,
UpdateSourceTrigger=PropertyChanged}" />
</StackPanel>
How Data Binding Works
• <StackPanel DataContext="{StaticResource
myCustomer}"> <TextBox Text="{Binding FirstName}"/>
<TextBox Text="{Binding LastName}"/> <TextBox
Text="{Binding Street}"/> <TextBox Text="{Binding
City}"/> </StackPanel>
• Show AutoChangeNotification.
ValueConverters
• <StackPanel>
• <StackPanel.Resources>
• <BooleanToVisibilityConverter x:Key="boolToVis" />
•
• </StackPanel.Resources>
• Note: Instead of Button.FontSize we can also use Control.FontSize for more generic use.
Style Inheritance
• A style in WPF can base on another style. This allows you to specify
a base style that sets common properties and derive from it for
specialized controls.
Code
<Style x:Key="baseStyle"> <Setter Property="FontSize" Value="12" />
<Setter Property="Background" Value="Orange" />
</Style>
<Style x:Key="boldStyle" BasedOn="{StaticResource baseStyle}">
<Setter Property="FontWeight" Value="Bold" />
</Style>
Creating Implicit Styles
• <Application …>
• <Application.Resources>
• <Style TargetType=”{x:Type Button}”>
• <Setter Property=”FontSize” Value=”22”/>
• <Setter Property=”Background” Value=”Purple”/>
• <Setter Property=”Foreground” Value=”White”/>
• <Setter Property=”Height” Value=”50”/>
• <Setter Property=”Width” Value=”50”/>
• <Setter Property=”RenderTransformOrigin” Value=”.5,.5”/>
• <Setter Property=”RenderTransform”>
• <Setter.Value>
• <RotateTransform Angle=”10”/>
• </Setter.Value>
• </Setter>
• </Style>
• </Application.Resources>
• </Application>
Control Templates
• The following code sample shows a simple control template for a button with an ellipse shape.
• <Window.Resources>
• <Style x:Key="DialogButtonStyle" TargetType="Button">
• <Setter Property="Template">
• <Setter.Value>
• <ControlTemplate TargetType="{x:Type Button}">
• <Grid>
• <Ellipse Fill="{TemplateBinding Background}"
• Stroke="{TemplateBinding BorderBrush}"/>
• <ContentPresenter HorizontalAlignment="Center"
• VerticalAlignment="Center"/>
• </Grid>
• </ControlTemplate>
• </Setter.Value>
• </Setter>
• </Style>
• </Window.Resources>
• <StackPanel>
• <Button Style="{StaticResource DialogButtonStyle}" Height="40" Width="80"/>
• </StackPanel>
Next Steps
• First Buy
• Title: Windows Presentation Foundation Unleashed
• Author: Adam Nathan, Sams
• (Currently the best book on the subject)