Sie sind auf Seite 1von 83

Introduction to Windows Presentation

Foundation (WPF)

Deep Sengupta
Associate Software Engineer
JDA Software
Agenda

• Why Windows Presentation Foundation ?


• WPF Architecture
• WPF Property system
• WPF Event system
• Layouts
• DataBinding
• Style
• Control Template
.NET At The Core
Windows Presentation Foundation

A productive, unified approach to UI,


media and documents to deliver
unmatched user experience
Why WPF and Not Windows Forms?

1. Improved Application Model.


2. Improved Controls.
3. Support for Data Validation and Data Binding
Models and LINQ.
4. Support for High-End Text Rendering ,Typography
and Documents
5. Enhanced Support for 2D and 3D Graphics ,
Animations and Multimedia.
Improved Application Model

• WPF facilitates the separation of code and design in a WPF


application. WPF allows you to construct your interface using a
markup language called XAML
• (pronounced zammel, rhymes with camel).
• Offers Flexibility in choosing application type (WPF standalone
application or XAML Browser application XBAP).
• Also supports an add-in model(System.AddIn Namespace)
that allow you to work with visual and non-visual model.
Improved Control

• All WPF controls supports variable content types (means


a control can contains other control).
• Control template and data template helps modify the
appearance of the
• Data template to change the appearance of the content
that control holds.
Data validation support,DBM,LINQ

• WPF 3.5 allows to bind data through traditional data


model and LINQ.
• Debugging through trace level property of
System.Diagonistics.Presentation.TraceSources class to
specify the extent of debug tracing of the bindings.
• Example. IDataError interface and
ValidatesOnExceptions and ValidatesOnDataErrors
propertiesof the binding/Multibinding classes allow to
verify the input.
Support for High-End Text Rendering, Typography, Documents
and enhanced support for 2D and 3D graphics

• 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

• Graphics in WPF are vector based, in contrast to raster


based.
• Vector graphics are inherently scalable and typically
require less storage than a comparable raster image.
• Vector graphics are inherently scalable and typically
require less storage than a comparable raster image.
• The net result for developers with WPF is that
applications scale nicely without a loss in visual quality.
ClearType & Antialiasing

Sub-pixel positioning & natural widths


2D Graphics, 3D 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

1. Visual Studio 2008


2. The second primary tool for creating WPF applications from Microsoft is Expression
Blend. Blend targets designers rather than developers. It works with the same files as
Visual Studio, so a designer using Blend and a developer using Visual Studio can both
work on the same projects, solution, and files. Blend is somewhat comparable to the IDE
for Adobe Flash.
3. A third-party product exists for designing WPF interfaces—Aurora, by Mobiform
Software. It provides a similar set of features as Expression Blend. One notable feature
is that Aurora designer can be embedded in another WPF application
4. Expression Design is another Microsoft product. It is for authoring vector-based
graphical content, similar to Adobe Illustrator or Inkscape. Expression Design can be
used to create logos, icons, and illustrations for use with WPF.
5. Aside from the 3D tools just mentioned, at least one WPF-specific 3D content editor is
available—ZAM 3D by Electric Rain. ZAM 3D is very similar to the Swift 3D product for
Flash. It’s more approachable than most 3D editors and is probably the best place to
start for WPF developers interested in 3D.
6. One final tool worth mentioning is Kaxaml. It is a lightweight XAML editor featuring a live
preview.
Getting Started with WPF
WPF 3.5 Architecture

PresentationFramework

PresentaionCore WindowsBase

Common Language Runtime

milcore WindowsCodecs

User32 DirectX

Kernel
Presentation Framework

• Presentation Framework component is implemented as


PresentaionFramework.dll in.net Framework 3.5.
• Offers classes that control the appearance and
presentation of WPF 3.5 Applications.
• Example. Controls, Layout, animations and data binding
are handled by this layer.
Presentation Core

• Implemented as PresentationCore.dll in .net Framework


3.5.
• Classes and types offered by this component provide
functionalities such as properties, events and messeges.
• Does not offers type for UI as by Presentation
framework.
WindowsBase

• 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

• Unmanaged component in WPF 3.5.


• Milcore interacts with DirectX and acts as an interface between
DirectX and CLR and managed WPF components.
• Due to this interaction with DirectX, milcore allows to see 2-
D,3-D contents and to work with them.
• Has composition engine that uses the H/W and S/w rendering
of DirectX for WPF 3.5 applications.
• Milcore is able to use DirectX because it is an unmanaged
component.
WPF 3.5 class hierarchy

System.Windows.Threading.DispatcherObject

System.Windows.DependencyObject

System.Windows.Freezable System.Window.Media.Visual System.Windows.ContentElement

System.Windows.UIElement

System.Windows.FrameworkElement

System.Windows.Controls.Control System.Windows.Controls.Panel System.Windows.Shapes.Shape


System.Windows.Threading.DispatcherObject class

• DispatcherObject class is used for managing threads.


• WPF applications run with two threads: one for UI another for rendering.
• UI thread main executing thread and obtains input and events.
• WPF applications can have more that one UI thread but leads to complicated processing.
So, WPF employs STA(Single threaded apartment model).
• With STA WPF applications are now compatible with IE.
• With STA there can be multiple threads for UI elements but only one will run at a time.UI
elements belonging to one thread are private to that thread only. This is called thread
affinity.
• Interaction between multiple threads are done using dispatcher an instance of Dispatcher
class. Every thread has a dispatcher that sends and receives User32 messages to execute
the thread. In the dispatcher the work items are queued based on the priority they are
executed.
• Reference to the dispatcher are stored in the an instance of DispatcherObject class.
• DispatcherObject class provides with methods to allow you to check that no thread other
than the one on which an object of the class is created, accesses the object.
System.Windows.DependencyObject class

• Dependency property is the CLR property backed by


System.Windows.DependencyProperty class and is
registered with WPF property system.
• Derived classes can use the dependency property system.
• The values of dependency properties depend on several
properties or inputs such as styles themes and animations of
WPF Objects.
• Dependency properties allow you to use expressions as
property values, bind data,incorporate animations,apply
styles.
System.Windows.Freezable class

• 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

• Used to render elements used in WPF applications.


• The Visual class acts as a link between the managed
WPF components and Milcore by generating the tree like
structure in the Milcore called Composition tree.
• WPF uses the retained mode rendering system i.e.
complete composition tree is cached by milcore.
Other classes

• System.Windows.UIElement class has APIs for


implementing functionalities such as layouts and events for
WPF elements.
• System.Windows.FrameworkElement classis the interface
between UIElement class and WPF framework level
implementation elements.
• System.Windows.Controls.Control class
:Label,Button,RadioButton etc are derived from this class.
Has several properties to incorporate background and
foreground visual effects.
Types of WPF applications

• WPF 3.5 application:


a. Standalone WPF applications.
b. XAML Browser applications
Other classes continued….

• System.Windows.Controls.Panel class is a container


control that holds other controlsAll panels are derived from
this.Example.Grid,Canvas,StackPanel.
• System.Windows.Shapes.Shape class offers support to 2-
D,3-D graphicsDifferent shapes such as Ecllipse,Circle etc
are derived from this class.
• System.Windows.ContentElement class exists in the
presentationcore assembly and offers some of the core
level functionalities to work with content of WPF
applications.responsible for the style and presentation of
the contents.
Why XAML

It seems strangle to use XML as a declarative language


that Microsoft would base their future on. Why?
• Concise implementation (Similar to HTML)
• Human Readable (except Vector & Meshes)
• Interoperable between multiple tools such as Blend,
Orcas, XAMLPAD
Declarative Programming Through XAML

XAML = Extensible Application Markup Language


•Easily toolable, declarative markup
•Code and content are separate
•Can be rendered in the browser / standalone application

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

• A dependency property depends on multiple providers for


determining its value at any point in time. These providers could be
an animation continuously changing its value.
• The biggest feature of a dependency property is its built-in ability to
provide change notification.
• The main difference is, that the value of a normal .NET property is
read directly from a private member in your class, whereas the
value of a DependencyProperty is resolved dynamically .
• When you set a value of a dependency property it is not stored in a
field of your object, but in a dictionary of keys and values provided
by the base class DependencyObject. The key of an entry is the
name of the property and the value is the value you want to set.
Why Dependency Properties

• Reduced memory footprint


It's a huge dissipation to store a field for each property when you think that over 90%
of the properties of a UI control typically stay at its initial values. Dependency
properties solve these problems by only store modified properties in the instance. The
default values are stored once within the dependency property.

• 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

• Each WPF control registers a set of


DependencyProperties to the static
DependencyProperty class. Each of them
consists of a key - that must be unique per type
- and a metadata that contain callbacks and a
default value. All types that want to use
DependencyProperties must derive from
DependencyObject. This baseclass defines a
key, value dictionary that contains local values
of dependency properties. The key of an entry is
the key defined with the dependency property.
When you access a dependency property over
its .NET property wrapper, it internally calls
GetValue(DependencyProperty) to access the
value. This method resolves the value by using
a value resolution strategy that is explained in
detail below. If a local value is available, it reads
it directly from the dictionary. If no value is set if
goes up the logical tree and searches for an
inherited value. If no value is found it takes the
default value defined in the property metadata.
This sequence is a bit simplified, but it shows
the main concept.
How to create a dependency property
• Code Implementation of Button class
public class Button : ButtonBase
{
// The dependency property
public static readonly DependencyProperty IsDefaultProperty;
static Button()
{
// Register the property
Button.IsDefaultProperty = DependencyProperty.Register(“IsDefault”,
typeof(bool), typeof(Button),
new FrameworkPropertyMetadata(false,
new PropertyChangedCallback(OnIsDefaultChanged)));

}
// A .NET property wrapper (optional)
public bool IsDefault
{
get { return (bool)GetValue(Button.IsDefaultProperty); }
set { SetValue(Button.IsDefaultProperty, value); }
}
// A property changed callback (optional)
private static void OnIsDefaultChanged(
DependencyObject o, DependencyPropertyChangedEventArgs e) { … }

• }
ReadOnly Dependency property

• 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

• One purpose of an attached property is to allow different child elements


to specify unique values for a property that is actually defined in a
parent element.
• Attached properties are a special kind of DependencyProperties.
• A good example for this concept are layout panels. Each layout panel
needs different data to align its child elements. The Canvas needs Top
and Left, The DockPanel needs Dock, etc.
• Point To Remember: Attached properties are a XAML concept,
whereas dependency properties are a WPF concept. Because
WPF attached properties are dependency properties, they support
dependency property concepts such as property metadata, and default
values from that property metadata.
How to create a attached property

public static readonly DependencyProperty TopProperty =


DependencyProperty.RegisterAttached(
"Top",
typeof(double),
typeof(Canvas),
new FrameworkPropertyMetadata(False,
FrameworkPropertyMetadataOptions.Inherits));
public static void SetTop(UIElement element, double value)
{
element.SetValue(TopProperty, value);
}
public static double GetTop(UIElement element)
{
return (double)element.GetValue(TopProperty);
}
Routed Events

• 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

private void Button_KeyDown(object sender, KeyEventArgs e)


{
string str = sender.GetType().Name;
}

private void Button_PreviewKeyDown(object sender, KeyEventArgs e)


{
string str = sender.GetType().Name;
}

private void Grid_PreviewKeyDown(object sender, KeyEventArgs e)


{
string str= sender.GetType().Name;
}

private void Grid_KeyDown(object sender, KeyEventArgs e)


{
string str = sender.GetType().Name;
}
How to Create a Custom Routed Event

public class Button : ButtonBase


{
• // The routed event
• public static readonly RoutedEvent ClickEvent;
• static Button()
• {
• // Register the event
• Button.ClickEvent = EventManager.RegisterRoutedEvent(“Click”,
• RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(Button));
• …
• }
• // A .NET event wrapper (optional)
• public event RoutedEventHandler Click
• {
• add { AddHandler(Button.ClickEvent, value); }
• remove { RemoveHandler(Button.ClickEvent, value); }
• }
• protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
• {
• …
• // Raise the event
• RaiseEvent(new RoutedEventArgs(Button.ClickEvent, this));
• …
• }
• …
• }
RoutedEventArgs

• Source—The element in the logical tree that originally raised the


event.
• OriginalSource—The element in the visual tree that originally
raised the event (for example, the TextBlock or ButtonChrome child
of a standard Button).
• Handled—A Boolean that can be set to true to mark the event as
handled. This is precisely what halts any tunneling or bubbling.
• RoutedEvent—The actual routed event object (such as
Button.ClickEvent), which can be helpful for identifying the raised
event when the same handler is used for multiple routed events.
Layouts

• Layout is a critical component of an application’s


usability on a wide range of devices.
• Static pixel-based sizes can work in limited
environments.
• WPF contains built-in panels that can make it easy to
avoid layout pitfalls.
Example of bad layout.

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

• Width: Specifies a fixed width


• Height: Specifies a fixed height
• MinWidth: The minimum permissible width
• MaxWidth: The maximum permissible width
• MinHeight :The minimum permissible height
• MaxHeight :The maximum permissible height
• HorizontalAlignment: Horizontal position if element is smaller than available space
• VerticalAlignment :Vertical position if element is smaller than available space
• Margin: Space around outside of element
• Padding: Space between element border and content
• Visibility: Allows the element to be made invisible to the layout system where necessary
• FlowDirection: Text direction
• Panel.ZIndex :Controls which elements are on top or underneath
• RenderTransform: Applies a transform without modifying the layout
• LayoutTransform :Applies a transform that affects layout
Canvas

• Canvas is most basic panel.


• Performs no layout logic.
• Puts children where you tell it to.
• Gives complete control and precise positing of every child.
• For example, when you want to build an image out of graphical
elements, the positioning of the elements is dictated by the picture
you are creating, not by any set of automated layout rules. For these
scenarios, you can use a Canvas.
(Note : Never use canvas for as a base layout for arranging WPF
controls)
Canvas (Important properties)
• Canvas defines four attached properties for setting the position of child
elements. Vertical position is set
with either the Top or Bottom property, and horizontal position is
determined by either the Left or Right property.
Code Example
<Canvas Background="Yellow" Width="150" Height="100">
<TextBlock Canvas.Left="10"
Canvas.Top="20">Hello</TextBlock>
<TextBlock Canvas.Right="10" Canvas.Bottom="20">world!
</TextBlock>
</Canvas>
(Note : If you attempt to set Canvas.Left and Canvas.Right simultaneously,
Canvas.Right gets ignored. And if you attempt to set Canvas.Top and
Canvas.Bottom simultaneously,Canvas.Bottom gets ignored. Therefore, you
can’t dock an element to more than one corner of the Canvas at a time.)
StackPanel

• StackPanel is a very simple panel that arranges its


children in a row or a column.
• StackPanel is a popular panel because of its simplicity
and usefulness. It is most useful for arranging small
subsections.
StackPanel (Important 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

• WrapPanel works just like a StackPanel until it runs out


of space.
• WrapPanel wraps its child element to additional rows or
columns when there’s not enough space for a single
stack.
WrapPanel (Important Properties)

• Like StackPanel, WrapPanel has no attached properties for controlling element


positions.It defines three properties for controlling its behavior Orientation
,ItemHeight ,ItemBehavior.

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)

• DockPanel has a Dock attached property (of type System.Windows.Controls.Dock),


so children can control their docking with one of four possible values: Left (the default
when Dock isn’t applied), Top, Right, and Bottom.
• The LastChildFill property of dock panel allow last element to fill the remaining space.
Code
<DockPanel>
<Button DockPanel.Dock="Top">Top</Button>
<Button DockPanel.Dock="Bottom">Bottom</Button>
<Button DockPanel.Dock="Left">Left</Button>
<Button DockPanel.Dock="Right">Right</Button>
<Button>Fill</Button>
</DockPanel>
Grid

• Grid is the most versatile panel, and probably the one


you’ll use most often.
• It enables you to arrange its children in a multirow and
multicolumn fashion without relying on wrapping (like
WrapPanel), and provides a number of features to
control the rows and columns in interesting ways.
Grid (Important Properties)

• For the basic usage of Grid, you define the number of


rows and columns by adding that number of
RowDefinition and ColumnDefinition elements to its
RowDefinitions and ColumnDefinitions properties. (It’s a
little verbose, but handy for giving individual rows and
columns distinct sizes.)
• To specify the position of child element Grid have 2
attached properties Grid.Row Grid.Column.By default
the value of Row and Column is 0,0.
• ShowGridLine property is used to show the grid line.
Grid (Code)

• 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

• sometimes none of the included layout panels helps you to


arrange child elements in the way you like it. In this case its
easy to write your own layout panel. All you need to do is to
create a new class that derives from Panel.
• Layout occurs in two phases: measure and arrange.
• Your custom panel will first be asked how much space it
would like to have—that’s the measure phase.
• It is only in the “arrange” phase that we find out how much
space we have. During this phase, we must decide where to
put all of our children as best we can in the space available.
Custom Panel Continued …

• There are two methods to override:


• MeasureOverride - to determine the required size of the
panel according to the desired size of the child elements
and the available space.
• ArrangeOverride - to arrange the elements in the finally
available space. The final size can be smaller than the
requested.
Custom Panel Continued …

• public class MySimplePanel : Panel


• {
• // Make the panel as big as the biggest element
• protected override Size MeasureOverride(Size availableSize)
• {
• Size maxSize = new Size();
• foreach( UIElement child in InternalChildern)
• {
• maxSize.Height = Math.Max( child.DesiredSize.Height, maxSize.Height);
• maxSize.Width= Math.Max( child.DesiredSize.Width, maxSize.Width);
• }
• }
• // Arrange the child elements to their final position
• protected override Size ArrangeOverride(Size finalSize)
• {
• foreach( UIElement child in InternalChildern)
• {
• child.Arrange( new Rect( finalSize ) );
• }
• }
• }
RenderTransform and LayoutTransform

• 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>

Note: We will cover it in separate topic.


Handling Content Overflow

• 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

• The ScrollViewer control allows oversized content to be displayed by putting it


into a scrollable area.
• The ScrollViewer control allows oversized content to be displayed by putting it
into a scrollable area.
• ScrollViewer exposes several properties and methods for more advanced or
programmatic manipulation of scrolling, but its two most important properties
are VerticalScrollBarVisibility and HorizontalScrollBarVisibility.
• The default value for VerticalScrollBarVisibility is Visible, and the default value
for HorizontalScrollBarVisibility is Auto, to match the scrolling behavior used by
most applications.
Code
<ScrollViewer HorizontalScrollBarVisibility="Auto">
<Ellipse Fill="Green" Height="1000" Width="2000" />
</ScrollViewer>
Scaling

• 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 StackPanel to layout buttons of a dialog

• 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

• WPF provides a simple and powerful way to auto-


update data between the business model and the user
interface. This mechanism is called DataBinding.
• Every time when the data of your business model
changes, it automatically reflects the updates to the user
interface and vice versa.
• Databinding can be unidirectional (source -> target or
target <- source), or bidirectional (source <-> target).
• The source of a databinding can be a normal .NET
property or a DependencyProperty. The target property
of the binding must be a DependencyProperty.
Data Binding Continues …

• Databinding is typically done in XAML by using the


{Binding} markup extension. The following example
shows a simple binding between the text of a TextBox
and a Label that reflects the typed value:

<StackPanel>
<TextBox x:Name="txtInput" />
<Label Content="{Binding Text, ElementName=txtInput,
UpdateSourceTrigger=PropertyChanged}" />
</StackPanel>
How Data Binding Works

• To make the databinding properly work, both sides of a binding must


provide a change notification that tells the binding when to update the
target value. On normal .NET properties this is done by raising the
PropertyChanged event of the INotifyPropertyChanged interface. On
DependencyProperties it is done by the PropertyChanged callback of the
property metadata
Data Context

• Every WPF control derived from FrameworkElement has


a DataContext property. This property is meant to be
set to the data object it visualizes. If you don't explicity
define a source of a binding, it takes the data context by
default.
• The DataContext property inherits its value to child
elements. So you can set the DataContext on a superior
layout container and its value is inherited to all child
elements. This is very useful if you want to build a form
that is bound to multiple properties of the same data
object.
Data Context Code

• <StackPanel DataContext="{StaticResource
myCustomer}"> <TextBox Text="{Binding FirstName}"/>
<TextBox Text="{Binding LastName}"/> <TextBox
Text="{Binding Street}"/> <TextBox Text="{Binding
City}"/> </StackPanel>

• Show AutoChangeNotification.
ValueConverters

• you want to bind two properties of different types


together, you need to use a ValueConverter.
• A ValueConverter converts the value from a source type
to a target type and back.
• WPF already includes some value converters but in most
cases you will need to write your own by implementing
the IValueConverter interface.
Code to understand ValueConverters

• <StackPanel>
• <StackPanel.Resources>
• <BooleanToVisibilityConverter x:Key="boolToVis" />

• </StackPanel.Resources>

• <CheckBox x:Name="chkShowDetails" Content="Show Details" />


• <StackPanel x:Name="detailsPanel"
• Visibility="{Binding IsChecked, ElementName=chkShowDetails,
• Converter={StaticResource boolToVis}}">
• <Button Background="Blue"/>
• <Button Background="Black"/>
• <Button Background="Red"/>
• </StackPanel>
• </StackPanel>
Style

• A simple mechanism for separating property values from user


interface elements (similar to the relationship between
Cascading Style Sheets [CSS] and HTML).
• A style consists of a list of property setters. If you apply a style
it sets the properties on the user interface element to the
styles' values.
• Using styles gives you the following advantages:
Removes redundancy from your code
Let you change the appearance of a set of controls from
a single point
Gives you the possibility to swap the style at runtime
Style (Code to understand)
• <StackPanel Orientation="Horizontal">
• <StackPanel.Resources>
• <Style x:Key="buttonStyle">
• <Setter Property="Button.FontSize" Value="22"/>
• <Setter Property="Button.Background" Value="Purple"/>
• <Setter Property="Button.Foreground" Value="White"/>
• <Setter Property="Button.Height" Value="50"/>
• <Setter Property="Button.Width" Value="50"/>
• <Setter Property="Button.RenderTransformOrigin" Value=".5,.5"/>
• <Setter Property="Button.RenderTransform">
• <Setter.Value>
• <RotateTransform Angle="10"/>
• </Setter.Value>
• </Setter>
• </Style>
• </StackPanel.Resources>
• <Button Style="{StaticResource buttonStyle}">1</Button>
• <Button Style="{StaticResource buttonStyle}">2</Button>
• <Button Style="{StaticResource buttonStyle}">3</Button>
• </StackPanel>

• 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

• Controls in WPF are separated into logic, that defines


the states, events and properties and template, that
defines the visual appearance of the control. The wireup
between the logic and the template is done by
DataBinding.
• The template is defined by a dependency property called
Template. By setting this property to another template
you can completely replace the visual appearance of a
control.
Control Templates continued …
Control Templates continued ..

• 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)

• Download the Blend 2 May Preview


• Download the Net 3.0 SDK
• Download the extensions to Visual Studio 2005.
• Click on

Das könnte Ihnen auch gefallen