0% found this document useful (0 votes)
5 views57 pages

Module 8

The document provides an overview of Windows Presentation Foundation (WPF), a UI framework that utilizes XAML for designing user interfaces and offers features like data binding, layouts, and controls. It contrasts WPF with WinForms, highlighting WPF's advantages in rendering speed and UI customization. The document also explains the architecture of WPF, including its managed and unmanaged layers, and the separation of markup and code-behind for efficient development.

Uploaded by

PAulos
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views57 pages

Module 8

The document provides an overview of Windows Presentation Foundation (WPF), a UI framework that utilizes XAML for designing user interfaces and offers features like data binding, layouts, and controls. It contrasts WPF with WinForms, highlighting WPF's advantages in rendering speed and UI customization. The document also explains the architecture of WPF, including its managed and unmanaged layers, and the separation of markup and code-behind for efficient development.

Uploaded by

PAulos
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Department of CE/IT

Dot Net Technologies

WPF Unit no : 8
Dot Net Technologies
(01CE0602)
Unit 8: WPF
1) Introduction to WPF
Department of CE/IT
2) Introduction to XAML
3) WPF Architecture
Unit no : 8
4) WPF v/s WinForms Dot Net Technology
5) Layouts (01CE0602)

6) WPF Controls – TextBox, TextBlock, Label, Button


7) WPF Controls – ComboBox, ListBox, RadioButton
8) WPF Controls – CheckBox, DatePicker
Windows Presentation Foundation (WPF), a UI framework that is
resolution-independent and uses a vector-based rendering engine, built
to take advantage of modern graphics hardware.
WPF provides a comprehensive set of application-development
features that include Extensible Application Markup Language
(XAML), controls, data binding, layout, 2D and 3D graphics,
animation, styles, templates, documents, media, text, and typography.

WPF WPF is part of .NET, so you can build applications that incorporate
other elements of the .NET API.
WPF lets you develop an application using both markup and code-behind.
You generally use XAML markup to implement the appearance of an
application.
 while using managed programming languages (code-behind) to implement
its behavior.
This separation of appearance and behavior has the following benefits:
Mark-Up and 1. Development and maintenance costs are reduced because appearance-
Code Behind specific markup isn't tightly coupled with behavior-specific code.
2. Development is more efficient because designers can implement an
application's appearance simultaneously with developers who are
implementing the application's behavior.
3. Globalization and localization for WPF applications is simplified.
XAML is an XML-based markup language that implements an
application's appearance declaratively.
You typically use it to define windows, dialog boxes, pages, and user
controls, and to fill them with controls, shapes, and graphics.
The following example uses XAML to implement the appearance of a
window that contains a single button:

Mark-Up
Specifically, this XAML defines a window and a button by using
the Window and Button elements.
Each element is configured with attributes, such as the Window element’s
Title attribute to specify the window's title-bar text.
At run time, WPF converts the elements and attributes that are defined in
markup to instances of WPF classes.
For example, the Window element is converted to an instance of
Mark-Up the Window class whose Title property is the value of the Title attribute.
Figure below shows the user interface (UI) that is defined by the XAML
Since XAML is XML-based, the UI that you compose with it's assembled
in a hierarchy of nested elements that is known as an element tree.
The element tree provides a logical and intuitive way to create and manage
UIs.
The main behavior of an application is to implement the functionality that
responds to user interactions.
For example clicking a menu or button, and calling business logic and data
access logic in response.
In WPF, this behavior is implemented in code that is associated with
markup. This type of code is known as code-behind.
example below shows the updated markup from the previous example and
Code-Behind the code-behind
The updated markup defines the xmlns:x namespace and maps it to the
schema that adds support for the code-behind types.
The x:Class attribute is used to associate a code-behind class to this
specific XAML markup.
Considering this attribute is declared on the <Window> element, the code-
behind class must inherit from the Window class.

Code-Behind
Code-Behind
InitializeComponent is called from the code-behind class's constructor to
merge the UI that is defined in markup with the code-behind class.
(InitializeComponent is generated for you when your application is built,
which is why you don't need to implement it manually.)
The combination of x:Class and InitializeComponent ensure that your
implementation is correctly initialized whenever it's created.
Notice that in the markup the <Button> element defined a value
Code-Behind of button_click for the Click attribute.
With the markup and code-behind initialized and working together,
the Click event for the button is automatically mapped to
the button_click method.
When the button is clicked, the event handler is invoked and a message box
is displayed by calling the [Link] method.
InitializeComponent is called from the code-behind class's constructor to
merge the UI that is defined in markup with the code-behind class.
(InitializeComponent is generated for you when your application is built,
which is why you don't need to implement it manually.)
The combination of x:Class and InitializeComponent ensure that your
implementation is correctly initialized whenever it's created.
Notice that in the markup the <Button> element defined a value
Code-Behind of button_click for the Click attribute.
With the markup and code-behind initialized and working together,
the Click event for the button is automatically mapped to
the button_click method.
When the button is clicked, the event handler is invoked and a message box
is displayed by calling the [Link] method.
Output
Controls most often detect and respond to user input.
The WPF input system uses both direct and routed events to support text
input, focus management, and mouse positioning.
Applications often have complex input requirements.
WPF provides a command system that separates user-input actions from the
code that responds to those actions.
Input and The command system allows for multiple sources to invoke the same
Commands command logic.
For example, take the common editing operations used by different
applications: Copy, Cut, and Paste.
These operations can be invoked by using different user actions if they're
implemented by using commands.
When you create a user interface, you arrange your controls by location and
size to form a layout.
A key requirement of any layout is to adapt to changes in window size and
display settings.
Rather than forcing you to write the code to adapt a layout in these
circumstances, WPF provides a first-class, extensible layout system for
you.
The cornerstone of the layout system is relative positioning, which
Layout increases the ability to adapt to changing window and display conditions.
The layout system also manages the negotiation between controls to
determine the layout.
The negotiation is a two-step process: first, a control tells its parent what
location and size it requires. Second, the parent tells the control what space
it can have.
The layout system is exposed to child controls through base WPF classes.
For common layouts such as grids, stacking, and docking,
WPF includes several layout controls:

Canvas: Child controls provide their own layout.

DockPanel: Child controls are aligned to the edges of the panel.

Layout Grid: Child controls are positioned by rows and columns.

StackPanel: Child controls are stacked either vertically or horizontally.

 WrapPanel: Child controls are positioned in left-to-right order and


wrapped to the next line when there isn't enough space. on the current line.
1. Open Visual Studio.
2. Select Create a new project.

Creating a
WPF App
3. In the Search for templates box, type wpf, and then press Enter.
4. In the code language dropdown, choose C#.
5. In the templates list, select WPF Application and then select Next.

Creating a
WPF App
6. In the Configure your new project window, do the following:
I. In the Project name box, enter Names.
II. Select the Place solution and project in the same directory check box.
III. Optionally, choose a different Location to save your code.
IV. Select the Next button.

Creating a
WPF App
7. In the Additional information window, select .NET 6.0 (Long-term
support) for Target Framework. Select the Create button.

Creating a
WPF App
✓ Support for WPF in Visual Studio has five important components that
you'll interact with as you create an app:

Creating a
WPF App
✓ Create a WPF Application, where on clicking Button, the content of
TextBox, is added to ListBox.

Activity
✓ XAML, which stands for eXtensible Application Markup Language, is
Microsoft's variant of XML for describing a GUI.
✓ In previous GUI frameworks, like WinForms, a GUI was created in the
same language that you would use for interacting with the GUI, e.g. C#
or [Link] and usually maintained by the designer (e.g. Visual Studio),
✓ But with XAML, Microsoft is going another way. Much like with

Introduction
HTML, you are able to easily write and edit your GUI.
✓ It's such an essential part of WPF. Whether you're creating a Window or
to XAML a Page, it will consist of a XAML document and a CodeBehind file,
which together creates the Window/Page.
✓ The XAML file describes the interface with all its elements, while the
CodeBehind handles all the events and has access to manipulate with the
XAML controls.
✓ creating a control in XAML is as easy as writing it's name, surrounded
by angle brackets.
✓ For instance, a Button looks like this:<Button>
✓ XAML tags has to be ended, either by writing the end tag or by putting a
forward slash at the end of the start tag:
✓ Example <Button></Button> or <Button />

XAML ✓ A lot of controls allow you to put content between the start and end tags,
✓ which is then the content of the control.
✓ For instance, the Button control allows you to specify the text shown on
it between the start and end tags:
✓ Example:<Button> Click Me!</Button>
✓ HTML is not case-sensitive, but XAML is, because the control name has
to correspond to a type in the .NET framework.
✓ The same goes for attribute names, which corresponds to the properties
of the control.
✓ Here's a button where we define a couple of properties by adding
attributes to the tag:
✓ Example: <Button FontWeight="Bold" Content=“Click Me!" />

XAML ✓ However, all attributes of a control may also be defined like one shown
below, where they appear as child tags of the main control, using the
Control-Dot-Property notation:
✓ Example:
<Button>
<[Link]>Bold</[Link]>
<[Link]>Click Me!</[Link]>
</Button>
✓ However, a lot of controls allow content other than text, for instance
other controls.
✓ Here's an example where we have text in different colors on the same
button by using several TextBlock controls inside of the Button:
<Button>
<[Link]>Bold</[Link]>
<[Link]>
XAML <WrapPanel>
<TextBlock Foreground="Blue">Multi</TextBlock>
<TextBlock Foreground="Red">Color</TextBlock>
<TextBlock>Button</TextBlock>
</WrapPanel>
</[Link]>
</Button>
✓ The Content property only allows for a single child element, so we use a
WrapPanel to contain the differently colored blocks of text. Panels, like
the WrapPanel, plays an important role in WPF.
✓ Another of Writing the Same Code
<Button FontWeight="Bold">
<WrapPanel>

XAML <TextBlock Foreground="Blue">Multi</TextBlock>


<TextBlock Foreground="Red">Color</TextBlock>
<TextBlock>Button</TextBlock>
</WrapPanel>
</Button>
✓ Most modern UI frameworks are event driven and so is WPF.

✓ All of the controls, including the Window (which also inherits the
Control class) exposes a range of events that you may subscribe to.


Events in You can subscribe to these events, which means that your application
will be notified when they occur and you may react to that.
XAML
✓ There are many types of events, but some of the most commonly used
are there to respond to the user's interaction with your application using
the mouse or the keyboard.

✓ On most controls you will find events like KeyDown, KeyUp,


MouseDown, MouseEnter, MouseLeave, MouseUp and several others.
✓ to know how to link a control event in XAML to a piece of code in your
Code-behind file. Have a look at this example:

Events in
XAML
✓ Notice how we have subscribed to the Click event of the Button by
writing a method name.
✓ This method needs to be defined in code-behind, using the correct event
signature.

Events in
XAML
WPF
Architecture
✓ Managed Layer
✓ [Link]: This section contains high-level features like
application windows, panels, styles controls, layouts, content and so on
that helps us to build our application. It also implements the end-user
presentation features including data binding, time-dependencies,
animations and many more.

WPF
Architecture ✓ [Link]: This is a low-level API exposed by WPF providing
features for 2D, 3D, geometry and so on.

✓ [Link]: It holds the more basic elements that are capable to be


reused outside the WPF environment like Dispatcher objects and
Dependency objects.
✓ UnManaged Layer
✓ [Link]: The purpose of the milCore is to interface directly with
DirectX and provide basic support for 2D and 3D surface.

✓ This section is unmanaged code because it acts as a bridge between WPF


managed and the DirectX / User32 unmanaged API.
WPF
Architecture ✓ [Link]: WindowsCodecs is another low-level API for
imaging support in WPF applications like image processing, image
displaying and scaling and so on.

✓ It consists of a number of codecs that encode/decode images into vector


graphics that would be rendered into a WPF screen.
✓ Core Operating System Layer (Kernel)
✓ This layer has OS core components like User32, GDI, Device Drivers,
Graphic cards and so on. These components are used by the application
to access low-level APIs.
✓ DirectX: DirectX is the low-level API through which WPF renders all
graphics.

WPF
User32: User32 actually manages memory and process separation. It is
the primary core API that every application uses. User32 decides which
Architecture element will be placed where on the screen.
✓ GDI: GDI stands for Graphic Device Interface. GDI provides an
expanded set of graphics primitives and a number of improvements in
rendering quality.
✓ CLR: WPF leverages the full .NET Framework and executes on the
Common Language Runtime (CLR)
✓ Device Drivers: Device Drivers are specific to the operating system.
Device Drivers are used by the applications to access low-level APIs.
WPF WinForms
It is based on DirectX with XAML It provides access to the native windows
support. library of common controls.
It uses markup language for designing UI It does not use a markup language for
allowing the design of complex user design. In fact, it uses event-driven controls
interfaces. for the design.

WPF v/s
It can render fast as compared to
It renders slow as compared to WPF.
WinForms, complexity, and support.

WinForms It can be used to develop and design both


It can only be used to develop and design
windows applications and web
windows applications.
applications.
It has unlimited UI customization and
In this, controls are limited and difficult to
controls can be customized easily as it is
customize.
totally written from scratch.
It is easier to separate UI from back-end It is tough to separate UI from back-end
logic. logic.
It takes up more RAM than
It takes a smaller memory footprint.
WinForms.
It is considered good when the
It is considered good if you want to
application requires many media types,
develop an application without much
create a skinned UI, bind to XML,
added modern functionality, more
develop a desktop application having a
online resources.
web-like navigation style.
It also offers rich, interactive, animated, It does not offer any rich, Interactive,
WPF v/s hardware accelerated, vector 2D and
3D capabilities for developing
animated, hardware accelerated, vector
2D and 3D capabilities as compared to
WinForms applications. WPF.
It is simple to use WinForms as
It is a little bit tough, time-consuming,
controls can be used easily, it’s less
and complex to use WPF as compared
time-consuming and less tricky as
to WinForms.
compared to WPF.
It has an inbuilt story boarding feature
and animation model, it has the ability
It does not provide such features.
to use business objects in UI
declaratively.
✓ Layouts are the mechanism that WPF uses to define how visual items
will be displayed on the screen

✓ Proper layout and positioning are a vital part of interactive, high-


performance and user-friendly Windows applications.

✓ Layout is used to arrange a group of GUI elements in your application

Layouts
✓ Some of the most commonly used and popular layout panels are as
follows

❖ Stack Panel
❖ Wrap Panel
❖ Dock Panel
❖ Canvas Panel
❖ Grid Panel
✓ Arranges child elements into a single line that can be oriented
horizontally or vertically

✓ A StackPanel contains a collection of UIElement objects, which are in


the Children property.

✓ The default value is stretch for both HorizontalAlignment and


StackPanel VerticalAlignment of content that is contained in a StackPanel.

✓ Panel elements do not receive focus by default. To compel a panel


element to receive focus, set the Focusable property to true.

✓ If you require physical scrolling, wrap the host StackPanel element


ina ScrollViewer and set its CanContentScroll property to false.
✓ Example:
<Window x:Class="[Link]"
xmlns="[Link]
xmlns:x="[Link]
Title="MainWindow" Height="137.5" Width="300">
<StackPanel >

StackPanel <Button Name="Button1" Content="Button1" Width="140"/>


<Button Name="Button2" Content="Button2" Width="140"/>
<Button Name="Button3" Content="Button3" Width="140"/>
<Button Name="Button4" Content="Button4" Width="140"/>
<Button Name="Button5" Content="Button5" Width="140" />
</StackPanel>
</Window>
✓ Output

StackPanel
✓ Example:
<Window x:Class="[Link]"
xmlns="[Link]
xmlns:x="[Link]
Title="MainWindow" Height="137.5" Width="500">
<StackPanel Orientation="Horizontal">

StackPanel <Button Name="Button1" Content="Button1" Width="90"/>


<Button Name="Button2" Content="Button2" Width="90"/>
<Button Name="Button3" Content="Button3" Width="90"/>
<Button Name="Button4" Content="Button4" Width="90"/>
<Button Name="Button5" Content="Button5" Width="90" />
</StackPanel>
</Window>
✓ Output

StackPanel
✓ Positions child elements in sequential position from left to right,
breaking content to the next line at the edge of the containing box.

✓ Subsequent ordering happens sequentially from top to bottom or from


right to left, depending on the value of the Orientation property.

✓ A WrapPanel contains collection of UIElement objects, which are in


WrapPanel the Children property.

✓ All child elements of a WrapPanel receive the layout partition size


of ItemWidth multiplied by ItemHeight.
✓ Example:
<Window x:Class="[Link]"
xmlns="[Link]
xmlns:x="[Link]
Title="MainWindow" Height="150" Width="300">
<WrapPanel>

WrapPanel <Button Name="Button1" Content="Button1" Width="140"/>


<Button Name="Button2" Content="Button2" Width="140"/>
<Button Name="Button3" Content="Button3" Width="140"/>
<Button Name="Button4" Content="Button4" Width="140"/>
<Button Name="Button5" Content="Button5" Width="140" />
</WrapPanel>
</Window>
✓ Output

WrapPanel
✓ Example:
<Window x:Class="[Link]"
xmlns="[Link]
xmlns:x="[Link]
Title="MainWindow" Height="100" Width="300">
<WrapPanel Orientation="Vertical">

WrapPanel <Button Name="Button1" Content="Button1" Width="140"/>


<Button Name="Button2" Content="Button2" Width="140"/>
<Button Name="Button3" Content="Button3" Width="140"/>
<Button Name="Button4" Content="Button4" Width="140"/>
<Button Name="Button5" Content="Button5" Width="140" />
</WrapPanel>
</Window>
✓ Output

WrapPanel
✓ Defines an area where you can arrange child elements either horizontally or
vertically, relative to each other.

✓ A DockPanel contains a collection of UIElement objects, which are in


the Children property.

✓ The SetDock method changes the position of an element relative to other


elements within the same container.

DockPanel ✓ Alignment properties, such as HorizontalAlignment, change the position of


an element relative to its parent element.

✓ If you set the LastChildFill property to true, which is the default setting, the
last child element of a DockPanel always fills the remaining space,
regardless of any other dock value that you set on the last child element.

✓ To dock a child element in another direction, you must set


the LastChildFill property to false and must also specify an explicit dock
direction for the last child element.
✓ Example:
<Window x:Class="[Link]"
xmlns="[Link]
xmlns:x="[Link]
Title="MainWindow" Height="150" Width="525">
<DockPanel>

DockPanel <Button [Link]="Bottom" Name="Button1" Content="Button1"/>


<Button [Link]="Top" Name="Button2" Content="Button2" />
<Button [Link]="Left" Content="Button3" />
<Button [Link]="Right" Name="Button4" Content="Button4" />
<Button Name="Button5" Content="Button5" />
</DockPanel>
</Window>
✓ Output

DockPanel
✓ Defines an area within which you can explicitly position child elements by
using coordinates that are relative to the Canvas area.
✓ Canvas is the only panel element that has no inherent layout characteristics.
✓ A Canvas has default Height and Width properties of zero, unless it is the
child of an element that automatically sizes its child elements.
✓ Child elements of a Canvas are never resized, they are just positioned at their
designated coordinates.
✓ This provides flexibility for situations in which inherent sizing constraints or
alignment are not needed or wanted.
Canvas ✓ For cases in which you want child content to be automatically resized and
aligned, it is usually best to use a Grid element.
✓ The ZIndex property determines the order in which child elements that share
the same coordinate space appear.
✓ A higher ZIndex value for one child element indicates that this element will
appear above another child element that has a lower value.
✓ Child elements of a Canvas are always given the full size that they desire.
✓ As a result, vertical alignment and horizontal alignment have no effect inside
a Canvas.
✓ Canvas is a top-level layout control that you can use for absolute positioning
of child content.
✓ Example:
<Window x:Class="[Link]"
xmlns="[Link]
xmlns:x="[Link]
Title="MainWindow" Height="300" Width="200">
<Canvas >

Canvas
<Button Name="Button1" Content="Button1" [Link]="0" Width="90"/>
<Button Name="Button2" Content="Button2" [Link]="30" Width="90"/>
<Button Name="Button3" Content="Button3" [Link]="0" Width="90"/>
<Button Name="Button4" Content="Button4" [Link]="30"
Width="90"/>
<Button Name="Button5" Content="Button5" [Link]="100"
[Link]="0" Width="90" />
</Canvas>
</Window>
✓ Output

Canvas
✓ Defines a flexible grid area that consists of columns and rows.
✓ A Grid contains a collection of UIElement objects, which are in
the Children property.
✓ Columns and rows that are defined within a Grid can take advantage
of Star sizing to distribute remaining space proportionally.
✓ When Star is selected as the height or width of a row or column, that column
or row receives a weighted proportion of the remaining available space.
✓ This is in contrast to Auto, which distributes space evenly based on the size
of the content that is within a column or row.
✓ This value is expressed as * or 2* when you use Extensible Application
Markup Language (XAML).
Grid ✓ In the first case, the row or column would receive one times the available
space, while in the second case, the row or column would receive two times
the available space, and so on. By combining this technique to
proportionally distribute space with
a HorizontalAlignment and VerticalAlignment value of Stretch, it is possible
to partition layout space by percentage of screen space.
✓ Grid is the only layout panel that can distribute space in this manner.
✓ By default, rows and columns take up the least amount of space necessary to
accommodate the largest content within any cell contained in a given row or
column. For example, if a column has one cell with a long word like
"hippopotamus" contained within it but all the other cells in the column have
smaller words like "dog", the width of the column will be the width of the
largest word (hippopotamus).
✓ Example:
<Window x:Class="[Link]"
xmlns="[Link]
xmlns:x="[Link]
Title="MainWindow" Height="300" Width="200">
<Grid >
<[Link]>
<ColumnDefinition /> <ColumnDefinition />
</[Link]>
Grid <[Link]>
<RowDefinition/> <RowDefinition/>
</[Link]>
<Button Name="Button1" Content="Button1" />
<Button Name="Button2" Content="Button2" [Link]="1"/>
<Button Name="Button3" Content="Button3" [Link]="1"/>
<Button Name="Button4" Content="Button4" [Link]="1" [Link]="1"/>
</Grid>
</Window>
✓ Output

Grid
Controls Associated Default Event
Label -
TextBox TextChanged
TextBlock -
RadioButton Checked
CheckBox Checked
ComboBox SelectionChanged
Controls ListBox SelectionChanged
Button Click
Thanks

You might also like