Complete WPF Overview Tutorial with Example - iFour Technolab

Page 1

WPFConsultancy Overview iFour

https://www.ifourtechnolab.com/wpf-software-development


What is WPF?

❏ ❏ ❏ ❏ ❏

WPF, which stands for Windows Presentation Foundation, is Microsoft's latest approach to a GUI framework, used with the .NET framework. WPF , previously known as "Avalon", was initially released as part of .NET Framework 3.0 in 2006 , and then so many other features were added in the subsequent .NET framework versions. It is a powerful framework for building Windows applications. WPF offers Separation of Appearance and Behaviour. WPF contains features that will help you develop rich windows applications. WPF employs XAML, an XML-based language, to define and link various interface elements. WPF has a built-in set of data services to enable application developers to bind and manipulate data within applications

https://www.ifourtechnolab.com/wpf-software-development


Architecture of WPF

The major components of WPF architecture are as shown in the figure. The most important code part of WPF are −  Presentation Framework  Presentation Core  Milcore

The architecture of WPF can be classified into three layers,  Managed Layer  Unmanaged Layer  Core API Layer

Managed Layer 

The Presentation Framework : This DLL consists of all classes that are required to create the WPF UI. This wraps up the controls, data bindings, styling, shapes, media, documents, annotations, animation and more.

Presentation core : This is a low-level API exposed by WPF providing features for 2D, 3D, geometry and so on. https://www.ifourtechnolab.com/wpf-software-development


Unmanaged layer 

Milcore is a part of unmanaged code which allows tight integration with DirectX (responsible for display and rendering).

WindowsCodecs : WindowsCodecs provides Imaging support in WPF. Image display, processing, scaling and transform are all handled by WindowsCodecs

 CLR makes the development process more productive by offering many

features such as memory management, error handling, etc. Core API Layer 

This layer has OS core components like Kernel, User32, GDI, Device Drivers, Graphic cards etc. These components are used by the application to access low-level APIs. User32 manages memory and process separation.

DirectX : DirectX is the low-level API through which WPF renders all graphics. DirectX talks with drivers and renders the content.

GDI : GDI stands for Graphic Device Interface. GDI provides an expanded set of graphics primitives and a number of improvements in rendering quality. https://www.ifourtechnolab.com/wpf-software-development


WPF Advantages

 

  

In the earlier GUI frameworks, there was no real separation between how an application looks like and how it behaved. In WPF, UI elements are designed in XAML while behaviors can be implemented in procedural languages such C# and VB.Net. So it very easy to separate behavior from the designer code. With XAML, the programmers can work in parallel with the designers. The separation between a GUI and its behavior can allow us to easily change the look of a control by using styles and templates. Easier animation and special effects. Support rich data visualization. UIs are completely re-sizable without loss of quality.

https://www.ifourtechnolab.com/wpf-software-development


â?‘

WPF Features Feature

Description

Control inside a Control

Allows to define a control inside another control as a content.

Data binding

Mechanism to display and interact with data between UI elements and data object on user interface.

Media services

Provides an integrated system for building user interfaces with common media elements like images, audio, and video.

Templates

In WPF you can define the look of an element directly with a Template

Animations

Building interactivity and movement on user Interface

Alternative input

Supports multi-touch input on Windows 7 and above.

Direct3D

Allows to display more complex graphics and custom themes https://www.ifourtechnolab.com/wpf-software-development


XAMLConsultancy Overview iFour

https://www.ifourtechnolab.com/wpf-software-development


Index ❏

What is XAML?

Advantages of XAML

Basic Syntax of XAML

Namespaces

Why XAML in WPF

https://www.ifourtechnolab.com/wpf-software-development


What is XAML?

XAML stands for Extensible Application Markup Language

Its a simple language based on XML to create and initialize .NET objects with hierarchical relations.

Today XAML is used to create user interfaces in WPF, Silverlight, declare workflows in WF (Workflow Foundation) and for electronic paper in the XPS standard.

All classes in WPF have parameterless constructors and make excessive usage of properties. That is done to make it perfectly fit for XML languages like XAML.

https://www.ifourtechnolab.com/wpf-software-development


Advantage of XAML

It very easy to create, initialize, and set properties of objects with hierarchical relations.

XAML code is short and clear to read

Separation of designer code and logic

Graphical design tools like Expression Blend require XAML as source.

The goal of XAML is to enable visual designers to create user interface elements directly.

All you can do in XAML can also be done in code. XAML is just another way to create and initialize objects. You can use WPF without using XAML. It's up to you if you want to declare it in XAML or write it in code. https://www.ifourtechnolab.com/wpf-software-development


Basic Synatx of XAML

When you create your new WPF project, you will encounter some of the XAML code by default in MainWindow.xaml as shown below.

https://www.ifourtechnolab.com/wpf-software-development


Information

Description

<Window

It is the opening object element or container of the root.

x:Class = "Resources.MainWindow" It is a partial class declaration which connects the markup to the partial class code defined behind. xmlns =

Maps the default XAML namespace for WPF client/framework

xmlns:x =

XAML namespace for XAML language which maps it to x: prefix

>

End of object element of the root

<Grid></Grid>

It is starting and closing tags of an empty grid object.

</Window>

Closing the object element https://www.ifourtechnolab.com/wpf-software-development


Syntax

The syntax of an Object element starts with a left angle bracket (<) followed by the name of an object, e.g. Button.

Define some Properties and attributes of that object element.

The Object element must be closed by a forward slash (/) followed immediately by a right angle bracket (>).

https://www.ifourtechnolab.com/wpf-software-development


Syntax

Example of simple object with no child element <Button/>

Example of object element with some attributes <Button Content = "Click Me" Height = "30" Width = "60" />

</StackPanel>

https://www.ifourtechnolab.com/wpf-software-development


Syntax

Example of an alternate syntax do define properties (Property element syntax) <Button> <Button.Content>Click Me</Button.Content> <Button.Height>30</Button.Height> <Button.Width>60</Button.Width> </Button>

Example of Object with Child Element: StackPanel contains Textblock as child element <StackPanel Orientation = "Horizontal"> <TextBlock Text = "Hello"/> </StackPanel> https://www.ifourtechnolab.com/wpf-software-development


Namespaces

At the beginning of every XAML file you need to include two namespaces.

The first is http://schemas.microsoft.com/winfx/2006/xaml/presentation. It is mapped to all wpf controls in System.Windows.Controls.

The second is http://schemas.microsoft.com/winfx/2006/xaml it is mapped to System.Windows.Markup

that defines the XAML keywords.

https://www.ifourtechnolab.com/wpf-software-development


Why XAML in WPF?

Both XAML & WPF are independent pieces of technology.

For better Understanding, let us create a window with a button in it using XAML as below :

https://www.ifourtechnolab.com/wpf-software-development


â??

Output :

https://www.ifourtechnolab.com/wpf-software-development


â??

In case you choose not to use XAML in WPF, then you can achieve the same GUI result with procedural language as well. Let’s have a look at the same example, but this time, we will create a button in C#

https://www.ifourtechnolab.com/wpf-software-development


From the above example, it is clear that what you can do in XAML to create, initialize, and set properties of objects, the same tasks can also be done using code.

So below are the two less known facts about XAML : ❏

WPF doesn't need XAML

XAML doesn't need WPF

https://www.ifourtechnolab.com/wpf-software-development


Element Tree iFour Consultancy

https://www.ifourtechnolab.com/wpf-software-development


Element Tree

Windows Presentation Foundation (WPF) has a comprehensive tree structure in the form of objects. In WPF, there are two ways that a complete object tree is conceptualized −

Logical Tree Structure

Visual Tree Structure

There are many technologies where the elements and components are ordered in a tree structure so that the programmers can easily handle the object and change the behavior of an application.

Mostly, WPF developers and designers either use procedural language to create an application or design the UI part of the application in XAML keeping in mind the object tree structure.

https://www.ifourtechnolab.com/wpf-software-development


Logical Tree Structure

In WPF applications, the structure of the UI elements in XAML represents the logical tree structure. In XAML, the basic elements of UI are declared by the developer. The logical tree in WPF defines the following − ❏

Dependency properties

Static and dynamic resources

Binding the elements on its name etc.

https://www.ifourtechnolab.com/wpf-software-development


â??

Let’s have a look at the following example in which a button and a list box are created.

https://www.ifourtechnolab.com/wpf-software-development


Visual Tree Structure

In WPF, the concept of the visual tree describes the structure of visual objects, as represented by the Visual Base Class. It signifies all the UI elements which are rendered to the output screen.

When a programmer wants to create a template for a particular control, he is actually rendering the visual tree of that control. The visual tree is also very useful for those who want to draw lower level controls for performance and optimization reasons.

In WPF applications, visual tree is used for − ❏

Rendering the visual objects.

Rendering the layouts.

The routed events mostly travel along the visual tree, not the logical tree.

https://www.ifourtechnolab.com/wpf-software-development


Visual Tree Structure

In WPF, the concept of the visual tree describes the structure of visual objects, as represented by the Visual Base Class. It signifies all the UI elements which are rendered to the output screen.

When a programmer wants to create a template for a particular control, he is actually rendering the visual tree of that control. The visual tree is also very useful for those who want to draw lower level controls for performance and optimization reasons.

In WPF applications, visual tree is used for − ❏

Rendering the visual objects.

Rendering the layouts.

The routed events mostly travel along the visual tree, not the logical tree.

https://www.ifourtechnolab.com/wpf-software-development


https://www.ifourtechnolab.com/wpf-software-development


https://www.ifourtechnolab.com/wpf-software-development


The logical tree leaves out a lot of detail enabling you to focus on the core structure of the user interface and to ignore the details of exactly how it has been presented.

The logical tree is what you use to create the basic structure of the user interface.

The visual tree will be of interest if you're focusing on the presentation. For example, if you wish to

customize the appearance of any UI element, you will need to use the visual tree.

https://www.ifourtechnolab.com/wpf-software-development


Layout iFour Consultancy

https://www.ifourtechnolab.com/wpf-software-development


Layout

The layout of controls is very important and critical for application usability. It is used to arrange a group

of GUI elements in your application. There are certain important things to consider while selecting layout panels −

Positions of the child elements

Sizes of the child elements

Layering of overlapping child elements on top of each other

Fixed pixel arrangement of controls doesn’t work when the application is to be sed on different screen

resolutions. XAML provides a rich set of built-in layout panels to arrange GUI elements in an appropriate way. Some of the most commonly used and popular layout panels are as follows − https://www.ifourtechnolab.com/wpf-software-development


Sr. No. Panels & Description

1

Stack panel is a simple and useful layout panel in XAML. In stack panel, child elements can be arranged in a single line, either horizontally or vertically, based on the orientation property.

2

In WrapPanel, child elements are positioned in sequential order, from left to right or from top to bottom based on the orientation property.

3

DockPanel defines an area to arrange child elements relative to each other, either horizontally or vertically. With DockPanel you can easily dock child elements to top, bottom, right, left and center using the Dock property.

https://www.ifourtechnolab.com/wpf-software-development


Sr. No.

Panels & Description

4

Canvas panel is the basic layout panel in which the child elements can be positioned explicitly using coordinates that are relative to the Canvas any side such as left, right, top and bottom.

5

A Grid Panel provides a flexible area which consists of rows and columns. In a Grid, child elements can be arranged in tabular form.

https://www.ifourtechnolab.com/wpf-software-development


Nested Layout iFour Consultancy

https://www.ifourtechnolab.com/wpf-software-development


Nesting layout ď ą

Nesting of layout means the use layout panel inside another layout, e.g. define stack panels inside a grid. This concept is widely used to take the advantages of multiple layouts in an application.

https://www.ifourtechnolab.com/wpf-software-development


ď ą

Considering example of real world wherein we used grid layout for outlining and used stackpanel to display controls inside it.

https://www.ifourtechnolab.com/wpf-software-development


Output –

https://www.ifourtechnolab.com/wpf-software-development


iFourControls Consultancy

https://www.ifourtechnolab.com/wpf-software-development


Controls 

Windows Presentation Foundation (WPF) allows developers to easily build and create visually enriched UI based applications.  The classical UI elements or controls in other UI frameworks are also enhanced in WPF applications.  All of the standard WPF controls can be found in the Toolbox which is a part of the System.Windows.Controls.  These controls can also be created in XAML markup language.

https://www.ifourtechnolab.com/wpf-software-development


Control Library      

Grid Layout Label Buttons Editors Lists Menus and toolbars Scroll Viewer

Building Blocks  ToolTip  Thumb  Border  Popup  Document Viewers  Frame  Ranges  Containers

https://www.ifourtechnolab.com/wpf-software-development


Grid Layout 

  

Grid Column Definition Row Definition Grid Lines

https://www.ifourtechnolab.com/wpf-software-development


Labels ď ą

The Label control, in its most simple form, will look very much like the TextBlock which we used in another article. You will quickly notice though that instead of a Text property, the Label has a Content property. The reason for that is that the Label can host any kind of control directly inside of it, instead of just text.

<Label Content="This is a Label control." />

https://www.ifourtechnolab.com/wpf-software-development


Buttons

https://www.ifourtechnolab.com/wpf-software-development


Editors 

  

PasswordBox TextBox RichTextBox InkCanvas

https://www.ifourtechnolab.com/wpf-software-development


List 

Four standard list controls- ListBox, ComboBox, ListView, TreeView. List controls can be filled from one of the two sources. 1. Items Property 2. ItemsSource Property.

https://www.ifourtechnolab.com/wpf-software-development


List View 

 

List view derives from listBox It has ability to separate view properties from control properties. View property must be changed to grid view ad set properties on that object.

https://www.ifourtechnolab.com/wpf-software-development


Tree view <TreeView> <TreeViewItem Header='Coders'> <TreeViewItem Header='Don' /> <TreeViewItem Header='Dharma' /> </TreeViewItem> <TreeViewItem Header='Noncoders'> <TreeViewItem Header='Chris' /> </TreeViewItem> </TreeView>

https://www.ifourtechnolab.com/wpf-software-development


New Lists using Templates

https://www.ifourtechnolab.com/wpf-software-development


Menus & ToolBars

https://www.ifourtechnolab.com/wpf-software-development


Expander 

Expander is a layout in which we can add control and expand it when we need. When have less space in our application then we can use expander layout. We can assign the expand direction either down, up, left or right. At the time of expander creation we can assign IsExpanded property true or false. It has the same drawback as GroupBox that it can contain only one control.

<Window x:Class="GroupBoxDemo.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/present ation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="GroupBox Demo" Width="250" Height="180"> <Grid> <Expander Header=“Description" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" IsExpanded="False" Height="299" Width="497"> <TextBlock TextWrapping="Wrap" Text="This is some text content." Margin="5"/> </Expander> </Grid> </Window>

https://www.ifourtechnolab.com/wpf-software-development


Group Box 

<Window x:Class="GroupBoxDemo.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="GroupBox Demo" Width="250" Height="180"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions>

The GroupBox control allows you to visually group content and provide a title for grouped elements. When you use the default styling for a GroupBox, the child controls are surrounded by a border that includes a caption. There is no <GroupBox Header="Mouse Handedness"> need to explicitly define a Border. <StackPanel> <RadioButton Content="Left-Handed" Margin="5"/> Configuring a GroupBox is similar to setting up <RadioButton Content="Right-Handed" Margin="5" an Expander. Both controls inherit from the IsChecked="True"/> </StackPanel> same base class and include the same </GroupBox> properties for controlling the header area and <GroupBox Grid.Row="1" Header="Double Click Speed"> <Slider Margin="5" /> content. The key difference is that a GroupBox </GroupBox> does not add the user interaction that permits </Grid> </Window> the content to be expanded and collapsed. https://www.ifourtechnolab.com/wpf-software-development


Separator   

The Separator Control is used to separate items in items controls. The intention is to divide the items on the menu or toolbar into logical groups. It uses borders and rectangles.

<ListBox> <ListBoxItem>Sports Car</ListBoxItem> <ListBoxItem>Compact Car</ListBoxItem> <ListBoxItem>Family Car</ListBoxItem>

<ListBoxItem>Off-Road Car</ListBoxItem> <Separator/> <ListBoxItem>Supersports Bike</ListBoxItem> <ListBoxItem>Sports Tourer</ListBoxItem> <ListBoxItem>Cruiser</ListBoxItem> </ListBox>

https://www.ifourtechnolab.com/wpf-software-development


TabControl 

The WPF TabControl allows you to split your interface up into different areas, each accessible by clicking on the tab header, usually positioned at the top of the control.

<Window x:Class="WpfTutorialSamples.Misc_controls.TabControlSample“ xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="TabControlSample" Height="200" Width="250"> <Grid> <TabControl> <TabItem Header="General"> <Label Content="Content goes here..." /> </TabItem> <TabItem Header="Security" /> <TabItem Header="Details" /> </TabControl> </Grid>

</Window>

https://www.ifourtechnolab.com/wpf-software-development


Dialog  Standalone applications typically have a main window that both displays the main data over which the application operates and

exposes the functionality to process that data through user interface (UI) mechanisms like menu bars, tool bars, and status bars. A non-trivial application may also display additional windows to do the following:  Display specific information to users.  Gather information from users.

 Both display and gather information.  These types of windows are known as dialog boxes, and there are two types: modal and modeless.

https://www.ifourtechnolab.com/wpf-software-development


 A modal dialog box is displayed by a function when the

function needs additional data from a user to continue. Because the function depends on the modal dialog box to gather data

 A modeless dialog box, on the other hand, does not prevent

a user from activating other windows while it is open.  For example, if a user wants to find occurrences of a

particular word in a document, a main window will often open a dialog box to ask a user what word they are looking for.

 the modal dialog box also prevents a user from activating

other windows in the application while it remains open.  In most cases, a modal dialog box allows a user to signal

when they have finished with the modal dialog box by pressing either an OK or Cancel button.  Pressing the OK button indicates that a user has entered

data and wants the function to continue processing with that data.

Since finding a word doesn't prevent a user from editing the document, however, the dialog box doesn't need to be modal.

 A modeless dialog box at least provides a Close button to

close the dialog box.

 Pressing the Cancel button indicates that a user wants to

stop the function from executing altogether

https://www.ifourtechnolab.com/wpf-software-development


Dialog-Message box   

A message box is a dialog box that can be used to display textual information and to allow users to make decisions with buttons. To create a message box, you use the MessageBox class. MessageBox lets you configure the message box text, title, icon, and buttons, using code like the following. The following figure shows a message box that displays textual information, asks a question, and provides the user with three buttons to answer the question.

string messageBoxText = "Do you want to save changes?"; string caption = "Word Processor"; MessageBoxButton button = MessageBoxButton.YesNoCancel; MessageBoxImage icon = MessageBoxImage.Warning; // Display message box MessageBox.Show(messageBoxText, caption, button, icon);

https://www.ifourtechnolab.com/wpf-software-development


Message box(cont..) // Display message box MessageBoxResult result = MessageBox.Show(messageBoxText, caption, button, icon);

// Process message box results switch (result) { case MessageBoxResult.Yes: // User pressed Yes button break;

case MessageBoxResult.No: // User pressed No button // ... break; case MessageBoxResult.Cancel: // User pressed Cancel button

// ... break; }

https://www.ifourtechnolab.com/wpf-software-development


Other Common Dialog Boxes are Open File Dialog  Save File Dialog Box  Print Dialog Box 

A modeless dialog box, such as the Find Dialog Box shown in the following figure, has the same fundamental appearance as the modal dialog box.

Screenshot that shows a Find dialog box.

However, the behavior is slightly different, as described in the following sections.

 

A modeless dialog box is opened by calling the Show method. Unlike ShowDialog, Show returns immediately. Consequently, the calling window cannot tell when the modeless dialog box is closed and, therefore, does not know when to check for a dialog box result or get data from the dialog box for further processing. Instead, the dialog box needs to create an alternative way to return data to the calling window for processing.

https://www.ifourtechnolab.com/wpf-software-development


Window 

Window is the root window of XAML applications which provides minimize/maximize option, title bar, border, and close button.

It also provides the ability to create, configure, show, and manage the lifetime of windows and dialog boxes.

When you create a new WPF project, then by default, the Window control is present.

<Window x:Class="GroupBoxDemo.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentatio n" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="GroupBox Demo" Width="250" Height="180"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <GroupBox Header="Mouse Handedness"> <StackPanel> <RadioButton Content="Left-Handed" Margin="5"/> <RadioButton Content="Right-Handed" Margin="5" IsChecked="True"/> </StackPanel> </GroupBox> <GroupBox Grid.Row="1" Header="Double Click Speed"> <Slider Margin="5" /> </GroupBox> </Grid> </Window>

https://www.ifourtechnolab.com/wpf-software-development


Context Menu

ď ą

A context menu, often referred to as a popup or pop-up menu, is a menu which is shown upon certain user actions,

usually a right-click with the mouse on a specific control or window. ď ą

Contextual menus are often used to offer functionality that's relevant within a single control.

https://www.ifourtechnolab.com/wpf-software-development


<RichTextBox> <RichTextBox.ContextMenu> <ContextMenu>

<MenuItem Command="Cut"> <MenuItem.Icon> <Image Source="Images/cut.png" /> </MenuItem.Icon> </MenuItem> <MenuItem Command="Copy"> <MenuItem.Icon>

<Image Source="Images/copy.png" /> </MenuItem.Icon> </MenuItem> <MenuItem Command="Paste"> <MenuItem.Icon> <Image Source="Images/paste.png" /> </MenuItem.Icon>

</MenuItem> </ContextMenu> </RichTextBox.ContextMenu> </RichTextBox>

https://www.ifourtechnolab.com/wpf-software-development


Third-party controls ď ą

Third-party controls are those which are not created

by Microsoft but are created by some individual or company by using WPF User Control or Custom Control. Telerik and DevExpress are the most popular companies for creating third-party controls.

https://www.ifourtechnolab.com/wpf-software-development


<Window x:Class = "WPF3rdPartyControls.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"

xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local = "clr-namespace:WPF3rdPartyControls" xmlns:telerik = "http://schemas.telerik.com/2008/xaml/presentation" mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "604">

<Grid>

<telerik:RadCalculator HorizontalAlignment = "Left" Margin = "174,25,0,0" VerticalAlignment = "Top" /> </Grid>

</Window>

https://www.ifourtechnolab.com/wpf-software-development


Calendar ⚍

⚍

Calendar is a control that enables a user to select a date by using a visual calendar display. It provides some basic navigation using either the mouse or keyboard

https://www.ifourtechnolab.com/wpf-software-development


Cont.….

https://www.ifourtechnolab.com/wpf-software-development


Date picker ⚍

A Date Picker is a control that allows a user to pick a date value.

⚍

The user picks the date by using Combo Box selection for month, day, and year values

https://www.ifourtechnolab.com/wpf-software-development


Cont.‌. Properties Date

Gets or sets the date currently set in the date picker.

DayFormat

Gets or sets the display format for the day value.

DayFormatProperty

Gets the identifier for the DayFormat dependency property.

Orientation

Gets or sets a value that indicates whether the day, month, and year selectors are stacked horizontally or vertically.

YearFormat

Gets or sets the display format for the year value.

MonthFormat

Gets or sets the display format for the month value.

https://www.ifourtechnolab.com/wpf-software-development


Image ⚍

⚍

A control that displays an image, you can use either the Image object or the Image Brush object. An Image object display an image, while an Image Brush object paints another object with an image.

https://www.ifourtechnolab.com/wpf-software-development


Cont.‌. Properties wSource

Gets or sets the source for the image.

Width

Gets or sets the width of a FrameworkElement. (Inherited from FrameworkElement)

StretchProperty

Identifies the Stretch dependency property.

Opacity

Gets or sets the degree of the object's opacity. (Inherited from UIElement)

Name

Gets or sets the identifying name of the object.

CanDrag

Gets or sets a value that indicates whether the element can be dragged as data in a drag-anddrop operation. (Inherited from UIElement)

https://www.ifourtechnolab.com/wpf-software-development


Popup ⚍

⚍

Popup is a control that displays content on top of existing content, within the bounds of the application window. It is a temporary display on other content.

https://www.ifourtechnolab.com/wpf-software-development


Cont.‌. Properties Child

Gets or sets the content to be hosted in the popup.

ChildProperty

Gets the identifier for the Child dependency property.

IsOpen

Gets or sets whether the popup is currently displayed on the screen.

Opacity

Gets or sets the degree of the object's opacity. (Inherited from UIElement)

Name

Gets or sets the identifying name of the object.

https://www.ifourtechnolab.com/wpf-software-development


Progress Bar ⚫

Progress Bar is a control that indicates the progress of an operation, where the typical visual appearance is a bar that animates a filled area as the progress continues.

It can show the progress in one of the two following styles − ⚫ ⚫

A bar that displays a repeating pattern, or A bar that fills based on a value.

https://www.ifourtechnolab.com/wpf-software-development


Cont.‌. Properties IsIndeterminate

Gets or sets a value that indicates whether the progress bar reports generic progress with a repeating pattern or reports progress based on the Value property.

ShowError

Gets or sets a value that indicates whether the progress bar should use visual states that communicate an Error state to the user.

ShowPaused

Gets or sets a value that indicates whether the progress bar should use visual states that communicate a Paused state to the user.

Name

Gets or sets the identifying name of the object.

https://www.ifourtechnolab.com/wpf-software-development


Scroll Viewer ⚍

A ScrollViewer is a control that provides a scrollable area that can contain other visible elements.

https://www.ifourtechnolab.com/wpf-software-development


Cont.‌. Properties ComputedHorizontalScrollBarVisibility

Gets a value that indicates whether the horizontal ScrollBar is visible.

ComputedHorizontalScrollBarVisibilityProper ty

Identifies the ComputedHorizontalScrollBarVisibility dependency property.

ScrollableHeight

Gets a value that represents the vertical size of the area that can be scrolled; the difference between the width of the extent and the width of the viewport.

Name

Gets or sets the identifying name of the object.

ScrollableWidth

Gets a value that represents the horizontal size of the area that can be scrolled; the difference between the width of the extent and the width of the viewport.

https://www.ifourtechnolab.com/wpf-software-development


Toggle Button ⚍

A Toggle Button is a control that can switch states, such as CheckBox and RadioButton. .

https://www.ifourtechnolab.com/wpf-software-development


Cont.‌. Properties IsChecked

Gets or sets whether the ToggleButton is checked.

IsCheckedProperty

Identifies the IsChecked dependency property.

IsThreeState

Gets or sets a value that indicates whether the control supports three states

Name

Gets or sets the identifying name of the object.

IsThreeStateProperty

Identifies the IsThreeState dependency property.

https://www.ifourtechnolab.com/wpf-software-development


tooltip ⚍

A tooltip is a control that creates a pop-up window that displays information for an element in the GUI.

https://www.ifourtechnolab.com/wpf-software-development


Cont.‌. Properties IsOpen

Gets or sets a value that indicates whether the ToolTip is visible.

Placement

Gets or sets how a ToolTip is positioned in relation to the placement target element.

PlacementTarget

Gets or sets the visual element or control that the tool tip should be positioned in relation to when opened by the ToolTipService.

Name

Gets or sets the identifying name of the object.

https://www.ifourtechnolab.com/wpf-software-development


Dependency Property iFour Consultancy

https://www.ifourtechnolab.com/wpf-software-development


Dependency Property

In WPF applications, Dependency property is a specific type of property which extends the CLR property. It takes the advantage of specific functionalities available in the WPF property system.

A class which defines a dependency property must be inherited from the DependencyObject class.

Many of the UI controls class which are used in XAML are derived from the DependencyObject class and they support dependency properties, e.g. Button class supports the IsMouseOver dependency property.

https://www.ifourtechnolab.com/wpf-software-development


Dependency Property (Cont...)

â?‘

â??

The following XAML code creates a button with some properties.

<Window x:Class = "WPFDependencyProperty.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local = "clr-namespace:WPFDependencyProperty" Title = "MainWindow" Height = "350" Width = "604"> <Grid> <Button Height = "40" Width = "175" Margin = "10" Content = "Dependency Property"> <Button.Style> <Style TargetType = "{x:Type Button}"> <Style.Triggers> <Trigger Property = "IsMouseOver" Value = "True"> <Setter Property = "Foreground" Value = "Red" /> </Trigger> </Style.Triggers> </Style> </Button.Style> </Button> </Grid> </Window>

https://www.ifourtechnolab.com/wpf-software-development


https://www.ifourtechnolab.com/wpf-software-development


Why We Need Dependency Properties

Dependency property gives you all kinds of benefits when you use it in your application. Dependency Property can used over a CLR property in the following scenarios − ❏

If you want to set the style

If you want data binding

If you want to set with a resource (a static or a dynamic resource)

If you want to support animation

https://www.ifourtechnolab.com/wpf-software-development


Why We Need Dependency Properties

Basically, Dependency Properties offer a lot of functionalities that you won’t get by using a CLR property.

The main difference between dependency properties and other CLR properties are listed below − ❏

CLR properties can directly read/write from the private member of a class by using getter and setter. In contrast, dependency properties are not stored in local object.

Dependency properties are stored in a dictionary of key/value pairs which is provided by the DependencyObject class. It also saves a lot of memory because it stores the property when changed. It can be bound in XAML as well. https://www.ifourtechnolab.com/wpf-software-development


Routed Event iFour Consultancy

https://www.ifourtechnolab.com/wpf-software-development


Routed Event

A Routed Event is a type of event that can invoke handlers on multiple listeners in an element tree rather than just the object that raised the event. It is basically a CLR event that is supported by an instance of the Routed Event class. It is registered with the WPF event system.

RoutedEvents have three main routing strategies which are as follows − ❏

Direct Event

Bubbling Event

Tunnel Event

https://www.ifourtechnolab.com/wpf-software-development


Bubbling Event

A Bubbling Event begins with the element where the event is originated.

Then it travels up the visual tree to the topmost element in the visual tree.

So, in WPF, the topmost element is most likely a window.

https://www.ifourtechnolab.com/wpf-software-development


Tunnel Event

Event handlers on the element tree root are invoked and then the event travels down the visual tree to all the children nodes until it reaches the element in which the event originated.

The difference between a bubbling and a tunneling event is that a tunneling event will always start with a preview.

In a WPF application, events are often implemented as a tunneling/bubbling pair. So, you'll have a preview MouseDown and then a MouseDown event.

https://www.ifourtechnolab.com/wpf-software-development


Direct Event

A Direct Event is similar to events in Windows forms which are raised by the element in which the event is originated.

Unlike a standard CLR event, direct routed events support class handling and they can be used in

Event Setters and Event Triggers within your style of your Custom Control. ❏

A good example of a direct event would be the MouseEnter Event.

https://www.ifourtechnolab.com/wpf-software-development


Input And Data Binding iFour Consultancy

https://www.ifourtechnolab.com/wpf-software-development


ď ą

Windows Presentation Foundation (WPF) provides a powerful API with the help of which applications can get input from various devices such as mouse, keyboard, and touch panels.

ď ą

Data binding is the process that establishes a connection between the application UI and business logic. If the binding has the correct settings and the data provides the proper notifications, then, when the data changes its value, the elements that are bound to the data reflect changes automatically

https://www.ifourtechnolab.com/wpf-software-development


 

Binding data to UI Elements Using Converters to convert data during Binding Using Data Templates to visualize data

https://www.ifourtechnolab.com/wpf-software-development


Binding Components  Target Object  Target Property  Binding Source  Path Target Property Must be a dependency property

https://www.ifourtechnolab.com/wpf-software-development


 

OneWay-Updates the target property only when the source property change. TwoWay-Updates the target property or the property whenever either the target property or the source property changes. OneWayToSource-updates the source property when the target property changes OneTime- Updates the target property only when the application starts or when the DataContext undergoes a change.

https://www.ifourtechnolab.com/wpf-software-development


 

Triggering supported by TwoWay or OneWayToSource mode of binding Dependency property or INotifyPropertyChanged UpdateSourceTrigger property  Explicit -Updates the binding source only when you call.  UpdateSource- method.  LostFocus-Updates the binding source whenever the binding target element loses

https://www.ifourtechnolab.com/wpf-software-development


Binding using XAML Binding using Code

<Label Name="lblNote" Content="{DynamicResource ResourceKey=Note}" /> <TextBox Name="txtNote" VerticalContentAlignment="Top" HorizontalAlignment="Stretch" Text="{Binding AppointmentNote,Mode=TwoWay}" VerticalAlignment="Stretch" Width="Auto" Height="Auto" /> MyData myDataObject = new MyData(DateTime.Now); Binding myBinding = new Binding("MyDataProperty"); myBinding.Source = myDataObject; myText.SetBinding(TextBlock.TextProperty, myBinding);

https://www.ifourtechnolab.com/wpf-software-development


Used when data doesn’t match between bindings create a conversion class When to use  Culture changes needed  Different View of data then native storage  Incompatible data types between target and source

https://www.ifourtechnolab.com/wpf-software-development


Contained in the System.Windows.Controls namespace BooleanToVisibilityConverter  Converts True/False to Visible, Hidden or Collapsed BorderGapMaskConverter  Represents a converter that converts the dimensions of a GroupBox control into a VisualBrush

https://www.ifourtechnolab.com/wpf-software-development


 

Makes it easy to put content with data Easy to define visual styles for data Reusable and modifiable

https://www.ifourtechnolab.com/wpf-software-development


StylesConsultancy And Triggers iFour

https://www.ifourtechnolab.com/wpf-software-development


Styles

❏ ❏

❏ ❏

The .NET framework provides several strategies to personalize and customize the appearance of an application. Style gives uniformity to our application and improves user UI experience. Styles provide us the flexibility to set some properties of an object and reuse these specific settings across multiple objects for a consistent look. In styles, you can set only the existing properties of an object such as Height, Width, Font size, etc. Only default behavior of a control can be specified. Multiple properties can be added into a single style.

https://www.ifourtechnolab.com/wpf-software-development


Scenario

As you can see in first image, Width and Height properties of each button is set. It is tedious to set property of each button like this to maintain uniformity. And this is not the case only for buttons as there will be many more elements. It is not feasible to give style like this. Rather what we can do is, declare a style for particular element by setting properties of that control. Just like it is done in second image. Sounds more efficient. Right? Let’s see an example.

https://www.ifourtechnolab.com/wpf-software-development


â?‘

Example

<Window x:Class = "XAMLStyle.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local = "clr-namespace:XAMLStyle" mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "604"> <Window.Resources> <Style x:Key = "myButtonStyle" TargetType = "Button"> <Setter Property = "Height" Value = "30" /> <Setter Property = "Width" Value = "80" /> <Setter Property = "Foreground" Value = "Blue" /> <Setter Property = "FontSize" Value = "12" /> <Setter Property = "Margin" Value = "10" /> </Style> </Window.Resources> <StackPanel> <Button Content = "Button1" Style = "{StaticResource myButtonStyle}" /> <Button Content = "Button2" Style = "{StaticResource myButtonStyle}" /> <Button Content = "Button3" Style="{StaticResource myButtonStyle}" /> </StackPanel>

</Window>

https://www.ifourtechnolab.com/wpf-software-development


Explanation

 Styles are defined in the resource dictionary and each style has a unique key identifier and a target type.

 Inside <style> you can see that multiple setter tags are defined for each property which will be included in the style.  All of the common properties of each button are now defined in style and then the style are assigned to

each button with a unique key by setting the style property through the StaticResource markup extension.  The advantage of doing it like this is immediately obvious, we can reuse that style anywhere in its scope; and if we need to change it, we simply change it once in the style definition instead of on each element.

https://www.ifourtechnolab.com/wpf-software-development


Style Levels

â?‘

Sr.No

Levels & Description

1

Control Level Defining a style on control level can only be applied to that particular control. Given below is an example of a control level where the button and TextBlock have their own style.

2

Layout Level Defining a style on any layout level will make it accessible by that layout and its child elements only.

3

Window Level Defining a style on a window level can make it accessible by all the elements on that window.

4

Application Level Defining a style on app level can make it accessible throughout the entire application. Let’s take the same example, but here, we will put the styles in app.xaml file to make it accessible throughout application.

https://www.ifourtechnolab.com/wpf-software-development


Triggers   

A trigger basically enables you to change property values or take actions based on the value of a property. So, it allows you to dynamically change the appearance and/or behavior of your control without having to create a new one. Triggers are used to change the value of any given property, when certain conditions are satisfied. Triggers are usually defined in a style or in the root of a document which are applied to that specific control.

https://www.ifourtechnolab.com/wpf-software-development


Types Of Triggers 

There are three types of triggers  

Property Triggers Data Triggers Event Triggers

https://www.ifourtechnolab.com/wpf-software-development


Property Triggers ď ą In property triggers, when a change occurs in one property, it will bring either an immediate or an animated change in another

property. ď ą For example, you can use a property trigger to change the appearance of a button when the mouse hovers over the button. <Window x:Class = "WPFPropertyTriggers.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "MainWindow" Height = "350" Width = "604"> <Window.Resources> <Style x:Key = "TriggerStyle" TargetType = "Button"> <Setter Property = "Foreground" Value = "Blue" /> <Style.Triggers> <Trigger Property = "IsMouseOver" Value = "True"> <Setter Property = "Foreground" Value = "Green" /> </Trigger> </Style.Triggers> </Style> </Window.Resources> <Grid> <Button Width = "100" Height = "70" Style = "{StaticResource TriggerStyle}" Content = "Trigger"/> </Grid> </Window>

https://www.ifourtechnolab.com/wpf-software-development


Data Triggers  A data trigger performs some actions when the bound data satisfies some conditions.  For example, There is checkbox and label. When the checkbox is checked, it will change label’s foreground color to red. <Window x:Class = "WPFDataTrigger.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "Data Trigger" Height = "350" Width = "604"> <StackPanel HorizontalAlignment = "Center"> <CheckBox x:Name = "redColorCheckBox" Content = "Set red as foreground color" Margin = "20"/> <TextBlock Name = "txtblock" VerticalAlignment = "Center" Text = "Event Trigger" FontSize = "24" Margin = "20"> <TextBlock.Style> <Style> <Style.Triggers> <DataTrigger Binding = "{Binding ElementName = redColorCheckBox, Path = IsChecked}" Value = "true"> <Setter Property = "TextBlock.Foreground" Value = "Red"/> <Setter Property = "TextBlock.Cursor" Value = "Hand" /> </DataTrigger> </Style.Triggers> </Style> </TextBlock.Style> </TextBlock> </StackPanel> </Window>

https://www.ifourtechnolab.com/wpf-software-development


Event Triggers  A data trigger performs some actions when the bound data satisfies some conditions.  For example, There is checkbox and label. When the checkbox is checked, it will change label’s foreground color to red. <Window x:Class = "WPFEventTrigger.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "MainWindow" Height = "350" Width = "604"> <Grid> <Button Content = "Click Me" Width = "60" Height = "30"> <Button.Triggers> <EventTrigger RoutedEvent = "Button.Click"> <EventTrigger.Actions> <BeginStoryboard> <Storyboard> <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty = "Width" Duration = "0:0:4"> <LinearDoubleKeyFrame Value = "60" KeyTime = "0:0:0"/> <LinearDoubleKeyFrame Value = "120" KeyTime = "0:0:1"/> <LinearDoubleKeyFrame Value = "200" KeyTime = "0:0:2"/> <LinearDoubleKeyFrame Value = "300" KeyTime = "0:0:3"/>

</DoubleAnimationUsingKeyFrames>

<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty = "Height" Duration = "0:0:4"> <LinearDoubleKeyFrame Value = "30" KeyTime = "0:0:0"/> <LinearDoubleKeyFrame Value = "40" KeyTime = "0:0:1"/> <LinearDoubleKeyFrame Value = "80" KeyTime = "0:0:2"/> <LinearDoubleKeyFrame Value = "150" KeyTime = "0:0:3"/> </DoubleAnimationUsingKeyFrames>

</Storyboard> </BeginStoryboard> </EventTrigger.Actions> </EventTrigger> </Button.Triggers> </Button> </Grid> </Window>

https://www.ifourtechnolab.com/wpf-software-development


Thank You

https://www.ifourtechnolab.com/wpf-software-development


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.