Sei sulla pagina 1di 306

WPF

About the Tutorial


WPF stands for Windows Presentation Foundation. It is a powerful framework for building
Windows applications. This tutorial explains the features that you need to understand to
build WPF applications and how it brings a fundamental change in Windows applications.

Audience
This tutorial has been designed for all those readers who want to learn WPF and to apply
it instantaneously in different type of applications.

Prerequisites
Before proceeding with this tutorial, you should have a basic understanding of XML, Web
Technologies and HTML.

Copyright & Disclaimer


Copyright 2015 by Tutorials Point (I) Pvt. Ltd.

All the content and graphics published in this e-book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish
any contents or a part of contents of this e-book in any manner without written consent
of the publisher.

We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.
Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our
website or its contents including this tutorial. If you discover any errors on our website or
in this tutorial, please notify us at contact@tutorialspoint.com

i
WPF

Table of Contents
About the Tutorial .................................................................................................................................. i

Audience ................................................................................................................................................ i

Prerequisites .......................................................................................................................................... i

Copyright & Disclaimer ........................................................................................................................... i

Table of Contents .................................................................................................................................. ii

1. WPF OVERVIEW .............................................................................................................. 1

WPF Architecture .................................................................................................................................. 1

WPF Advantages ................................................................................................................................. 2

WPF Features...................................................................................................................................... 2

2. WPF ENVIRONMENT SETUP ............................................................................................ 3

Installation ............................................................................................................................................ 3

3. WPF HELLO WORLD ........................................................................................................ 7

4. WPF XAML OVERVIEW .................................................................................................. 12

Basic Syntax ......................................................................................................................................... 12

Why XAML in WPF ............................................................................................................................... 13

5. WPF ELEMENTS TREE .................................................................................................... 17

Logical Tree Structure .......................................................................................................................... 17

Visual Tree Structure ........................................................................................................................... 18

6. WPF DEPENDENCY PROPERTIES .................................................................................... 20

Why We Need Dependency Properties ................................................................................................ 21

Custom Dependency Properties .......................................................................................................... 22

7. WPF ROUTED EVENTS ................................................................................................... 25

Direct Event ......................................................................................................................................... 25

ii
WPF

Bubbling Event .................................................................................................................................... 25

Tunnel Event ....................................................................................................................................... 25

Custom Routed Events ........................................................................................................................ 29

8. WPF CONTROLS ............................................................................................................ 34

9. BUTTON ........................................................................................................................... 37

10. CALENDAR ....................................................................................................................... 46

11. CHECKBOX ....................................................................................................................... 52

12. COMBOBOX ..................................................................................................................... 62

13. CONTEXTMENU ............................................................................................................... 69

14. DATAGRID ........................................................................................................................ 76

15. DATEPICKER ..................................................................................................................... 85

16. DIALOG BOX ..................................................................................................................... 90

17. GRIDVIEW ........................................................................................................................ 93

18. IMAGE.............................................................................................................................. 99

19. LABEL ............................................................................................................................. 104

20. LISTBOX.......................................................................................................................... 108

21. MENU ............................................................................................................................ 113

22. PASSWORDBOX.............................................................................................................. 119

23. POPUP ........................................................................................................................... 123

24. PROGRESSBAR ............................................................................................................... 126

25. RADIOBUTTON ............................................................................................................... 130


iii
WPF

26. SCROLLVIEWER .............................................................................................................. 137

27. SLIDER ............................................................................................................................ 143

28. TEXTBLOCK .................................................................................................................... 148

29. TOGGLEBUTTON ............................................................................................................ 151

30. TOOLTIP ......................................................................................................................... 155

31. WINDOW ....................................................................................................................... 158

32. THIRD-PARTY CONTROLS ............................................................................................... 162

33. WPF LAYOUTS ............................................................................................................. 169

Stack Panel ........................................................................................................................................ 169

Wrap Panel ........................................................................................................................................ 172

Dock Panel......................................................................................................................................... 175

Canvas Panel ..................................................................................................................................... 179

Grid Panel .......................................................................................................................................... 183

34. NESTING OF LAYOUT...................................................................................................... 187

35. WPF INPUT.................................................................................................................. 189

Mouse ............................................................................................................................................... 189

Keyboard .......................................................................................................................................... 193

ContextMenu or RoutedCommands .................................................................................................. 195

Multi Touch ....................................................................................................................................... 198

36. WPF COMMAND LINE ................................................................................................. 203

37. WPF DATA BINDING .................................................................................................... 208

One-Way Data Binding ...................................................................................................................... 208

Two-Way Data Binding ...................................................................................................................... 212

iv
WPF

38. WPF RESOURCES ......................................................................................................... 215

Resource Scope ................................................................................................................................. 217

Resource Dictionaries ........................................................................................................................ 217

39. WPF TEMPLATES ......................................................................................................... 220

Control Template............................................................................................................................... 220

Data Template ................................................................................................................................... 222

40. WPF STYLES................................................................................................................. 227

Control Level ..................................................................................................................................... 231

Layout Level ...................................................................................................................................... 232

Window Level .................................................................................................................................... 234

Application Level ............................................................................................................................... 235

41. WPF TRIGGERS ............................................................................................................ 238

Property Triggers ............................................................................................................................... 238

Data Triggers ..................................................................................................................................... 239

Event Triggers .................................................................................................................................... 241

42. WPF DEBUGGING ........................................................................................................ 244

Debugging in C# ................................................................................................................................. 244

Debugging in XAML ........................................................................................................................... 248

UI Debugging Tools for XAML ............................................................................................................ 251

43. WPF CUSTOM CONTROLS ........................................................................................... 254

User Control ...................................................................................................................................... 254

Custom Controls ................................................................................................................................ 258

44. WPF EXCEPTION HANDLING ........................................................................................ 263

Syntax ............................................................................................................................................... 263

Hierarchy ........................................................................................................................................... 264


v
WPF

45. WPF LOCALIZATION .................................................................................................... 270

46. WPF INTERACTION ...................................................................................................... 277

Behaviors .......................................................................................................................................... 277

Drag and Drop ................................................................................................................................... 280

47. WPF 2D GRAPHICS ...................................................................................................... 284

Shapes and Drawing .......................................................................................................................... 284

48. WPF 3D GRAPHICS ...................................................................................................... 288

49. WPF MULTIMEDIA ...................................................................................................... 293

Speech Synthesizer ............................................................................................................................ 295

vi
1. WPF OVERVIEW WPF

WPF stands for Windows Presentation Foundation. It is a powerful framework for building
Windows applications. This tutorial explains the features that you need to understand to
build WPF applications and how it brings a fundamental change in Windows applications.

WPF was first introduces in .NET framework 3.0 version, and then so many other features
were added in the subsequent .NET framework versions.

WPF Architecture
Before WPF, the other user interface frameworks offered by Microsoft such as MFC and
Windows forms, were just wrappers around User32 and GDI32 DLLs, but WPF makes only
minimal use of User32. So,

WPF is more than just a wrapper.


It is a part of the .NET framework.
It contains a mixture of managed and unmanaged code.

The major components of WPF architecture are as shown in the figure below. The most
important code part of WPF are:

Presentation Framework
Presentation Core
Milcore

Presentation Framework

Presentation Core

CLR

Milcore
User32 DirectX

Kernel
The presentation framework and the presentation core have been written in managed
code. Milcore is a part of unmanaged code which allows tight integration with DirectX
1
WPF

(responsible for display and rendering). CLR makes the development process more
productive by offering many features such as memory management, error handling, etc.

WPF Advantages
In the earlier GUI frameworks, there was no real separation between how an application
looks like and how it behaved. Both GUI and behavior was created in the same language,
e.g. C# or VB.Net which would require more effort from the developer to implement both
UI and behavior associated with it.

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.

WPF Features
WPF is a powerful framework to create Windows application. It supports many great
features, some of which have been listed below:

Feature Description

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


Control

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

2
2. WPF ENVIRONMENT SETUP WPF

Microsoft provides two important tools for WPF application development.

Visual Studio
Expression Blend

Both the tools can create WPF projects, but the fact is that Visual Studio is used more by
developers, while Blend is used more often by designers. For this tutorial, we will mostly
be using Visual Studio.

Installation
Microsoft provides a free version of Visual Studio which can be downloaded from
https://www.visualstudio.com/en-us/downloads/download-visual-studio-vs.aspx.

Download the files and follow the steps given below to set up WPF application development
environment on your system.

1. After the download is complete, run the installer. The following dialog will be
displayed.

3
WPF

2. Click the Install button and it will start the installation process.

4
WPF

3. Once the installation process is completed successfully, you will get to see the
following dialog box.

4. Close this dialog box and restart your computer if required.

5. Now open Visual Studio from the Start Menu which will open the following dialog
box.

5
WPF

6. Once all is done, you will see the main window of Visual Studio.

You are now ready to build your first WPF application.

6
3. WPF HELLO WORLD WPF

In this chapter, we will develop a simple Hello World WPF application. So lets start the
simple implementation by following the steps given below.

1. Click on File > New > Project menu option.

7
WPF

2. The following dialog box will be displayed.

3. Under Templates, select Visual C# and in the middle panel, select WPF Application.

4. Give the project a name. Type HelloWorld in the name field and click the OK button.

5. By default, two files are created, one is the XAML file (mainwindow.xaml) and the
other one is the CS file (mainwindow.cs)

6. On mainwindow.xaml, you will see two sub-windows, one is the design window and
the other one is the source (XAML) window.

7. In WPF application, there are two ways to design an UI for your application. One is to
simply drag and drop UI elements from the toolbox to the Design Window. The second
way is to design your UI by writing XAML tags for UI elements. Visual Studio handles
XAML tags when drag and drop feature is used for UI designing.

8. In mainwindow.xaml file, the following XAML tags are written by default.

<Window x:Class="HelloWorld.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>

8
WPF

</Grid>
</Window>

9. By default, a Grid is set as the first element after page.


10. Lets go to the toolbox and drag a TextBlock to the design window.

11. You will see the TextBlock on the design window.


9
WPF

12. When you look at the source window, you will see that Visual Studio has generated
the XAML code of the TextBlock for you.

13. Lets change the Text property of TextBlock in XAML code from TextBlock to Hello
World.

<Window x:Class="HelloWorld.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>
<TextBlock x:Name="textBlock"
HorizontalAlignment="Left"
Margin="235,143,0,0"
TextWrapping="Wrap"
Text="Hello World!"
VerticalAlignment="Top"
Height="44"
Width="102"/>
</Grid>
</Window>

14. Now, you will see the change on the Design Window as well.

10
WPF

When the above code is compiled and executed, you will see the following window.

Congratulations! You have designed and created your first WPF application.

11
4. WPF XAML OVERVIEW WPF

One of the first things you will encounter while working with WPF is XAML. XAML stands
for Extensible Application Markup Language. Its a simple and declarative language based
on XML.

In XAML, it very easy to create, initialize, and set properties of objects with
hierarchical relations.

It is mainly used for designing GUIs, however it can be used for other purposes as
well, e.g., to declare workflow in Workflow Foundation.

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

<Window x:Class="Resources.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>

</Grid>
</Window>

The above XAML file contains different kinds of information. The following table briefly
explains the role of each information.

Information Description
<Window It is the opening object element or container
of the root.
It is a partial class declaration which connects
x:Class="Resources.MainWindow" the markup to the partial class code defined
behind.
xmlns="http://schemas.microsoft.com/ Maps the default XAML namespace for WPF
winfx/2006/xaml/presentation" client/framework.
xmlns:x="http://schemas.microsoft.co XAML namespace for XAML language which
m/winfx/2006/xaml" maps it to x: prefix
> End of object element of the root
<Grid> It is starting and closing tags of an empty grid
</Grid> object.
</Window> Closing the object element

12
WPF

The syntax rules for XAML is almost similar to XML. If you look at an XAML document, then
you will notice that it is actually a valid XML file, but an XML file is not necessarily an XAML
file. It is because in XML, the value of the attributes must be a string while in XAML, it can
be a different object which is known as Property element 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 (>).

Example of simple object with no child element:


<Button/>

Example of object element with some attributes:


<Button Content="Click Me"
Height="30"
Width="60"/>

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>

Why XAML in WPF


XAML is not only the most widely known feature of WPF, but it's also one of the most
misunderstood features. If you have exposure to WPF, then you must have heard of XAML;
but take a note of the following two less known facts about XAML:

13
WPF

WPF doesn't need XAML

XAML doesn't need WPF

They are in fact separable pieces of technology. To understand how that can be, let's look
at a simple example in which a button is created with some properties in XAML.

<Window x:Class="WPFXAMLOverview.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">
<StackPanel>
<Button x:Name="button"
Content="Click Me"
HorizontalAlignment="Left"
Margin="150"
VerticalAlignment="Top"
Width="75"/>
</StackPanel>
</Window>

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

using System.Windows;
using System.Windows.Controls;

namespace WPFXAMLOverview
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
// Create the StackPanel
StackPanel stackPanel = new StackPanel();

14
WPF

this.Content = stackPanel;

// Create the Button


Button button = new Button();
button.Content = "Click Me";
button.HorizontalAlignment = HorizontalAlignment.Left;
button.Margin = new Thickness(150);
button.VerticalAlignment = VerticalAlignment.Top;
button.Width = 75;
stackPanel.Children.Add(button);

}
}
}

When you compile and execute either the XAML code or the C# code, you will see the
same output as shown below.

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.

XAML is just another simple and easy way to design UI elements.

With XAML, it doesnt mean that what you can do to design UI elements is the only
way. You can either declare the objects in XAML or define them using code.

15
WPF

XAML is optional, but despite this, it is at the heart of WPF design.


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

WPF aims to make it possible to control all visual aspects of the user interface from
mark-up.

16
5. WPF ELEMENTS TREE WPF

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

With the help of these tree structures, you can easily create and identify the relationship
between UI elements. 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.

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.

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

<Window x:Class="WPFElementsTree.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">
<StackPanel>
<Button x:Name="button" Height="30" Width="70" Content="OK"
Margin="20"/>
<ListBox x:Name="listBox" Height="100" Width="100" Margin="20">
<ListBoxItem Content="Item 1"/>
<ListBoxItem Content="Item 2"/>
<ListBoxItem Content="Item 3"/>
</ListBox>
</StackPanel>
</Window>

17
WPF

If you look at the XAML code, you will observe a tree structure, i.e. the root node is the
Window and inside the root node, there is only one child, that is StackPanel. But StackPanel
contains two child elements, button and list box. List box has three more child list box
items.

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.

To see the visual tree of the above simple application which contains a button and a list
box, lets compile and execute the XAML code and you will see the following window.

When the application is running, you can see the visual tree of the running application in
Live Visual Tree window which shows the complete hierarchy of this application, as shown
below.

18
WPF

The visual tree is typically a superset of the logical tree. You can see here that all the
logical elements are also present in the visual tree. So these two trees are really just two
different views of the same set of objects that make up the UI.

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.

19
6. WPF DEPENDENCY PROPERTIES WPF

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.

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>

The x:Type markup extension in XAML has a similar functionality like typeof() in C#. It is
used when attributes are specified which take the type of the object such as <Style
TargetType="{x:Type Button}">

20
WPF

When the above code is compiled and executed, you would get the following
MainWindow. When the mouse is over the button, it will change the foreground color of
a button. When the mouse leaves the button, it changes back to its original color.

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

Basically, Dependency Properties offer a lot of functionalities that you wont 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.

21
WPF

Custom Dependency Properties


In .NET framework, custom dependency properties can also be defined. Follow the steps
given below to define custom dependency property in C#.

Declare and register your dependency property with system call register.
Provide the setter and getter for the property.
Define a static handler which will handle any changes that occur globally
Define an instance handler which will handle any changes that occur to that
particular instance.

The following C# code defines a dependency property to set the SetText property of the
user control.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication3
{
/// <summary>
/// Interaction logic for UserControl1.xaml
/// </summary>
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}

22
WPF

public static readonly DependencyProperty SetTextProperty =


DependencyProperty.Register("SetText", typeof(string), typeof(UserControl1),
new PropertyMetadata("", new PropertyChangedCallback(OnSetTextChanged)));
public string SetText
{
get { return (string)GetValue(SetTextProperty); }
set { SetValue(SetTextProperty, value); }
}
private static void OnSetTextChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
UserControl1 UserControl1Control = d as UserControl1;
UserControl1Control.OnSetTextChanged(e);
}
private void OnSetTextChanged(DependencyPropertyChangedEventArgs e)
{
tbTest.Text = e.NewValue.ToString();
}

}
}

Here is the XAML file in which the TextBlock is defined as a user control and the Text
property will be assigned to it by the SetText dependency property.

The following XAML code creates a user control and initializes its SetText dependency
property.

<Window x:Class="WpfApplication3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:views="clr-namespace:WpfApplication3"
Title="MainWindow" Height="350" Width="604">
<Grid>
<views:UserControl1 SetText="Hellow World"/>
</Grid>
</Window>

23
WPF

Let's run this application. You can immediately observe that in our MainWindow, the
dependency property for user control has been successfully used as a Text.

24
7. WPF ROUTED EVENTS WPF

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

Direct Event
A direct event is similar to events in Windows forums 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.

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.

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.

Given below is a simple example of a Routed event in which a button and three text blocks
are created with some properties and events.

<Window x:Class="WPFRoutedEvents.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="450" Width="604"

25
WPF

ButtonBase.Click ="Window_Click" >


<Grid>

<StackPanel Margin="20" ButtonBase.Click="StackPanel_Click">


<StackPanel Margin="10">
<TextBlock Name="txt1" FontSize="18" Margin="5" Text="This is a
TextBlock 1" />
<TextBlock Name="txt2" FontSize="18" Margin="5" Text="This is a
TextBlock 2" />
<TextBlock Name="txt3" FontSize="18" Margin="5" Text="This is a
TextBlock 3" />
</StackPanel>
<Button Margin="10" Content="Click me"
Click="Button_Click"
Width="80"/>
</StackPanel>
</Grid>
</Window>

Here is the C# code for the Click events implementation for Button, StackPanel, and
Window.

using System.Windows;

namespace WPFRoutedEvents
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private void Button_Click(object sender, RoutedEventArgs e)


{
txt1.Text = "Button is Clicked";

26
WPF

}
private void StackPanel_Click(object sender, RoutedEventArgs e)

{
txt2.Text = "Click event is bubbled to Stack Panel";
}
private void Window_Click(object sender, RoutedEventArgs e)
{
txt3.Text = "Click event is bubbled to Window";
}
}
}

When you compile and execute the above code, it will produce the following window:

27
WPF

When you click on the button, the text blocks will get updated, as shown below.

If you want to stop the routed event at any particular level, then you will need to set the
e.Handled = true;

Lets change the StackPanel_Click event as shown below:

private void StackPanel_Click(object sender, RoutedEventArgs e)


{
txt2.Text = "Click event is bubbled to Stack Panel";
e.Handled = true;
}

When you click on the button, you will observe that the click event will not be routed to
the window and will stop at the stackpanel and the 3rd text block will not be updated.

28
WPF

Custom Routed Events


In .NET framework, custom routed event can also be defined. You need to follow the steps
given below to define a custom routed event in C#.

Declare and register your routed event with system call RegisterRoutedEvent.
Specify the Routing Strategy, i.e. Bubble, Tunnel, or Direct.
Provide the event handler.

Lets take an example to understand more about custom routed events. Follow the steps
given below:

1. Create a new WPF project with WPFCustomRoutedEvent

2. Right click on your solution and select Add > New Item...

3. The following dialog will open, now select Custom Control (WPF) and name it
MyCustomControl.

4. Click the Add button and you will see that two new files (Themes/Generic.xaml and
MyCustomControl.cs) will be added in your solution.

The following XAML code sets the style for the custom control in Generic.xaml file.

<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WPFCustomRoutedEvent">

29
WPF

<Style TargetType="{x:Type local:MyCustomControl}">


<Setter Property="Margin" Value="50"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:MyCustomControl}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">

<Button x:Name="PART_Button" Content="Click Me" />


</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>

Given below is the C# code for the MyCustomControl class which inherits from the
Control class in which a custom routed event Click is created for the custom control.

using System.Windows;
using System.Windows.Controls;

namespace WPFCustomRoutedEvent
{
public class MyCustomControl : Control
{
static MyCustomControl()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(MyCustomControl),
new FrameworkPropertyMetadata(typeof(MyCustomControl)));
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();

//demo purpose only, check for previous instances and remove the handler first

var button = GetTemplateChild("PART_Button") as Button;

30
WPF

if (button != null)
button.Click += Button_Click;

void Button_Click(object sender, RoutedEventArgs e)


{
RaiseClickEvent();
}

public static readonly RoutedEvent ClickEvent =


EventManager.RegisterRoutedEvent("Click", RoutingStrategy.Bubble,
typeof(RoutedEventHandler), typeof(MyCustomControl));

public event RoutedEventHandler Click


{
add { AddHandler(ClickEvent, value); }
remove { RemoveHandler(ClickEvent, value); }
}

protected virtual void RaiseClickEvent()


{
RoutedEventArgs args = new
RoutedEventArgs(MyCustomControl.ClickEvent);
RaiseEvent(args);
}
}
}

Here is the custom routed event implementation in C# which will display a message box
when the user clicks it.

using System.Windows;

namespace WPFCustomRoutedEvent
{
// <summary>
// Interaction logic for MainWindow.xaml

31
WPF

// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private void MyCustomControl_Click(object sender, RoutedEventArgs e)


{
MessageBox.Show("It is the custom routed event of your custom control");

}
}
}

Here is the implementation in MainWindow.xaml to add the custom control with a routed
event Click.

<Window x:Class="WPFCustomRoutedEvent.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WPFCustomRoutedEvent"
Title="MainWindow" Height="350" Width="604">
<Grid>
<local:MyCustomControl Click="MyCustomControl_Click"/>
</Grid>
</Window>

When the above code is compiled and executed, it will produce the following window which
contains a custom control.

32
WPF

When you click on the custom control, it will produce the following message.

33
8. WPF CONTROLS WPF

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.

The complete inheritance hierarchy of WPF controls are as follows:

34
WPF

The following table contains a list of controls which we will discuss in the subsequent
chapters.

Sr. Controls & Description


No.

1 Button
A control that responds to user input

2 Calendar
Represents a control that enables a user to select a date by using a visual
calendar display.
3 CheckBox
A control that a user can select or clear.

4 ComboBox
A drop-down list of items a user can select from.

5 ContextMenu
Gets or sets the context menu element that should appear whenever the
context menu is requested through user interface (UI) from within this element.
6 DataGrid
Represents a control that displays data in a customizable grid.

7 DatePicker
A control that lets a user select a date.

8 Dialogs
An application may also display additional windows to help the user gather or
display important information.
9 GridView
A control that presents a collection of items in rows and columns that can scroll
horizontally.
10 Image
A control that presents an image.

11 Label
Displays text on a form. Provides support for access keys.

12 ListBox
A control that presents an inline list of items that the user can select from.

13 Menus
Represents a Windows menu control that enables you to hierarchically organize
elements associated with commands and event handlers.
14 PasswordBox
A control for entering passwords.

15 Popup
Displays content on top of existing content, within the bounds of the application
window.
16 ProgressBar
A control that indicates progress by displaying a bar.

35
WPF

17 RadioButton
A control that allows a user to select a single option from a group of options.

18 ScrollViewer
A container control that lets the user pan and zoom its content.

19 Slider
A control that lets the user select from a range of values by moving a Thumb
control along a track.
20 TextBlock
A control that displays text.

21 ToggleButton
A button that can be toggled between 2 states.

22 ToolTip
A pop-up window that displays information for an element.

23 Window
The root window which provides minimize/maximize option, Title bar, border
and close button
24 3rd Party Controls
Use third-party controls in your WPF applications.

We will discuss all these controls one by one with their implementation.

36
9. BUTTON WPF

The Button class represents the most basic type of button control. The hierarchical
inheritance of Button class is as follows:

37
WPF

Commonly Used Properties of Button Class

Sr. Property & Description


No.

1 Background
Gets or sets a brush that provides the background of the control. (Inherited
from Control)

2 BorderBrush
Gets or sets a brush that describes the border fill of a control. (Inherited from
Control)

3 BorderThickness
Gets or sets the border thickness of a control. (Inherited from Control)

4 Content
Gets or sets the content of a ContentControl. (Inherited from ContentControl)

5 ClickMode
Gets or sets a value that indicates when the Click event occurs, in terms of
device behavior. (Inherited from ButtonBase)

6 ContentTemplate
Gets or sets the data template that is used to display the content of the
ContentControl. (Inherited from ContentControl)

7 FontFamily
Gets or sets the font used to display text in the control. (Inherited from
Control)

8 FontSize
Gets or sets the size of the text in this control. (Inherited from Control)

9 FontStyle
Gets or sets the style in which the text is rendered. (Inherited from Control)

38
WPF

10 FontWeight
Gets or sets the thickness of the specified font. (Inherited from Control)

11 Foreground
Gets or sets a brush that describes the foreground color. (Inherited from
Control)

12 Height
Gets or sets the suggested height of a FrameworkElement. (Inherited from
FrameworkElement)

13 HorizontalAlignment
Gets or sets the horizontal alignment characteristics that are applied to a
FrameworkElement when it is composed in a layout parent, such as a panel
or items control. (Inherited from FrameworkElement)

14 IsEnabled
Gets or sets a value indicating whether the user can interact with the control.
(Inherited from Control)

15 IsPressed
Gets a value that indicates whether a ButtonBase is currently in a pressed
state. (Inherited from ButtonBase)

16 Margin
Gets or sets the outer margin of a FrameworkElement. (Inherited from
FrameworkElement)

Name
17 Gets or sets the identifying name of the object. When a XAML processor
creates the object tree from XAML markup, run-time code can refer to the
XAML-declared object by this name. (Inherited from FrameworkElement)

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

Resources
19 Gets the locally defined resource dictionary. In XAML, you can establish
resource items as child object elements of a frameworkElement.Resources
property element, through XAML implicit collection syntax. (Inherited from
FrameworkElement)

39
WPF

20 Style
Gets or sets an instance Style that is applied for this object during layout and
rendering. (Inherited from FrameworkElement)

Template
21 Gets or sets a control template. The control template defines the visual
appearance of a control in UI, and is defined in XAML markup. (Inherited from
Control)

VerticalAlignment
22 Gets or sets the vertical alignment characteristics that are applied to a
FrameworkElement when it is composed in a parent object such as a panel or
items control. (Inherited from FrameworkElement)

23 Visibility
Gets or sets the visibility of a UIElement. A UIElement that is not visible is not
rendered and does not communicate its desired size to layout. (Inherited from
UIElement)

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

Commonly Used Methods of Button Class

Sr.
No. Method & Description

1 ClearValue
Clears the local value of a dependency property. (Inherited from
DependencyObject)

2 FindName
Retrieves an object that has the specified identifier name. (Inherited from
FrameworkElement)

40
WPF

OnApplyTemplate
3 Invoked whenever application code or internal processes (such as a rebuilding
layout pass) call ApplyTemplate. In simplest terms, this means the method is
called just before a UI element displays in your app. Override this method to
influence the default post-template logic of a class. (Inherited from
FrameworkElement)

OnContentChanged
4 Invoked when the value of the Content property changes. (Inherited from
ContentControl)

5 OnDragEnter
Called before the DragEnter event occurs. (Inherited from Control)

OnDragLeave
6 Called before the DragLeave event occurs. (Inherited from Control)

7 OnDragOver
Called before the DragOver event occurs. (Inherited from Control)

8 OnDrop
Called before the Drop event occurs. (Inherited from Control)

9 OnGotFocus
Called before the GotFocus event occurs. (Inherited from Control)

OnKeyDown
10 Called before the KeyDown event occurs. (Inherited from Control)

41
WPF

OnKeyUp
11 Called before the KeyUp event occurs. (Inherited from Control)

12 OnLostFocus
Called before the LostFocus event occurs. (Inherited from Control)

SetBinding
13 Attaches a binding to a FrameworkElement, using the provided binding object.
(Inherited from FrameworkElement)

Commonly Used Events of Button Class


Sr.
No. Event & Description

Click
1 Occurs when a button control is clicked. (Inherited from ButtonBase)

DataContextChanged
2 Occurs when the value of the FrameworkElement.DataContext property
changes. (Inherited from FrameworkElement)
DragEnter
3 Occurs when the input system reports an underlying drag event with this
element as the target. (Inherited from UIElement)
DragLeave
4 Occurs when the input system reports an underlying drag event with this
element as the origin. (Inherited from UIElement)
DragOver
5 Occurs when the input system reports an underlying drag event with this
element as the potential drop target. (Inherited from UIElement)
DragStarting
6 Occurs when a drag operation is initiated. (Inherited from UIElement)

GotFocus
7 Occurs when a UIElement receives focus. (Inherited from UIElement)

Holding
8 Occurs when an otherwise unhandled Hold interaction occurs over the hit test
area of this element. (Inherited from UIElement)
IsEnabledChanged
9 Occurs when the IsEnabled property changes. (Inherited from Control)

KeyDown
10 Occurs when a keyboard key is pressed while the UIElement has focus.
(Inherited from UIElement)

42
WPF

KeyUp
11 Occurs when a keyboard key is released while the UIElement has focus.
(Inherited from UIElement)
LostFocus
12 Occurs when a UIElement loses focus. (Inherited from UIElement)

SizeChanged
13 Occurs when either the ActualHeight or the ActualWidth property changes
value on a FrameworkElement. (Inherited from FrameworkElement)

Example
Lets take a simple example to understand the concepts better. Follow the steps given
below:

1. Open Visual Studio and then Click File > New > Project menu option.

2. In the New Project dialog box, in the Templates pane, click on Visual C# and in
middle pane, select WPF Application.

3. In the Name box, type WPFButtonControl, and then click OK.

4. A new WPF project is created.

5. Drag a Button control from the Toolbox to the WPF design window.

6. Now click the button and go to the Properties window and set the following
properties of the button.

Property Value
Content Click Me
Margin 200
Height 20
Width 75

7. If you look at the XAML window, you will see the following code which is generated
by Visual Studio.

<Window x:Class="WPFButtonControl.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:WPFButtonControl"
mc:Ignorable="d"

43
WPF

Title="MainWindow" Height="350" Width="525">


<Grid>
<Button x:Name="button" Content="Click Me" HorizontalAlignment="Left"
Margin="194,150,0,0" VerticalAlignment="Top" Width="75"/>

</Grid>
</Window>

8. Lets now go to the design window and double-click on the button which will open
the MainWindow.xaml.cs file.

9. We will write the following C# code to display a message when the user clicks the
button.

using System.Windows;

namespace WPFButtonControl
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private void button_Click(object sender, RoutedEventArgs e)


{
MessageBox.Show("You have clicked the button");
}
}
}

When you compile and execute the above code, it will produce the following output:
44
WPF

When you click the button, it will display the following message:

We recommend that you execute the above example code and experiment with some other
properties and events.

45
10. CALENDAR WPF

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. The hierarchical
inheritance of Calendar class is as follows:

Commonly Used Properties of Calendar Class


Sr.
No. Properties & Description

1 BlackoutDates
Gets a collection of dates that are marked as not selectable.

CalendarButtonStyle
2 Gets or sets the Style associated with the control's internal CalendarButton
object.

3 CalendarDayButtonStyle
Gets or sets the Style associated with the control's internal CalendarDayButton
object.

46
WPF

4 CalendarItemStyle
Gets or sets the Style associated with the control's internal CalendarItem
object.

5 DisplayDate
Gets or sets the date to display.

6 DisplayDateEnd
Gets or sets the last date in the date range that is available in the calendar.

7 DisplayDateStart
Gets or sets the first date that is available in the calendar.

DisplayMode
8 Gets or sets a value that indicates whether the calendar displays a month,
year, or decade.

9 FirstDayOfWeek
Gets or sets the day that is considered the beginning of the week.

10 IsTodayHighlighted
Gets or sets a value that indicates whether the current date is highlighted.

11 SelectedDate
Gets or sets the currently selected date.

12 SelectedDates
Gets a collection of selected dates.

13 SelectionMode
Gets or sets a value that indicates what kind of selections are allowed.

Commonly Used Methods of Calendar Class


Sr.
No. Method & Description

1 OnApplyTemplate
Builds the visual tree for the Calendar control when a new template is applied.
(Overrides FrameworkElement.OnApplyTemplate().)

47
WPF

ToString
2 Provides a text representation of the selected date. (Overrides
Control.ToString().)

Commonly Used Events of Calendar Class


Sr. Events & Description
No.

1 DisplayDateChanged
Occurs when the DisplayDate property is changed.

2 DisplayModeChanged
Occurs when the DisplayMode property is changed.

3 SelectedDatesChanged
Occurs when the collection returned by the SelectedDates property is changed.

4 SelectionModeChanged
Occurs when the SelectionMode changes.

Example
1. Lets create a new WPF project with WPFCalenderControl name.

2. Drag the calendar control from a toolbox and change the background color in the
properties window.

3. Now switch to XAML window in which you will see the XAML tags for calendar and
its background.

4. Add some more properties to set the blackouts dates and selection event, as shown
in the following XAML code.

<Window x:Class="WPFCalenderControl.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:WPFCalenderControl"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="604">
<Grid>
<Calendar Margin="20" SelectionMode="MultipleRange"
48
WPF

IsTodayHighlighted="false"
DisplayDate="1/1/2015"
DisplayDateEnd="1/31/2015"
SelectedDatesChanged="Calendar_SelectedDatesChanged"
xmlns:sys="clr-namespace:System;assembly=mscorlib">
<Calendar.BlackoutDates>
<CalendarDateRange Start="1/2/2015" End="1/4/2015"/>
<CalendarDateRange Start="1/9/2015" End="1/9/2015"/>
<CalendarDateRange Start="1/16/2015" End="1/16/2015"/>
<CalendarDateRange Start="1/23/2015" End="1/25/2015"/>
<CalendarDateRange Start="1/30/2015" End="1/30/2015"/>
</Calendar.BlackoutDates>
<Calendar.SelectedDates>
<sys:DateTime>1/5/2015</sys:DateTime>
<sys:DateTime>1/12/2015</sys:DateTime>
<sys:DateTime>1/14/2015</sys:DateTime>
<sys:DateTime>1/13/2015</sys:DateTime>
<sys:DateTime>1/15/2015</sys:DateTime>
<sys:DateTime>1/27/2015</sys:DateTime>
<sys:DateTime>4/2/2015</sys:DateTime>
</Calendar.SelectedDates>
<Calendar.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FFE4EAF0" Offset="0"/>
<GradientStop Color="#FFECF0F4" Offset="0.16"/>
<GradientStop Color="#FFFCFCFD" Offset="0.16"/>
<GradientStop Color="#FFD80320" Offset="1"/>
</LinearGradientBrush>
</Calendar.Background>
</Calendar>
</Grid>
</Window>

The select event implementation in C# is as follows:

using System;
using System.Windows;

49
WPF

using System.Windows.Controls;

namespace WPFCalenderControl
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private void Calendar_SelectedDatesChanged(object sender,


SelectionChangedEventArgs e)
{
var calendar = sender as Calendar;
if (calendar.SelectedDate.HasValue)
{
DateTime date = calendar.SelectedDate.Value;
this.Title = date.ToShortDateString();
}

}
}
}

When you compile and execute the above code, it will produce the following window which
shows some of the dates are selected while some are blacked out.

50
WPF

If you select another date, then it will be shown on the title of this window.

We recommend that you execute the above example code and try its other properties and
events.

51
11. CHECKBOX WPF

A checkbox is a control that a user can select (check) or clear (uncheck). It provides a list
of options that a user can select, such as a list of settings to apply to an application. The
hierarchical inheritance of Checkbox class is as follows:

52
WPF

Commonly Used Properties of CheckBox


Sr. Property & Description
No.

Background
1 Gets or sets a brush that provides the background of the control. (Inherited
from Control)

BorderBrush
2 Gets or sets a brush that describes the border fill of a control. (Inherited from
Control)

3 BorderThickness
Gets or sets the border thickness of a control. (Inherited from Control)

4 Content
Gets or sets the content of a ContentControl. (Inherited from ContentControl)

5 ClickMode
Gets or sets a value that indicates when the Click event occurs, in terms of
device behavior. (Inherited from ButtonBase)

6 ContentTemplate
Gets or sets the data template that is used to display the content of the
ContentControl. (Inherited from ContentControl)

7 FontFamily
Gets or sets the font used to display text in the control. (Inherited from
Control)

8 FontSize
Gets or sets the size of the text in this control. (Inherited from Control)

9 FontStyle
Gets or sets the style in which the text is rendered. (Inherited from Control)

10 FontWeight
Gets or sets the thickness of the specified font. (Inherited from Control)

11 Foreground
Gets or sets a brush that describes the foreground color. (Inherited from
Control)

53
WPF

12 Height
Gets or sets the suggested height of a FrameworkElement. (Inherited from
FrameworkElement)

HorizontalAlignment
13 Gets or sets the horizontal alignment characteristics that are applied to a
FrameworkElement when it is composed in a layout parent, such as a panel
or items control. (Inherited from FrameworkElement)

IsChecked
14 Gets or sets whether the ToggleButton is checked. (Inherited from
ToggleButton)

IsEnabled
15 Gets or sets a value indicating whether the user can interact with the control.
(Inherited from Control)

IsPressed
16 Gets a value that indicates whether a ButtonBase is currently in a pressed
state. (Inherited from ButtonBase)

IsThreeState
17 Gets or sets a value that indicates whether the control supports three states.
(Inherited from ToggleButton)

18 Margin
Gets or sets the outer margin of a FrameworkElement. (Inherited from
FrameworkElement)

Name
19 Gets or sets the identifying name of the object. When a XAML processor
creates the object tree from XAML markup, run-time code can refer to the
XAML-declared object by this name. (Inherited from FrameworkElement)

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

Resources
Gets the locally defined resource dictionary. In XAML, you can establish
21 resource items as child object elements of a frameworkElement.Resources
property element, through XAML implicit collection syntax. (Inherited from
FrameworkElement)

22 Style

54
WPF

Gets or sets an instance Style that is applied for this object during layout and
rendering. (Inherited from FrameworkElement)

Template
23 Gets or sets a control template. The control template defines the visual
appearance of a control in UI, and is defined in XAML markup. (Inherited from
Control)

VerticalAlignment
24 Gets or sets the vertical alignment characteristics that are applied to a
FrameworkElement when it is composed in a parent object such as a panel or
items control. (Inherited from FrameworkElement)

Visibility
25 Gets or sets the visibility of a UIElement. A UIElement that is not visible is not
rendered and does not communicate its desired size to layout. (Inherited from
UIElement)

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

Commonly Used Methods of CheckBox

Sr.
No. Method & Description

1 ClearValue
Clears the local value of a dependency property. (Inherited from
DependencyObject)

2 FindName
Retrieves an object that has the specified identifier name. (Inherited from
FrameworkElement)

OnApplyTemplate
3 Invoked whenever application code or internal processes (such as a rebuilding
layout pass) call ApplyTemplate. In simplest terms, this means the method is
called just before a UI element displays in your app. Override this method to
influence the default post-template logic of a class. (Inherited from
FrameworkElement)

55
WPF

4 OnContentChanged
Invoked when the value of the Content property changes. (Inherited from
ContentControl)

5 OnDragEnter
Called before the DragEnter event occurs. (Inherited from Control)

6 OnDragLeave
Called before the DragLeave event occurs. (Inherited from Control)

7 OnDragOver
Called before the DragOver event occurs. (Inherited from Control)

8 OnDrop
Called before the Drop event occurs. (Inherited from Control)

9 OnGotFocus
Called before the GotFocus event occurs. (Inherited from Control)

10 OnKeyDown
Called before the KeyDown event occurs. (Inherited from Control)

11 OnKeyUp
Called before the KeyUp event occurs. (Inherited from Control)

OnLostFocus
12 Called before the LostFocus event occurs. (Inherited from Control)

56
WPF

OnToggle
13 Called when the ToggleButton receives toggle stimulus. (Inherited from
ToggleButton)

SetBinding
14 Attaches a binding to a FrameworkElement, using the provided binding object.
(Inherited from FrameworkElement)

Commonly Used Events of CheckBox


Sr. Event & Description
No.

1 Checked
Fires when a ToggleButton is checked. (Inherited from ToggleButton)

2 Click
Occurs when a button control is clicked. (Inherited from ButtonBase)

3 DataContextChanged
Occurs when the value of the FrameworkElement.DataContext property
changes. (Inherited from FrameworkElement)
4 DragEnter
Occurs when the input system reports an underlying drag event with this
element as the target. (Inherited from UIElement)
5 DragLeave
Occurs when the input system reports an underlying drag event with this
element as the origin. (Inherited from UIElement)
6 DragOver
Occurs when the input system reports an underlying drag event with this
element as the potential drop target. (Inherited from UIElement)
7 DragStarting
Occurs when a drag operation is initiated. (Inherited from UIElement)

8 GotFocus
Occurs when a UIElement receives focus. (Inherited from UIElement)

9 Holding
Occurs when an otherwise unhandled Hold interaction occurs over the hit test
area of this element. (Inherited from UIElement)
10 Intermediate
Fires when the state of a ToggleButton is switched to the indeterminate state.
(Inherited from ToggleButton)
11 IsEnabledChanged
Occurs when the IsEnabled property changes. (Inherited from Control)

12 KeyDown
Occurs when a keyboard key is pressed while the UIElement has focus.
(Inherited from UIElement)

57
WPF

13 KeyUp
Occurs when a keyboard key is released while the UIElement has focus.
(Inherited from UIElement)
14 LostFocus
Occurs when a UIElement loses focus. (Inherited from UIElement)

15 SizeChanged
Occurs when either the ActualHeight or the ActualWidth property changes value
on a FrameworkElement. (Inherited from FrameworkElement)
16 Unchecked
Occurs when a ToggleButton is unchecked. (Inherited from ToggleButton)

Example
1. Lets create a new WPF project with the name WPFCheckBoxControl.

2. Drag two checkboxes and two textboxes from a toolbox and set the following
properties in the properties window.

Controls Property Value


Checkbox1 Content Two States
Name checkBox1
Width 90
Checkbox2 Content Three States
Name checkBox2
Width 90
textbox1 Name textBox1
Width 300
Textbox2 Name textBox2
Width 300

3. Now switch to XAML window in which you will see the XAML tags for check boxes
and text boxes.

4. Add some more properties and selection event as shown in the following XAML
code.

<Window x:Class="WPFCheckBoxControl.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:WPFCheckBoxControl"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="604">
<Grid>
<CheckBox x:Name="checkBox1"
Content="Two States"
58
WPF

HorizontalAlignment="Left"
Margin="80,70,0,0"
VerticalAlignment="Top"
Checked="HandleCheck"
Unchecked="HandleUnchecked" Width="90"/>
<CheckBox x:Name="checkBox2"
Content="Three States"
HorizontalAlignment="Left"
Margin="80,134,0,0"
VerticalAlignment="Top"
Width="90"
IsThreeState="True"
Indeterminate="HandleThirdState"
Checked="HandleCheck"
Unchecked="HandleUnchecked"/>
<TextBox x:Name="textBox1" HorizontalAlignment="Left"
Height="23" Margin="236,68,0,0"
TextWrapping="Wrap" VerticalAlignment="Top"
Width="300"/>
<TextBox x:Name="textBox2" HorizontalAlignment="Left"
Height="23" Margin="236,135,0,0" TextWrapping="Wrap"
VerticalAlignment="Top" Width="300"/>
</Grid>
</Window>

Here is the implementation in C# for different events:

using System.Windows;
using System.Windows.Controls;

namespace WPFCheckBoxControl
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{

59
WPF

public MainWindow()
{
InitializeComponent();
}
private void HandleCheck(object sender, RoutedEventArgs e)
{
CheckBox cb = sender as CheckBox;
if (cb.Name == "checkBox1") textBox1.Text = "2 state CheckBox is
checked.";
else textBox2.Text = "3 state CheckBox is checked.";
}

private void HandleUnchecked(object sender, RoutedEventArgs e)


{
CheckBox cb = sender as CheckBox;
if (cb.Name == "checkBox1") textBox1.Text = "2 state CheckBox is
unchecked.";
else textBox2.Text = "3 state CheckBox is unchecked.";
}

private void HandleThirdState(object sender, RoutedEventArgs e)


{
CheckBox cb = sender as CheckBox;
textBox2.Text = "3 state CheckBox is in indeterminate state.";
}
}
}

When you compile and execute the above code, it will produce the following window. When
you check / uncheck the checkboxes, it will update the text block accordingly.

60
WPF

We recommend that you execute the above example code and try some other properties
and events of the checkbox control.

61
12. COMBOBOX WPF

A combobox is a selection control that combines a non-editable textbox and a drop-down


listbox that allows users to select an item from a list. It either displays the current selection
or is empty if there is no selected item. The hierarchical inheritance of ComboBox class is
as follows:

Commonly Used Properties of ComboBox


Sr. Property & Description
No.
Background
1 Gets or sets a brush that provides the background of the control. (Inherited
from Control)
2 BorderThickness
Gets or sets the border thickness of a control. (Inherited from Control)

62
WPF

3 FontFamily
Gets or sets the font used to display text in the control. (Inherited from Control)
4 FontSize
Gets or sets the size of the text in this control. (Inherited from Control)
5 FontStyle
Gets or sets the style in which the text is rendered. (Inherited from Control)
6 FontWeight
Gets or sets the thickness of the specified font. (Inherited from Control)
7 Foreground
Gets or sets a brush that describes the foreground color. (Inherited from
Control)
8 GroupStyle
Gets a collection of GroupStyle objects that define the appearance of each level
of groups. (Inherited from ItemsControl)
9 Header
Gets or sets the content for the control's header.
Height
10 Gets or sets the suggested height of a FrameworkElement. (Inherited from
FrameworkElement)
HorizontalAlignment
11 Gets or sets the horizontal alignment characteristics that are applied to a
FrameworkElement when it is composed in a layout parent, such as a panel or
items control. (Inherited from FrameworkElement)
IsDropDownOpen
12 Gets or sets a value that indicates whether the drop-down portion of the
ComboBox is currently open.
IsEditable
13 Gets a value that indicates whether the user can edit text in the text box portion
of the ComboBox. This property always returns false.
14 IsEnabled
Gets or sets a value indicating whether the user can interact with the control.
(Inherited from Control)
15 Margin
Gets or sets the outer margin of a FrameworkElement. (Inherited from
FrameworkElement)
16 Name
Gets or sets the identifying name of the object. When a XAML processor creates
the object tree from XAML markup, run-time code can refer to the XAML-
declared object by this name. (Inherited from FrameworkElement)
17 Opacity
Gets or sets the degree of the object's opacity. (Inherited from UIElement)
18 SelectedIndex
Gets or sets the index of the selected item. (Inherited from Selector)
19 SelectedItem
Gets or sets the selected item. (Inherited from Selector)
SelectedValue
20 Gets or sets the value of the selected item, obtained by using the
SelectedValuePath. (Inherited from Selector)
Style
21 Gets or sets an instance Style that is applied for this object during layout and
rendering. (Inherited from FrameworkElement)
VerticalAlignment
22 Gets or sets the vertical alignment characteristics that are applied to a
FrameworkElement when it is composed in a parent object such as a panel or
items control. (Inherited from FrameworkElement)
63
WPF

Width
23 Gets or sets the width of a FrameworkElement. (Inherited from
FrameworkElement)
ItemsSource
24 Gets or sets an object source used to generate the content of the ItemsControl.
(Inherited from ItemsControl)

Commonly Used Methods of ComboBox


Sr. Method & Description
No.
Arrange
Positions child objects and determines a size for a UIElement. Parent objects
1 that implement custom layout for their child elements should call this method
from their layout override implementations to form a recursive layout update.
(Inherited from UIElement)
FindName
2 Retrieves an object that has the specified identifier name. (Inherited from
FrameworkElement)
3 Focus
Attempts to set the focus on the control. (Inherited from Control)
4 GetValue
Returns the current effective value of a dependency property from a
DependencyObject. (Inherited from DependencyObject)
5 IndexFromContainer
Returns the index to the item that has the specified, generated container.
(Inherited from ItemsControl)
6 OnDragEnter
Called before the DragEnter event occurs. (Inherited from Control)
7 OnDragLeave
Called before the DragLeave event occurs. (Inherited from Control)
8 OnDragOver
Called before the DragOver event occurs. (Inherited from Control)
9 OnDrop
Called before the Drop event occurs. (Inherited from Control)
10 OnKeyDown
Called before the KeyDown event occurs. (Inherited from Control)
11 OnKeyUp
Called before the KeyUp event occurs. (Inherited from Control)
12 OnLostFocus
Called before the LostFocus event occurs. (Inherited from Control)
ReadLocalValue
13 Returns the local value of a dependency property, if a local value is set.
(Inherited from DependencyObject)
SetBinding
14 Attaches a binding to a FrameworkElement, using the provided binding object.
(Inherited from FrameworkElement)
SetValue
15 Sets the local value of a dependency property on a DependencyObject.
(Inherited from DependencyObject)

64
WPF

Commonly Used Events of ComboBox


Sr. Event & Description
No.
DragEnter
1 Occurs when the input system reports an underlying drag event with this
element as the target. (Inherited from UIElement)
DragLeave
2 Occurs when the input system reports an underlying drag event with this
element as the origin. (Inherited from UIElement)
DragOver
3 Occurs when the input system reports an underlying drag event with this
element as the potential drop target. (Inherited from UIElement)
4 DragStarting
Occurs when a drag operation is initiated. (Inherited from UIElement)
Drop
5 Occurs when the input system reports an underlying drop event with this
element as the drop target. (Inherited from UIElement)
6 DropCompleted
Occurs when a drag-and-drop operation is ended. (Inherited from UIElement)
7 DropDownClosed
Occurs when the drop-down portion of the ComboBox closes.
8 DropDownOpened
Occurs when the drop-down portion of the ComboBox opens.
9 GotFocus
Occurs when a UIElement receives focus. (Inherited from UIElement)
10 IsEnabledChanged
Occurs when the IsEnabled property changes. (Inherited from Control)
11 KeyDown
Occurs when a keyboard key is pressed while the UIElement has focus.
(Inherited from UIElement)
12 KeyUp
Occurs when a keyboard key is released while the UIElement has focus.
(Inherited from UIElement)
13 LostFocus
Occurs when a UIElement loses focus. (Inherited from UIElement)
14 SelectionChanged
Occurs when the currently selected item changes. (Inherited from Selector)
SizeChanged
15 Occurs when either the ActualHeight or the ActualWidth property changes value
on a FrameworkElement. (Inherited from FrameworkElement)

Example
1. Lets create a new WPF project with the name WPFComboBoxControl.

2. Drag two comboboxes and two textboxes from a toolbox and set the following
properties in the properties window.

Controls Property Value


Combobox1 isEditable False
Name comboBox
Width 90
Combobox2 isEditable True
Name comboBox1
65
WPF

Width 90
Textbox1 Name textBox
Width 300
Textbox2 Name textBox1
Width 300

3. Now switch to XAML window in which you will see the XAML tags for comboboxes
and textboxes.

4. Add some more properties combobox items and selection event, as shown in the
following XAML code.

<Window x:Class="WPFComboBoxControl.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:WPFComboBoxControl"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="604">
<Grid>
<ComboBox x:Name="comboBox" HorizontalAlignment="Left"
Margin="80,53,0,0" VerticalAlignment="Top" Width="120"
SelectionChanged="Combo_SelectionChanged">
<ComboBoxItem Content="Item #1"/>
<ComboBoxItem Content="Item #2"/>
<ComboBoxItem Content="Item #3"/>

</ComboBox>
<ComboBox x:Name="comboBox1" HorizontalAlignment="Left"
Margin="80,153,0,0" VerticalAlignment="Top" Width="120"
IsEditable="True"
SelectionChanged="Combo1_SelectionChanged">
<ComboBoxItem Content="Item #1"/>
<ComboBoxItem Content="Item #2"/>
<ComboBoxItem Content="Item #3"/>

</ComboBox>
<TextBox x:Name="textBox" HorizontalAlignment="Left"
Height="23" Margin="253,53,0,0" TextWrapping="Wrap"

66
WPF

VerticalAlignment="Top" Width="200"/>
<TextBox x:Name="textBox1" HorizontalAlignment="Left"
Height="23" Margin="253,152,0,0" TextWrapping="Wrap"
VerticalAlignment="Top" Width="200"/>

</Grid>
</Window>

Here is the C# code in which the selection changed events are implemented.

using System.Windows;
using System.Windows.Controls;

namespace WPFComboBoxControl
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private void Combo_SelectionChanged(object sender, SelectionChangedEventArgs e)

{
textBox.Text = comboBox.SelectedItem.ToString();
}

private void Combo1_SelectionChanged(object sender,


SelectionChangedEventArgs e)
{
textBox1.Text = comboBox1.SelectedItem.ToString();
}
}

67
WPF

When you compile and execute the above code, it will produce the following window. When
you select an item, it will be displayed on the textbox.

We recommend that you execute the above example code and try some other properties
and events of the combobox control.

68
13. CONTEXTMENU WPF

ContextMenu is a pop-up menu that enables a control to expose functionality that is


specific to the context of the control. It appears whenever the context menu is requested
through a user interface from within this element. The hierarchical inheritance of
ContextMenu class is as follows:

Commonly Used Properties of ContextMenu


Sr. Property & Description
No.
1 Background
Gets or sets a brush that provides the background of the control. (Inherited
from Control)
2 BorderThickness
Gets or sets the border thickness of a control. (Inherited from Control)
69
WPF

3 ContextMenu
Gets or sets the context menu element that should appear whenever the
context menu is requested through user interface (UI) from within this
element. (Inherited from FrameworkElement.)
4 FontFamily
Gets or sets the font used to display text in the control. (Inherited from Control)
5 FontSize
Gets or sets the size of the text in this control. (Inherited from Control)
6 FontStyle
Gets or sets the style in which the text is rendered. (Inherited from Control)
7 FontWeight
Gets or sets the thickness of the specified font. (Inherited from Control)
Foreground
8 Gets or sets a brush that describes the foreground color. (Inherited from
Control)
GroupStyle
9 Gets a collection of GroupStyle objects that define the appearance of each level
of groups. (Inherited from ItemsControl)
HasItems
10 Gets a value that indicates whether the ItemsControl contains items. (Inherited
from ItemsControl.)
Height
11 Gets or sets the suggested height of a FrameworkElement. (Inherited from
FrameworkElement)
HorizontalAlignment
12 Gets or sets the horizontal alignment characteristics that are applied to a
FrameworkElement when it is composed in a layout parent, such as a panel or
items control. (Inherited from FrameworkElement)
IsFocused
13 Gets a value that determines whether this element has logical focus. This is a
dependency property. (Inherited from UIElement.)
14 IsOpen
Gets or sets a value that indicates whether the ContextMenu is visible.
IsEnabled
15 Gets or sets a value indicating whether the user can interact with the control.
(Inherited from Control)
ItemsSource
16 Gets or sets an object source used to generate the content of the ItemsControl.
(Inherited from ItemsControl)
Margin
17 Gets or sets the outer margin of a FrameworkElement. (Inherited from
FrameworkElement)
Name
18 Gets or sets the identifying name of the object. When a XAML processor creates
the object tree from XAML markup, run-time code can refer to the XAML-
declared object by this name. (Inherited from FrameworkElement)
19 Opacity
Gets or sets the degree of the object's opacity. (Inherited from UIElement)
Style
20 Gets or sets an instance Style that is applied for this object during layout and
rendering. (Inherited from FrameworkElement)
VerticalAlignment
21 Gets or sets the vertical alignment characteristics that are applied to a
FrameworkElement when it is composed in a parent object such as a panel or
items control. (Inherited from FrameworkElement)
70
WPF

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

Commonly Used Methods of ContextMenu


Sr. Method & Description
No.
AddChild
1 Adds the specified object as the child of the ItemsControl object. (Inherited
from ItemsControl.)
Arrange
Positions child objects and determines a size for a UIElement. Parent objects
2 that implement custom layout for their child elements should call this method
from their layout override implementations to form a recursive layout update.
(Inherited from UIElement)
FindName
3 Retrieves an object that has the specified identifier name. (Inherited from
FrameworkElement)
4 Focus
Attempts to set the focus on the control. (Inherited from Control)
GetValue
5 Returns the current effective value of a dependency property from a
DependencyObject. (Inherited from DependencyObject)
IsItemItsOwnContainer
6 Determines if the specified item is (or is eligible to be) its own container.
(Inherited from ItemsControl.)
OnDragEnter
7 Called before the DragEnter event occurs. (Inherited from Control)
8 OnDragLeave
Called before the DragLeave event occurs. (Inherited from Control)
9 OnDragOver
Called before the DragOver event occurs. (Inherited from Control)
10 OnDrop
Called before the Drop event occurs. (Inherited from Control)
OnContextMenuOpening
11 Invoked whenever an unhandled ContextMenuClosing routed event reaches
this class in its route. Implement this method to add class handling for this
event. (Inherited from FrameworkElement.)
12 OnItemsChanged
Invoked when the Items property changes. (Inherited from ItemsControl.)
13 OnLostFocus
Called before the LostFocus event occurs. (Inherited from Control)
ReadLocalValue
14 Returns the local value of a dependency property, if a local value is set.
(Inherited from DependencyObject)
SetBinding
15 Attaches a binding to a FrameworkElement, using the provided binding object.
(Inherited from FrameworkElement)
SetValue
16 Sets the local value of a dependency property on a DependencyObject.
(Inherited from DependencyObject)

71
WPF

Commonly Used Events of ContextMenu


Sr. Event & Description
No.
1 Closed
Occurs when a particular instance of a ContextMenu closes.
2 ContextMenuClosing
Occurs just before any context menu on the element is closed. (Inherited from
FrameworkElement.)
3 ContextMenuOpening
Occurs when any context menu on the element is opened. (Inherited from
FrameworkElement.)
4 DataContextChanged
Occurs when the data context for this element changes. (Inherited from
FrameworkElement.)
5 DragEnter
Occurs when the input system reports an underlying drag event with this
element as the target. (Inherited from UIElement)
6 DragLeave
Occurs when the input system reports an underlying drag event with this
element as the origin. (Inherited from UIElement)
7 DragOver
Occurs when the input system reports an underlying drag event with this
element as the potential drop target. (Inherited from UIElement)
8 Drop
Occurs when the input system reports an underlying drop event with this
element as the drop target. (Inherited from UIElement)
9 GotFocus
Occurs when a UIElement receives focus. (Inherited from UIElement)
10 IsEnabledChanged
Occurs when the IsEnabled property changes. (Inherited from Control)
11 KeyDown
Occurs when a keyboard key is pressed while the UIElement has focus.
(Inherited from UIElement)
12 KeyUp
Occurs when a keyboard key is released while the UIElement has focus.
(Inherited from UIElement)
13 LostFocus
Occurs when a UIElement loses focus. (Inherited from UIElement)

Example
1. Lets create a new WPF project with the name WPFContextMenuControl.

2. Drag a textbox from a toolbox and set the following properties in the properties
window.

Property Value
Name textBox1
Text Hi, this is WPF tutorial
TextWraping Wrap
Width 300

72
WPF

3. Now switch to XAML window in which you will see the XAML tags for textbox and
ContextMenu.

4. Add some more properties, menu items, and checked and unchecked events, as
shown in the following XAML code.

The following example contains a textbox with ContextMenu which manipulates the text
inside the textbox. The following XAML code creates a textbox with some properties and
events context menu.

<Window x:Class="WPFContextMenuControl.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:WPFContextMenuControl"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="604">
<Grid>
<TextBox x:Name="textBox1" HorizontalAlignment="Left"
Height="178" Margin="92,61,0,0" TextWrapping="Wrap"
Text="Hi, this is WPF tutorial"
VerticalAlignment="Top" Width="306">
<TextBox.ContextMenu>
<ContextMenu>
<MenuItem Header="_Bold" IsCheckable="True"
Checked="Bold_Checked" Unchecked="Bold_Unchecked" />
<MenuItem Header="_Italic" IsCheckable="True"
Checked="Italic_Checked"
Unchecked="Italic_Unchecked" />
<Separator />
<MenuItem Header="Increase Font Size"
Click="IncreaseFont_Click" />
<MenuItem Header="_Decrease Font Size"
Click="DecreaseFont_Click" />
</ContextMenu>
</TextBox.ContextMenu>
</TextBox>
</Grid>

73
WPF

</Window>

Here is the implementation in C# for different events.

using System.Windows;

namespace WPFContextMenuControl
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Bold_Checked(object sender, RoutedEventArgs e)
{
textBox1.FontWeight = FontWeights.Bold;
}

private void Bold_Unchecked(object sender, RoutedEventArgs e)


{
textBox1.FontWeight = FontWeights.Normal;
}

private void Italic_Checked(object sender, RoutedEventArgs e)


{
textBox1.FontStyle = FontStyles.Italic;
}

private void Italic_Unchecked(object sender, RoutedEventArgs e)


{
textBox1.FontStyle = FontStyles.Normal;
}

74
WPF

private void IncreaseFont_Click(object sender, RoutedEventArgs e)


{
if (textBox1.FontSize < 18)
{
textBox1.FontSize += 2;
}
}

private void DecreaseFont_Click(object sender, RoutedEventArgs e)


{
if (textBox1.FontSize > 10)
{
textBox1.FontSize -= 2;
}
}
}
}

When you compile and execute the above code, it will produce the following window:

We recommend that you execute the above example code and try some other properties
and events of ContextMenu.

75
14. DATAGRID WPF

A DataGrid is a control that displays data in a customizable grid. It provides a flexible way
to display a collection of data in rows and columns. The hierarchical inheritance of DataGrid
class is as follows:

Commonly Used Properties of DataGrid


Sr. No. Properties & Description
1 AlternatingRowBackground
Gets or sets the background brush for use on alternating rows.
2 AreRowDetailsFrozen
Gets or sets a value that indicates whether the row details can scroll
horizontally.

76
WPF

3 AutoGenerateColumns
Gets or sets a value that indicates whether the columns are created
automatically.
4 CanUserAddRows
Gets or sets a value that indicates whether the user can add new rows to
the DataGrid.
5 CanUserDeleteRows
Gets or sets a value that indicates whether the user can delete rows from
the DataGrid.
CanUserReorderColumns
6 Gets or sets a value that indicates whether the user can change the column
display order by dragging column headers with the mouse.
CanUserResizeColumns
7 Gets or sets a value that indicates whether the user can adjust the width of
columns by using the mouse.
CanUserResizeRows
8 Gets or sets a value that indicates whether the user can adjust the height of
rows by using the mouse.
CanUserSortColumns
9 Gets or sets a value that indicates whether the user can sort columns by
clicking the column header.
10 ColumnHeaderHeight
Gets or sets the height of the column headers row.
11 ColumnHeaderStyle
Gets or sets the style applied to all column headers in the DataGrid.
12 Columns
Gets a collection that contains all the columns in the DataGrid.
13 ColumnWidth
Gets or sets the standard width and sizing mode of columns and headers in
the DataGrid.
14 CurrentCell
Gets or sets the cell that has focus.
15 CurrentColumn
Gets or sets the column that contains the current cell.
16 CurrentItem
Gets the data item bound to the row that contains the current cell.
17 FrozenColumnCount
Gets or sets the number of non-scrolling columns.
HorizontalScrollBarVisibility
18 Gets or sets a value that indicates how horizontal scroll bars are displayed
in the DataGrid.
IsReadOnly
19 Gets or sets a value that indicates whether the user can edit values in the
DataGrid.
20 RowBackground
Gets or sets the default brush for the row background.
21 RowHeight
Gets or sets the suggested height for all rows.
22 SelectedCells
Gets the list of cells that are currently selected.

77
WPF

Commonly Used Methods of DataGrid


Sr. No. Methods & Description
BeginEdit
1 Invokes the BeginEdit command, which will place the current cell or row into
edit mode.
CancelEdit
2 Invokes the CancelEditCommand command for the cell or row currently in
edit mode.
ClearDetailsVisibilityForItem
3 Clears the DetailsVisibility property for the DataGridRow that represents the
specified data item.
ColumnFromDisplayIndex
4
Gets the DataGridColumn at the specified index.
CommitEdit
5 Invokes the CommitEditCommand command for the cell or row currently in
edit mode.
GenerateColumns
6
Generates columns for the specified properties of an object.
GetDetailsVisibilityForItem
Gets the DetailsVisibility property for the DataGridRow that represents the
7
specified data item.
OnApplyTemplate
When overridden in a derived class, is invoked whenever application code or
8 internal processes call ApplyTemplate. (Overrides
FrameworkElement.OnApplyTemplate().)
ScrollIntoView
9
Scrolls the DataGrid vertically to display the row for the specified data item.
SelectAllCells
10
Selects all the cells in the DataGrid.
SetDetailsVisibilityForItem
Sets the value of the DetailsVisibility property for the DataGridRow that
11
contains the specified object.
UnselectAllCells
12
Unselects all the cells in the DataGrid.

Commonly Used Events of DataGrid


Sr. No. Events & Description
1 AddingNewItem
Occurs before a new item is added to the DataGrid.
2 AutoGeneratedColumns
Occurs when auto generation of all columns is completed.
3 AutoGeneratingColumn
Occurs when an individual column is auto-generated.
4 BeginningEdit
Occurs before a row or cell enters edit mode.
5 CellEditEnding
Occurs before a cell edit is committed or canceled.
6 ColumnDisplayIndexChanged
Occurs when the DisplayIndex property on one of the columns changes.
ColumnHeaderDragCompleted
7 Occurs when the user releases a column header after dragging it by using
the mouse.

78
WPF

8 ColumnHeaderDragDelta
Occurs every time the mouse position changes while the user drags a column
header.
9 ColumnHeaderDragStarted
Occurs when the user begins dragging a column header by using the mouse.
10 ColumnReordered
Occurs when a column moves to a new position in the display order.
11 ColumnReordering
Occurs before a column moves to a new position in the display order.
12 CopyingRowClipboardContent
Occurs after the default row content is prepared.
13 CurrentCellChanged
Occurs when the value of the CurrentCell property has changed.
14 InitializingNewItem
Occurs when a new item is created.
LoadingRow
15 Occurs after a DataGridRow is instantiated, so that you can customize it
before it is used.
16 LoadingRowDetails
Occurs when a new row details template is applied to a row.
17 PreparingCellForEdit
Occurs when a cell enters edit mode.
18 RowDetailsVisibilityChanged
Occurs when the visibility of a row details element changes.
19 RowEditEnding
Occurs before a row edit is committed or canceled.
20 SelectedCellsChanged
Occurs when the SelectedCells collection changes.
21 Sorting
Occurs when a column is being sorted.
22 UnloadingRow
Occurs when a DataGridRow object becomes available for reuse.
23 UnloadingRowDetails
Occurs when a row details element becomes available for reuse.

Example
1. Lets create a new WPF project with WPFDataGridControl name.

2. Drag Data grid from a toolbox.

3. The following example shows how to display data in a DataGrid. Given below is the
XAML code in which two data grids are created with a set of properties and events.

<Window x:Class="WPFDataGridControl.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:core="clr-namespace:System;assembly=mscorlib"
xmlns:local="clr-namespace:WPFDataGridControl"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>

79
WPF

<ObjectDataProvider x:Key="myEnum"
MethodName="GetValues"
ObjectType="{x:Type core:Enum}">
<ObjectDataProvider.MethodParameters>
<x:TypeExtension Type="local:Party" />
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>
<Grid>
<DataGrid Name="dataGrid"
AlternatingRowBackground="LightBlue"
AlternationCount="2"
AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Name"
Binding="{Binding Name}" />
<DataGridTextColumn Header="Title"
Binding="{Binding Title}" />
<DataGridCheckBoxColumn Header="ReElected?"
Binding="{Binding WasReElected}"/>
<DataGridComboBoxColumn Header="Party"
SelectedItemBinding="{Binding Affiliation}"

ItemsSource="{Binding
Source={StaticResource myEnum}}" />
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>

Here is the implementation in C# for two different classes.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
80
WPF

using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WPFDataGridControl {
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>

public partial class MainWindow : Window {

public MainWindow() {
InitializeComponent();
dataGrid.ItemsSource = Employee.GetEmployees();
}
}

public enum Party {


Indepentent,
Federalist,
DemocratRepublican,
}
public class Employee : INotifyPropertyChanged {
private string name;

public string Name {


get { return name; }
set {
name = value;
RaiseProperChanged();
}
}

81
WPF

private string title;

public string Title {


get { return title; }
set {
title = value;
RaiseProperChanged();
}
}

private bool wasReElected;

public bool WasReElected {


get { return wasReElected; }
set {
wasReElected = value;
RaiseProperChanged();
}
}

private Party affiliation;

public Party Affiliation {


get { return affiliation; }
set {
affiliation = value;
RaiseProperChanged();
}
}

public static ObservableCollection<Employee> GetEmployees() {


var employees = new ObservableCollection<Employee>();
employees.Add(new Employee() { Name = "Ali", Title = "Minister",
WasReElected = true,
Affiliation = Party.Indepentent });

82
WPF

employees.Add(new Employee() { Name = "Ahmed", Title = "CM",


WasReElected = false,
Affiliation = Party.Federalist });

employees.Add(new Employee() { Name = "Amjad", Title = "PM",


WasReElected = true,
Affiliation = Party.DemocratRepublican });

employees.Add(new Employee() { Name = "Waqas", Title = "Minister",


WasReElected = false, Affiliation = Party.Indepentent });

employees.Add(new Employee() { Name = "Bilal", Title = "Minister",


WasReElected = true, Affiliation = Party.Federalist });

employees.Add(new Employee() { Name = "Waqar", Title = "Minister",


WasReElected = false, Affiliation = Party.DemocratRepublican });

return employees;
}

public event PropertyChangedEventHandler PropertyChanged;

private void RaiseProperChanged([CallerMemberName] string caller = "") {

if (PropertyChanged != null) {
PropertyChanged(this, new PropertyChangedEventArgs(caller));
}
}
}
}

83
WPF

When you compile and execute the above code, it will produce the following window.

We recommend that you execute the above example code and try some of the other
properties and events of DataGrid.

84
15. DATEPICKER WPF

A DatePicker is a control that allows a user to pick a date value. The user picks the date
by using ComboBox selection for month, day, and year values. The hierarchical inheritance
of DatePicker class is as follows:

Commonly Used Properties of DatePicker


Sr. No. Property & Description
1 CalendarIdentifier
Gets or sets the calendar system to use.
2 CalendarIdentifierProperty
Gets the identifier for the CalendarIdentifier dependency property.
3 Date
Gets or sets the date currently set in the date picker.
4 DateProperty
Gets the identifier for the Date dependency property.
5 DayFormat
Gets or sets the display format for the day value.
6 DayFormatProperty
Gets the identifier for the DayFormat dependency property.
7 DayVisible
Gets or sets a value that indicates whether the day selector is shown.
85
WPF

8 DayVisibleProperty
Gets the identifier for the DayVisible dependency property.
9 Header
Gets or sets the content for the control's header.
10 HeaderProperty
Identifies the Header dependency property.
11 HeaderTemplate
Gets or sets the DataTemplate used to display the content of the control's
header.
12 HeaderTemplateProperty
Identifies the HeaderTemplate dependency property.
13 MaxYear
Gets or sets the maximum Gregorian year available for picking.
14 MaxYearProperty
Gets the identifier for the MaxYear dependency property.
15 MinYear
Gets or sets the minimum Gregorian year available for picking.
16 MinYearProperty
Gets the identifier for the MinYear dependency property.
17 MonthFormat
Gets or sets the display format for the month value.
18 MonthFormatProperty
Gets the identifier for the MonthFormat dependency property.
19 MonthVisible
Gets or sets a value that indicates whether the month selector is shown.
20 MonthVisibleProperty
Gets the identifier for the MonthVisible dependency property.
Orientation
21 Gets or sets a value that indicates whether the day, month, and year selectors
are stacked horizontally or vertically.
22 OrientationProperty
Gets the identifier for the Orientation dependency property.
23 YearFormat
Gets or sets the display format for the year value.
24 YearFormatProperty
Gets the identifier for the YearFormat dependency property.
25 YearVisible
Gets or sets a value that indicates whether the year selector is shown.
26 YearVisibleProperty
Gets the identifier for the YearVisible dependency property.

Commonly Used Events in DatePicker Class

Sr. No. Event & Description

1 DateChanged
Occurs when the date value is changed.
DragEnter
2 Occurs when the input system reports an underlying drag event with this
element as the target. (Inherited from UIElement)
DragLeave
3 Occurs when the input system reports an underlying drag event with this
element as the origin. (Inherited from UIElement)

86
WPF

DragOver
4 Occurs when the input system reports an underlying drag event with this
element as the potential drop target. (Inherited from UIElement)
5 DragStarting
Occurs when a drag operation is initiated. (Inherited from UIElement)
6 GotFocus
Occurs when a UIElement receives focus. (Inherited from UIElement)
Holding
7 Occurs when an otherwise unhandled Hold interaction occurs over the hit test
area of this element. (Inherited from UIElement)
8 IsEnabledChanged
Occurs when the IsEnabled property changes. (Inherited from Control)
KeyDown
9 Occurs when a keyboard key is pressed while the UIElement has focus.
(Inherited from UIElement)
KeyUp
10 Occurs when a keyboard key is released while the UIElement has focus.
(Inherited from UIElement)
11 LostFocus
Occurs when a UIElement loses focus. (Inherited from UIElement)

Commonly Used Methods in DatePicker Class


Sr. Method & Description
No.
ClearValue
1 Clears the local value of a dependency property. (Inherited from
DependencyObject)
FindName
2 Retrieves an object that has the specified identifier name. (Inherited from
FrameworkElement)
OnApplyTemplate
Invoked whenever application code or internal processes (such as a rebuilding
3 layout pass) call ApplyTemplate. In simplest terms, this means the method is
called just before a UI element displays in your app. Override this method to
influence the default post-template logic of a class. (Inherited from
FrameworkElement)
4 OnDragEnter
Called before the DragEnter event occurs. (Inherited from Control)
5 OnDragLeave
Called before the DragLeave event occurs. (Inherited from Control)
6 OnDragOver
Called before the DragOver event occurs. (Inherited from Control)
7 OnDrop
Called before the Drop event occurs. (Inherited from Control)
8 OnGotFocus
Called before the GotFocus event occurs. (Inherited from Control)
9 OnKeyDown
Called before the KeyDown event occurs. (Inherited from Control)
10 OnKeyUp
Called before the KeyUp event occurs. (Inherited from Control)
11 OnLostFocus
Called before the LostFocus event occurs. (Inherited from Control)
12 SetBinding
87
WPF

Attaches a binding to a FrameworkElement, using the provided binding object.


(Inherited from FrameworkElement)

Example
1. Lets create a new WPF project with the name WPFDatePickerControl.

2. Drag a DatePicker from the toolbox.

3. The following example shows how to create a DatePicker control.

4. When you click on any date from the DatePicker control, the program will update
the title with that date.

5. The following XAML code creates a DatePicker with some properties and click event.

<Window x:Class="WPFDatePickerControl.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>
<DatePicker HorizontalAlignment="Center"
Margin="10,10,0,0"
VerticalAlignment="Top"
SelectedDateChanged="DatePicker_SelectedDateChanged"/>
</Grid>
</Window>

Here is the C# implementation for DatePicker_SelectedDateChanged event.

using System;
using System.Windows;
using System.Windows.Controls;

namespace WPFDatePickerControl
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

88
WPF

private void DatePicker_SelectedDateChanged(object sender,


SelectionChangedEventArgs e)
{
var picker = sender as DatePicker;

DateTime? date = picker.SelectedDate;


if (date == null)
{
this.Title = "No date";
}
else
{
this.Title = date.Value.ToShortDateString();
}
}
}
}

When you compile and execute the above code, it will produce the following window.

We recommend that you execute the above example code and try some of the other
properties and events of the DatePicker class.

89
16. DIALOG BOX WPF

All standalone applications have a main window that exposes some functionality and
displays some data over which the application operates through a GUI. An application may
also display additional windows to do the following:

Display some specific information to users


Gather useful information from users
Both display and gather important information

Example
Lets take an example to understand the concept of Dialog Box. First of all, create a new
WPF project with the name WPFDialog.

1. Drag one button and one textbox from the Toolbox.

2. When the user clicks this button, it opens another dialog box with Yes, No, and
Cancel buttons and displays a message click any button on it.

3. When a user clicks any of them, this dialog box gets closed and shows a textbox
with the information of the button that was clicked.

4. Here is the XAML code to initialize a button and a textbox with some properties.

<Window x:Class="WPFDialog.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 Height="23"
Margin="100"
Name="ShowMessageBox"
VerticalAlignment="Top"
Click="ShowMessageBox_Click">Show Message Box</Button>
<TextBox Height="23"
HorizontalAlignment="Left"
Margin="181,167,0,0"
Name="textBox1"
VerticalAlignment="Top"
Width="120" />

90
WPF

</Grid>
</Window>

Here is the C# code in which the button click event is implemented.

using System;
using System.Windows;
using System.Windows.Controls;

namespace WPFDialog
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void ShowMessageBox_Click(object sender, RoutedEventArgs e)
{
string msgtext = "Click any button";
string txt = "My Title";
MessageBoxButton button = MessageBoxButton.YesNoCancel;
MessageBoxResult result = MessageBox.Show(msgtext, txt, button);
switch (result)
{
case MessageBoxResult.Yes:
textBox1.Text = "Yes";
break;
case MessageBoxResult.No:
textBox1.Text = "No";
break;
case MessageBoxResult.Cancel:
textBox1.Text = "Cancel";
break;

91
WPF

}
}
}
}

When you compile and execute the above code, it will produce the following window.

When you click on the button, it displays another dialog box (as shown below) that prompts
the user to click a button.

In case the user clicks the Yes button, it updates the textbox with the button content.

92
17. GRIDVIEW WPF

A GridView is a control that displays data items in rows and columns. Actually a ListView
displays data. By default, it contains a GridView. The hierarchical inheritance of GridView
class is as follows:

Below are the commonly used properties of GridView

Sr. No. Property & Description


Background
1 Gets or sets a brush that provides the background of the control. (Inherited
from Control)
2 BorderThickness
Gets or sets the border thickness of a control. (Inherited from Control)

93
WPF

DataContext
3 Gets or sets the data context for a FrameworkElement when it participates
in data binding. (Inherited from FrameworkElement)
FontFamily
4 Gets or sets the font used to display text in the control. (Inherited from
Control)
5 FontSize
Gets or sets the size of the text in this control. (Inherited from Control)
6 FontStyle
Gets or sets the style in which the text is rendered. (Inherited from Control)
7 FontWeight
Gets or sets the thickness of the specified font. (Inherited from Control)
Foreground
8 Gets or sets a brush that describes the foreground color. (Inherited from
Control)
GroupStyle
9 Gets a collection of GroupStyle objects that define the appearance of each
level of groups. (Inherited from ItemsControl)
10 Header
Gets or sets the content for the list header. (Inherited from ListViewBase)
11 Height
Gets or sets the suggested height of a FrameworkElement. (Inherited from
FrameworkElement)
HorizontalAlignment
12 Gets or sets the horizontal alignment characteristics that are applied to a
FrameworkElement when it is composed in a layout parent, such as a panel
or items control. (Inherited from FrameworkElement)
HorizontalContentAlignment
13 Gets or sets the horizontal alignment of the control's content. (Inherited
from Control)
Items
14 Gets the collection used to generate the content of the control. (Inherited
from ItemsControl)
ItemsSource
15 Gets or sets an object source used to generate the content of the
ItemsControl. (Inherited from ItemsControl)
ItemTemplate
16 Gets or sets the DataTemplate used to display each item. (Inherited from
ItemsControl)
Margin
17 Gets or sets the outer margin of a FrameworkElement. (Inherited from
FrameworkElement)
Name
18 Gets or sets the identifying name of the object. When a XAML processor
creates the object tree from XAML markup, run-time code can refer to the
XAML-declared object by this name. (Inherited from FrameworkElement)
19 Opacity
Gets or sets the degree of the object's opacity. (Inherited from UIElement)
Resources
20 Gets the locally defined resource dictionary. In XAML, you can establish
resource items as child object elements of a frameworkElement.Resources
property element, through XAML implicit collection syntax. (Inherited from
FrameworkElement)
21 SelectedIndex
Gets or sets the index of the selected item. (Inherited from Selector)
94
WPF

22 SelectedItem
Gets or sets the selected item. (Inherited from Selector)
23 SelectedItems
Gets the currently selected items. (Inherited from ListViewBase)
SelectedRanges
24 Gets a collection of ItemIndexRange objects that describe the currently
selected items in the list. (Inherited from ListViewBase)
SelectedValue
25 Gets or sets the value of the selected item, obtained by using the
SelectedValuePath. (Inherited from Selector)
Style
26 Gets or sets an instance Style that is applied for this object during layout and
rendering. (Inherited from FrameworkElement)
VerticalAlignment
27 Gets or sets the vertical alignment characteristics that are applied to a
FrameworkElement when it is composed in a parent object such as a panel
or items control. (Inherited from FrameworkElement)
VerticalContentAlignment
28 Gets or sets the vertical alignment of the control's content. (Inherited from
Control)
Width
29 Gets or sets the width of a FrameworkElement. (Inherited from
FrameworkElement)

Below are the commonly used events in GridView

Sr. No. Event & Description


DataContextChanged
1 Occurs when the value of the FrameworkElement.DataContext property
changes. (Inherited from FrameworkElement)
DragEnter
2 Occurs when the input system reports an underlying drag event with this
element as the target. (Inherited from UIElement)
DragLeave
3 Occurs when the input system reports an underlying drag event with this
element as the origin. (Inherited from UIElement)
DragOver
4 Occurs when the input system reports an underlying drag event with this
element as the potential drop target. (Inherited from UIElement)
5 DragStarting
Occurs when a drag operation is initiated. (Inherited from UIElement)
Drop
6 Occurs when the input system reports an underlying drop event with this
element as the drop target. (Inherited from UIElement)
ImageFailed
7 Occurs when there is an error associated with image retrieval or format.
ImageOpened
8 Occurs when the image source is downloaded and decoded with no failure.
You can use this event to determine the natural size of the image source.
KeyDown
9 Occurs when a keyboard key is pressed while the UIElement has focus.
(Inherited from UIElement)
10 KeyUp

95
WPF

when a keyboard key is released while the UIElement has focus. (Inherited
from UIElement)

Commonly used Methods of GridView.

Sr. No. Method & Description


1 Arrange
Positions child objects and determines a size for a UIElement. Parent objects
that implement custom layout for their child elements should call this method
from their layout override implementations to form a recursive layout update.
(Inherited from UIElement)
2 ClearValue
Clears the local value of a dependency property. (Inherited from
DependencyObject)
3 FindName
Retrieves an object that has the specified identifier name. (Inherited from
FrameworkElement)
4 GetValue
Returns the current effective value of a dependency property from a
DependencyObject. (Inherited from DependencyObject)
5 ReadLocalValue
Returns the local value of a dependency property, if a local value is set.
(Inherited from DependencyObject)
6 SetBinding
Attaches a binding to a FrameworkElement, using the provided binding
object. (Inherited from FrameworkElement)
7 SetValue
Sets the local value of a dependency property on a DependencyObject.
(Inherited from DependencyObject)

Example
1. Lets take an example to understand the concept better. Start by creating a new
WPF project with the name WPFGridView.

2. Drag a grid view control from the Toolbox.

3. The following example shows the data in grid like table.

4. The following XAML code creates and implements a GridView.

<Window x:Class="WPFGridView.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ListView HorizontalAlignment="Left"
Height="299" Margin="10,10,0,0" VerticalAlignment="Top" Width="497"

Name="MenList">
<ListView.View>
96
WPF

<GridView>
<GridViewColumn Header="Name"
DisplayMemberBinding="{Binding Name}"
Width="100"/>
<GridViewColumn Header="ID"
DisplayMemberBinding="{Binding ID}"
Width="100"/>
<GridViewColumn Header="Age"
DisplayMemberBinding="{Binding Age}"
Width="100"/>
</GridView>
</ListView.View>
</ListView>
</Grid>
</Window>

Here is the C# implementation in which person class is implemented.

using System;
using System.Windows;
using System.Windows.Controls;

namespace WPFGridView
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
MenList.Items.Add(new Person() {Name = "Ali", ID = "123A", Age = 20 });
MenList.Items.Add(new Person() {Name = "Akram",ID= "456X", Age = 35 });
MenList.Items.Add(new Person() {Name = "Salman",ID="333E", Age = 49 });
}
}

97
WPF

class Person
{
public string Name { get; set; }
public string ID { get; set; }
public int Age { get; set; }
}
}

When you compile and execute the above code, it will produce the following output.

We recommend that you execute the above example code and try the other properties
and events of GridView.

98
18. IMAGE WPF

A control that displays an image, you can use either the Image object or the ImageBrush
object. An Image object display an image, while an ImageBrush object paints another
object with an image. The image source is specified by referring to an image file using
several supported formats. It can display the following formats;

Bitmap (BMP)
Tagged Image File Format (TIFF)
Icons (ICO)
Joint Photographic Experts Group (JPEG)
Graphics Interchange Format (GIF)
Portable Network Graphics (PNG)
JPEG XR

The hierarchical inheritance of Image class is as follows

Commonly Used Properties of Image class

Sr. No. Property & Description

CanDrag
1 Gets or sets a value that indicates whether the element can be dragged as
data in a drag-and-drop operation. (Inherited from UIElement)
Height
2 Gets or sets the suggested height of a FrameworkElement. (Inherited from
FrameworkElement)

99
WPF

3 HorizontalAlignment
Gets or sets the horizontal alignment characteristics that are applied to a
FrameworkElement when it is composed in a layout parent, such as a panel
or items control. (Inherited from FrameworkElement)
3 Margin
Gets or sets the outer margin of a FrameworkElement. (Inherited from
FrameworkElement)
4 Name
Gets or sets the identifying name of the object. When a XAML processor
creates the object tree from XAML markup, run-time code can refer to the
XAML-declared object by this name. (Inherited from FrameworkElement)
5 Opacity
Gets or sets the degree of the object's opacity. (Inherited from UIElement)
6 PlayToSource
Gets the information that is transmitted if the Image is used for a Play To
scenario.
Resources
Gets the locally defined resource dictionary. In XAML, you can establish
7 resource items as child object elements of a frameworkElement.Resources
property element, through XAML implicit collection syntax. (Inherited from
FrameworkElement)
8 SourceProperty
Identifies the Source dependency property.
9 Stretch
Gets or sets a value that describes how an Image should be stretched to fill
the destination rectangle.
10 StretchProperty
Identifies the Stretch dependency property.
Style
11 Gets or sets an instance Style that is applied for this object during layout
and rendering. (Inherited from FrameworkElement)
VerticalAlignment
12 Gets or sets the vertical alignment characteristics that are applied to a
FrameworkElement when it is composed in a parent object such as a panel
or items control. (Inherited from FrameworkElement)
Width
13 Gets or sets the width of a FrameworkElement. (Inherited from
FrameworkElement)
14 wSource
Gets or sets the source for the image.

Commonly Used Events of Image Class


Sr. No. Event & Description

DataContextChanged
1 Occurs when the value of the FrameworkElement.DataContext property
changes. (Inherited from FrameworkElement)
DragEnter
2 Occurs when the input system reports an underlying drag event with this
element as the target. (Inherited from UIElement)
DragLeave
3 Occurs when the input system reports an underlying drag event with this
element as the origin. (Inherited from UIElement)

100
WPF

DragOver
4 Occurs when the input system reports an underlying drag event with this
element as the potential drop target. (Inherited from UIElement)
5 DragStarting
Occurs when a drag operation is initiated. (Inherited from UIElement)
Drop
6 Occurs when the input system reports an underlying drop event with this
element as the drop target. (Inherited from UIElement)
DropCompleted
7 Occurs when a drag-and-drop operation is ended. (Inherited from
UIElement)
8 GotFocus
Occurs when a UIElement receives focus. (Inherited from UIElement)
9 ImageFailed
Occurs when there is an error associated with image retrieval or format.
ImageOpened
10 Occurs when the image source is downloaded and decoded with no failure.
You can use this event to determine the natural size of the image source.
KeyDown
11 Occurs when a keyboard key is pressed while the UIElement has focus.
(Inherited from UIElement)
KeyUp
12 Occurs when a keyboard key is released while the UIElement has focus.
(Inherited from UIElement)
SizeChanged
13 Occurs when either the ActualHeight or the ActualWidth property changes
value on a FrameworkElement. (Inherited from FrameworkElement)

Example
1. Lets create a new WPF project with the name WPFImageControl.

2. First divide the screen into two rows by using Grid.RowDefinition.

3. Drag three Image controls from the Toolbox.

4. The following example shows three images. The first one is a simple image; in the
second image, opacity property is set; and in the third image, one Eclipse is painted
with an ImageBrush.

5. The XAML code is as follows:

<Window x:Class="WPFImageControl.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="500" Width="604">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="1*"/>
<RowDefinition Height="1*"/>

101
WPF

</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal">
<Image Width="200"
Source="Images\red_rock_01.jpg"
VerticalAlignment="Top"
Margin="30"/>
<Image Width="200"
Source="Images\red_rock_01.jpg"
VerticalAlignment="Top"
Margin="30"
Opacity="0.5"/>
</StackPanel>
<StackPanel Grid.Row="1">
<Ellipse Height="100"
Width="200"
HorizontalAlignment="Center"
Margin="30">
<Ellipse.Fill>
<ImageBrush ImageSource="Images\tahoe_01.jpg" />
</Ellipse.Fill>
</Ellipse>
</StackPanel>
</Grid>
</Window>

102
WPF

When you compile and execute the above code, it will produce the following window:

We recommend that you execute the above example code and try the other properties
and events of the Image class.

103
19. LABEL WPF

The Label class provides both functional and visual support for access keys (also known
as mnemonics). It is frequently used to enable quick keyboard access to controls. The
hierarchical inheritance of Label class is as follows:

Below are the commonly used properties of Label class

Sr. No. Property & Description


Background
1 Gets or sets a brush that describes the background of a control. (Inherited
from Control.)
Content
2 Gets or sets the content of a ContentControl. (Inherited from ContentControl.)

ContentStringFormat
3 Gets or sets a composite string that specifies how to format the Content
property if it is displayed as a string.(Inherited from ContentControl.)
ContentTemplate
4 Gets or sets the data template used to display the content of the
ContentControl. (Inherited from ContentControl.)
104
WPF

ContextMenu
5 Gets or sets the context menu element that should appear whenever the
context menu is requested through user interface (UI) from within this
element.(Inherited from FrameworkElement.)
6 FontFamily
Gets or sets the font family of the control. (Inherited from Control.)
7 FontSize
Gets or sets the font size. (Inherited from Control.)
8 FontStyle
Gets or sets the font style. (Inherited from Control.)
FontWeight
9 Gets or sets the weight or thickness of the specified font. (Inherited from
Control.)
Foreground
10 Gets or sets a brush that describes the foreground color. (Inherited from
Control.)
Height
11 Gets or sets the suggested height of the element.(Inherited from
FrameworkElement.)
Margin
12 Gets or sets the outer margin of an element.(Inherited from
FrameworkElement.)
Name
13 Gets or sets the identifying name of the element. The name provides a
reference so that code-behind, such as event handler code, can refer to a
markup element after it is constructed during processing by a XAML
processor.(Inherited from FrameworkElement.)
Resources
14 Gets or sets the locally-defined resource dictionary. (Inherited from
FrameworkElement.)
Style
15 Gets or sets the style used by this element when it is rendered. (Inherited from
FrameworkElement.)
Target
16 Gets or sets the element that receives focus when the user presses the label's
. GTMT
17 Template
Gets or sets a control template. (Inherited from Control.)
Width
18 Gets or sets the width of the element.(Inherited from FrameworkElement.)

Commonly Used Events of Label Class


Sr. No. Event & Description

1 ContextMenuOpening
Occurs when the system processes an interaction that displays a context
menu.
2 DragEnter
Occurs when the input system reports an underlying drag event with this
element as the target. (Inherited from UIElement)
3 DragLeave
Occurs when the input system reports an underlying drag event with this
element as the origin. (Inherited from UIElement)

105
WPF

DragOver
4 Occurs when the input system reports an underlying drag event with this
element as the potential drop target. (Inherited from UIElement)
Drop
5 Occurs when the input system reports an underlying drop event with this
element as the drop target. (Inherited from UIElement)
6 GotFocus
Occurs when a UIElement receives focus. (Inherited from UIElement)
KeyDown
7 Occurs when a keyboard key is pressed while the UIElement has focus.
(Inherited from UIElement)
KeyUp
8 Occurs when a keyboard key is released while the UIElement has focus.
(Inherited from UIElement)
SizeChanged
9 Occurs when either the ActualHeight or the ActualWidth property changes
value on a FrameworkElement. (Inherited from FrameworkElement)

Commonly Used Methods in Label Class


Sr. Method & Description
No.
1 Focus
Focuses the TextBlock, as if it were a conventionally focusable control.
2 ToString
Returns the string representation of a Control object. (Inherited from Control.)

Example
1. Lets create a new WPF project with the name WPFLabelControl.

2. Drag one label control from the Toolbox.

3. Change the different properties of label from the properties window, as shown in
the following XAML code.

<Window x:Class="WPFLabelControl.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:WPFLabelControl"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="604">
<Grid>
<Label x:Name="label" Content="Label Example in WPF"
HorizontalAlignment="Left" Margin="71,82,0,0"
VerticalAlignment="Top" Height="135" Width="474"
106
WPF

Background="#FFD6BEBE" FontFamily="Snap ITC"


FontSize="36" FontStyle="Italic" FontWeight="Light"
Foreground="#FFBD6B6B"/>
</Grid>
</Window>

When you compile and execute the above code, it will produce the following window.

107
20. LISTBOX WPF

ListBox is a control that provides a list of items to the user item selection. A user can select
one or more items from the predefined list of items at a time. In a ListBox, multiple options
are always visible to the user without any user interaction. The hierarchical inheritance of
ListBox class is as follows:

Below are the commonly used Properties of ListBox class

Sr.
Property & Description
No.
Background
Gets or sets a brush that provides the background of the control. (Inherited
1
from Control)
BorderThickness
2
Gets or sets the border thickness of a control. (Inherited from Control)
FontFamily
3
Gets or sets the font used to display text in the control. (Inherited from Control)
FontSize
4
Gets or sets the size of the text in this control. (Inherited from Control)
108
WPF

FontStyle
5
Gets or sets the style in which the text is rendered. (Inherited from Control)
FontWeight
6
Gets or sets the thickness of the specified font. (Inherited from Control)
Foreground
Gets or sets a brush that describes the foreground color. (Inherited from
7
Control)
GroupStyle
Gets a collection of GroupStyle objects that define the appearance of each level
8
of groups. (Inherited from ItemsControl)
Height
Gets or sets the suggested height of a FrameworkElement. (Inherited from
9
FrameworkElement)
HorizontalAlignment
Gets or sets the horizontal alignment characteristics that are applied to a
10 FrameworkElement when it is composed in a layout parent, such as a panel or
items control. (Inherited from FrameworkElement)
IsEnabled
Gets or sets a value indicating whether the user can interact with the control.
11
(Inherited from Control)
Item
Gets the collection used to generate the content of the control. (Inherited from
12
ItemsControl)
ItemsSource
Gets or sets an object source used to generate the content of the ItemsControl.
13
(Inherited from ItemsControl)
Margin
Gets or sets the outer margin of a FrameworkElement. (Inherited from
14
FrameworkElement)
Name
Gets or sets the identifying name of the object. When a XAML processor creates
15 the object tree from XAML markup, run-time code can refer to the XAML-
declared object by this name. (Inherited from FrameworkElement)
Opacity
16
Gets or sets the degree of the object's opacity. (Inherited from UIElement)
SelectedIndex
17
Gets or sets the index of the selected item. (Inherited from Selector)
SelectedItem
18
Gets or sets the selected item. (Inherited from Selector)
SelectedValue
Gets or sets the value of the selected item, obtained by using the
19
SelectedValuePath. (Inherited from Selector)
Style
Gets or sets an instance Style that is applied for this object during layout and
20
rendering. (Inherited from FrameworkElement)
VerticalAlignment
Gets or sets the vertical alignment characteristics that are applied to a
21 FrameworkElement when it is composed in a parent object such as a panel or
items control. (Inherited from FrameworkElement)
Width
Gets or sets the width of a FrameworkElement. (Inherited from
22
FrameworkElement)

109
WPF

Commonly Used Events of ListBox


Sr.
Event & Description
No.
DragEnter
1 Occurs when the input system reports an underlying drag event with this
element as the target. (Inherited from UIElement)
DragLeave
2 Occurs when the input system reports an underlying drag event with this
element as the origin. (Inherited from UIElement)
DragOver
3 Occurs when the input system reports an underlying drag event with this
element as the potential drop target. (Inherited from UIElement)
DragStarting
4
Occurs when a drag operation is initiated. (Inherited from UIElement)
Drop
5 Occurs when the input system reports an underlying drop event with this
element as the drop target. (Inherited from UIElement)
DropCompleted
6
Occurs when a drag-and-drop operation is ended. (Inherited from UIElement)
GotFocus
7
Occurs when a UIElement receives focus. (Inherited from UIElement)
IsEnabledChanged
8
Occurs when the IsEnabled property changes. (Inherited from Control)
KeyDown
Occurs when a keyboard key is pressed while the UIElement has focus.
9
(Inherited from UIElement)
KeyUp
Occurs when a keyboard key is released while the UIElement has focus.
10
(Inherited from UIElement)
LostFocus
11
Occurs when a UIElement loses focus. (Inherited from UIElement)
SelectionChanged
12
Occurs when the currently selected item changes. (Inherited from Selector)
SizeChanged
Occurs when either the ActualHeight or the ActualWidth property changes value
13
on a FrameworkElement. (Inherited from FrameworkElement)

Commonly Used Methods of ListBox


Sr. Method & Description
No.
Arrange
Positions child objects and determines a size for a UIElement. Parent objects
1 that implement custom layout for their child elements should call this method
from their layout override implementations to form a recursive layout update.
(Inherited from UIElement)
FindName
2 Retrieves an object that has the specified identifier name. (Inherited from
FrameworkElement)
3 Focus
Attempts to set the focus on the control. (Inherited from Control)
GetValue
4 Returns the current effective value of a dependency property from a
DependencyObject. (Inherited from DependencyObject)
110
WPF

5 IndexFromContainer
Returns the index to the item that has the specified, generated container.
(Inherited from ItemsControl)
6 OnDragEnter
Called before the DragEnter event occurs. (Inherited from Control)
7 OnDragLeave
Called before the DragLeave event occurs. (Inherited from Control)
8 OnDragOver
Called before the DragOver event occurs. (Inherited from Control)
9 OnDrop
Called before the Drop event occurs. (Inherited from Control)
10 OnKeyDown
Called before the KeyDown event occurs. (Inherited from Control)
11 OnKeyUp
Called before the KeyUp event occurs. (Inherited from Control)
12 OnLostFocus
Called before the LostFocus event occurs. (Inherited from Control)
ReadLocalValue
13 Returns the local value of a dependency property, if a local value is set.
(Inherited from DependencyObject)
SetBinding
14 Attaches a binding to a FrameworkElement, using the provided binding object.
(Inherited from FrameworkElement)
SetValue
15 Sets the local value of a dependency property on a DependencyObject.
(Inherited from DependencyObject)

Example
1. Lets create a new WPF project with the name WPFListBoxControl.

2. Drag one list box and one textbox from the Toolbox.

3. When the user selects any item from the ListBox, it displayed on the TextBox as
well.

4. Here is the XAML code in which a ListBox and a TextBox is created and initialized
with some properties.

<Window x:Class="WPFListBoxControl.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:WPFListBoxControl"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="604">
<Grid>
<ListBox Name="listbox" Margin="118,77,293,103">

111
WPF

<ListBoxItem Content="XAML Tutorials"/>


<ListBoxItem Content="WPF Tutorials"/>
<ListBoxItem Content="Silverlight Tutorials"/>
<ListBoxItem Content="Windows 10 Tutorials"/>
<ListBoxItem Content="iOS Tutorials"/>
</ListBox>
<TextBox Height="23"
x:Name="textBox1"
Width="120"
Margin="361,116,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Text="{Binding SelectedItem.Content, ElementName=listbox}" />
</Grid>
</Window>

When the above code is compiled and executed, it will produce the following output:

We recommend that you execute the above example code and try the other properties
and events of ListBox control.

112
21. MENU WPF

Menu is a control that enables you to hierarchically organize elements associated with the
commands and event handlers. Menu is an ItemsControl, so it can contain a collection of
any object type such as string, image, or panel. The hierarchical inheritance of Menu class
is as follows:

Below are the commonly used properties on Menu class

Sr. No. Name & Description


Background
1 Gets or sets a brush that describes the background of a control. (Inherited
from Control.)
BindingGroup
2 Gets or sets the BindingGroup that is used for the element. (Inherited from
FrameworkElement.)

113
WPF

BitmapEffect
3 Obsolete. Gets or sets a bitmap effect that applies directly to the rendered
content for this element. This is a dependency property. (Inherited from
UIElement.)
4 BorderThickness
Gets or sets the border thickness of a control. (Inherited from Control.)
ContextMenu
5 Gets or sets the context menu element that should appear whenever the
context menu is requested through user interface (UI) from within this
element. (Inherited from FrameworkElement.)
6 Effect
Gets or sets the bitmap effect to apply to the UIElement. This is a dependency
property. (Inherited from UIElement.)
Height
7 Gets or sets the suggested height of the element. (Inherited from
FrameworkElement.)
IsMainMenu
8 Gets or sets a value that indicates whether this Menu receives a main menu
activation notification.
Items
9 Gets the collection used to generate the content of the ItemsControl.
(Inherited from ItemsControl.)
ItemsPanel
10 Gets or sets the template that defines the panel that controls the layout of
items. (Inherited from ItemsControl.)
ItemsSource
11 Gets or sets a collection used to generate the content of the ItemsControl.
(Inherited from ItemsControl.)
ItemStringFormat
12 Gets or sets a composite string that specifies how to format the items in the
ItemsControl if they are displayed as strings. (Inherited from ItemsControl.)
ItemTemplate
13 Gets or sets the DataTemplate used to display each item. (Inherited from
ItemsControl.)
ToolTip
14 Gets or sets the tool-tip object that is displayed for this element in the user
interface (UI). (Inherited from FrameworkElement.)
VerticalContentAlignment
15 Gets or sets the vertical alignment of the control's content. (Inherited from
Control.)
16 Width
Gets or sets the width of the element. (Inherited from FrameworkElement.)

Commonly Used Events in Menu Class

Sr. No. Event & Description

ContextMenuClosing
1 Occurs just before any context menu on the element is closed. (Inherited
from FrameworkElement.)
ContextMenuOpening
2 Occurs when any context menu on the element is opened. (Inherited from
FrameworkElement.)

114
WPF

KeyDown
3 Occurs when a key is pressed while focus is on this element. (Inherited from
UIElement.)
KeyUp
4 Occurs when a key is released while focus is on this element. (Inherited from
UIElement.)
ToolTipClosing
5 Occurs just before any tooltip on the element is closed. (Inherited from
FrameworkElement.)
ToolTipOpening
6 Occurs when any tooltip on the element is opened. (Inherited from
FrameworkElement.)
TouchDown
7 Occurs when a finger touches the screen while the finger is over this element.
(Inherited from UIElement.)
TouchEnter
8 Occurs when a touch moves from outside to inside the bounds of this
element. (Inherited from UIElement.)
TouchLeave
9 Occurs when a touch moves from inside to outside the bounds of this
element. (Inherited from UIElement.)
TouchMove
10 Occurs when a finger moves on the screen while the finger is over this
element. (Inherited from UIElement.)
TouchUp
11 Occurs when a finger is raised off of the screen while the finger is over this
element. (Inherited from UIElement.)

Example
1. Lets create a new WPF project with the name WPFMenuControl.

2. Drag a menu control from the Toolbox to the design window.

3. The following example contains three menu options with some menu items. When
the user clicks an item, the program updates the title. Here is the XAML code:

<Window x:Class="WPFMenuControl.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:WPFMenuControl"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="604">
<Grid>
<Menu HorizontalAlignment="Left" VerticalAlignment="Top" Width="517">
<MenuItem Header="File">
<MenuItem Header="Item 1" HorizontalAlignment="Left" Width="140"

115
WPF

Click="MenuItem_Click"/>
<MenuItem Header="Item 2" HorizontalAlignment="Left" Width="140"

Click="MenuItem_Click"/>
<Separator HorizontalAlignment="Left" Width="140"/>
<MenuItem Header="Item 3" HorizontalAlignment="Left" Width="140"

Click="MenuItem_Click"/>
</MenuItem>
<MenuItem Header="Edit">
<MenuItem Header="Item 1" HorizontalAlignment="Left" Width="140"

Click="MenuItem_Click1"/>
<MenuItem Header="Item 2" HorizontalAlignment="Left" Width="140"

Click="MenuItem_Click1"/>
<Separator HorizontalAlignment="Left" Width="140"/>
<MenuItem Header="Item 3" HorizontalAlignment="Left" Width="140"

Click="MenuItem_Click1"/>
</MenuItem>
<MenuItem Header="View">
<MenuItem Header="Item 1" HorizontalAlignment="Left" Width="140"

Click="MenuItem_Click2"/>
<MenuItem Header="Item 2" HorizontalAlignment="Left" Width="140"

Click="MenuItem_Click2"/>
<Separator HorizontalAlignment="Left" Width="140"/>
<MenuItem Header="Item 3" HorizontalAlignment="Left" Width="140"
Click="MenuItem_Click2"/>
</MenuItem>
</Menu>
</Grid>
</Window>

Here is the events implementation in C#.

using System.Windows;
using System.Windows.Controls;

namespace WPFMenuControl
{
/// <summary>
/// Interaction logic for MainWindow.xaml

116
WPF

/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
MenuItem item = sender as MenuItem;
this.Title = "File: " + item.Header;
}
private void MenuItem_Click1(object sender, RoutedEventArgs e)
{
MenuItem item = sender as MenuItem;
this.Title = "Edit: " + item.Header;

}
private void MenuItem_Click2(object sender, RoutedEventArgs e)
{
MenuItem item = sender as MenuItem;
this.Title = "View: " + item.Header;
}
}
}

When you compile and execute the above code, it will produce the following output:

117
WPF

We recommend that you execute the above example code and try the other properties
and events of Menu class.

118
22. PASSWORDBOX WPF

PasswordBox is a control that allows the user to enter masked passwords. When the user
enters a password, it will be displayed as password characters. You can change the
Password character by setting the PasswordChar property. The hierarchical inheritance of
PasswordBox class is as follows:

Commonly Used Properties of PasswordBox Class


Sr. No. Property & Description
1 InputScope
Gets or sets the context for input used by this PasswordBox.
2 InputScopeProperty
Identifies the InputScope dependency property.
IsPasswordRevealButtonEnabled
3 Gets or sets a value that specifies whether the visual UI of the PasswordBox
includes a button element that toggles showing or hiding the typed
characters. In Windows 10 and later, use PasswordRevealMode instead.
4 IsPasswordRevealButtonEnabledProperty
Identifies the IsPasswordRevealButtonEnabled dependency property.
MaxLength
5 Gets or sets the maximum length for passwords to be handled by this
PasswordBox.
6 MaxLengthProperty

119
WPF

Identifies the MaxLength dependency property.


7 Password
Gets or sets the password currently held by the PasswordBox.
8 PasswordChar
Gets or sets the masking character for the PasswordBox.
9 PasswordCharProperty
Identifies the PasswordChar dependency property.
10 PasswordProperty
Identifies the Password dependency property.
PasswordRevealMode
11 Gets or sets a value that specifies whether the password is always, never,
or optionally obscured.
12 PasswordRevealModeProperty
Identifies the PasswordRevealMode dependency property.
Resources
Gets the locally defined resource dictionary. In XAML, you can establish
13 resource items as child object elements of a frameworkElement.Resources
property element, through XAML implicit collection syntax. (Inherited from
FrameworkElement)

Commonly Used Events of PasswordBox Class


Sr. No. Event & Description
1 ContextMenuOpening
Occurs when the system processes an interaction that displays a context
menu.
2 GotFocus
Occurs when a UIElement receives focus. (Inherited from UIElement)
3 PasswordChanged
Occurs when the value of the Password property changes.
4 Paste
Occurs when text is pasted into the control.

Below are the commonly used Methods of PasswordBox class.

Sr. No. Method & Description


1 OnLostFocus
Called before the LostFocus event occurs. (Inherited from Control)
2 SelectAll
Selects all the characters in the PasswordBox.
3 SetBinding
Attaches a binding to a FrameworkElement, using the provided binding
object. (Inherited from FrameworkElement)
4 SetValue
Sets the local value of a dependency property on a DependencyObject.
(Inherited from DependencyObject)

The following example shows the PasswordBox, labels, and button. Here is the XAML code
in which all these controls are created and initialized.

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

120
WPF

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="604">
<Grid >
<PasswordBox x:Name="pwBox"
Height="35"
Width="200"
MaxLength="8"
Margin="159,55,158,229" />
<Label Content="Password"
HorizontalAlignment="Left"
Margin="108,61,0,0"
VerticalAlignment="Top"
Width="70" />
<Button Content="Ok"
HorizontalAlignment="Left"
Margin="406,64,0,0"
VerticalAlignment="Top"
Width="75" Click="Button_Click"/>
<Label Name="statusText"
HorizontalAlignment="Left"
Margin="159,128,0,0"
VerticalAlignment="Top"
Width="200"
Height="38"/>
</Grid>
</Window>

Here is the button click event implementation in C# in which the program compares if
the entered password is wpf12345 then it will display the correct password message on
the textblock.

using System.Windows;

namespace WPFPasswordBoxControl
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>

121
WPF

public partial class MainWindow : Window


{
public MainWindow()
{
InitializeComponent();
}

private void Button_Click(object sender, RoutedEventArgs e)


{
if (pwBox.Password.ToString() == "wpf12345")
statusText.Text = "Password Accepted";
else
statusText.Text = "Wrong Password";
}
}
}

When the above code is compiled and executed, it will produce the following window:

We recommend that you execute the above example code and try the other properties
and events of PasswordBox class.

122
23. POPUP WPF

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. The hierarchical
inheritance of Popup class is as follows:

Commonly Used Properties of Popup Class


Sr. No. Property & Description
1 Child
Gets or sets the content to be hosted in the popup.
2 ChildProperty
Gets the identifier for the Child dependency property.
ChildTransitions
3 Gets or sets the collection of Transition style elements that apply to child
content of a Popup.
4 ChildTransitionsProperty
Identifies the ChildTransitions dependency property.
HorizontalOffset
5 Gets or sets the distance between the left side of the application window and
the left side of the popup.
6 HorizontalOffsetProperty
Gets the identifier for the HorizontalOffset dependency property.
7 IsLightDismissEnabled
Gets or sets a value that determines how the Popup can be dismissed.
8 IsLightDismissEnabledProperty
Identifies the IsLightDismissEnabled dependency property.
9 IsOpen

123
WPF

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


10 IsOpenProperty
Gets the identifier for the IsOpen dependency property.
11 VerticalOffset
Gets or sets the distance between the top of the application window and the
top of the popup.
12 VerticalOffsetProperty
Gets the identifier for the VerticalOffset dependency property.

Commonly Used Events of Popup Class


Sr. No. Event & Description
1 Closed
Fires when the IsOpen property is set to false.
2 Opened
Fires when the IsOpen property is set to true.

Example
1. Lets create a new WPF project with the name WPFPopupControl.

2. When you look at the Toolbox, you will observe that there is no popup control. But
you can add a popup control to you app from XAML.

3. The following example shows how to use Popup control. Here is the XAML code in
which a Popup control and a CheckBox is created and initialized. When the user
checks the CheckBox, it displays a Popup.

<Window x:Class="WPFPopupControl.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:WPFPopupControl"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="604">
<Grid>
<CheckBox Name="PCheckBox" Margin="198,94,208,194"
Content="Checked Me"/>
<Popup IsOpen="{Binding ElementName=PCheckBox,Path=IsChecked}"
PlacementTarget="{Binding ElementName=PCheckBox}"
AllowsTransparency="True"
PopupAnimation="Slide">
<Canvas Width="125" Height="100" Background="LightGray">
<Canvas.RenderTransform>
124
WPF

<RotateTransform x:Name="theTransform" />


</Canvas.RenderTransform>
<TextBlock TextWrapping="Wrap"
Foreground="Blue"
Text="Hi, this is Popup"/>
</Canvas>
</Popup>
</Grid>
</Window>

When you compile and execute the above code, it will produce the following output. When
you tick the checkbox, a popup will appear; and when you uncheck the checkbox, the
popup will disappear.

We recommend that you execute the above example code and try the other properties
and events of popup class.

125
24. PROGRESSBAR WPF

ProgressBar 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.

The hierarchical inheritance of ProgressBar class is as follows:

Commonly Used Properties of ProgressBar


Sr. No. Property & Description
IsIndeterminate
1 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.
2 IsIndeterminateProperty
Identifies the IsIndeterminate dependency property.
3 ShowError
Gets or sets a value that indicates whether the progress bar should use visual
states that communicate an Error state to the user.

126
WPF

4 ShowErrorProperty
Identifies the ShowError dependency property.
5 ShowPaused
Gets or sets a value that indicates whether the progress bar should use visual
states that communicate a Paused state to the user.
6 ShowPausedProperty
Identifies the ShowPaused dependency property.
7 TemplateSettings
Gets an object that provides calculated values that can be referenced as
TemplateBinding sources when defining templates for a ProgressBar control.

Commonly Used Events in ProgressBar Class


Sr. No. Event & Description
1 ManipulationCompleted
Occurs when a manipulation on the UIElement is complete. (Inherited from
UIElement)
2 ManipulationDelta
Occurs when the input device changes position during a manipulation.
(Inherited from UIElement)
3 ManipulationInertiaStarting
Occurs when the input device loses contact with the UIElement object during
a manipulation and inertia begins. (Inherited from UIElement)
4 ManipulationStarted
Occurs when an input device begins a manipulation on the UIElement.
(Inherited from UIElement)
5 ManipulationStarting
Occurs when the manipulation processor is first created. (Inherited from
UIElement)
6 ValueChanged
Occurs when the range value changes. (Inherited from RangeBase)

Commonly Used Methods in ProgressBar Class


Sr. No. Method & Description
OnManipulationCompleted
1 Called before the ManipulationCompleted event occurs. (Inherited from
Control)
2 OnManipulationDelta
Called before the ManipulationDelta event occurs. (Inherited from Control)
3 OnManipulationInertiaStarting
Called before the ManipulationInertiaStarting event occurs. (Inherited from
Control)
4 OnManipulationStarted
Called before the ManipulationStarted event occurs. (Inherited from Control)
5 OnManipulationStarting
Called before the ManipulationStarting event occurs. (Inherited from Control)
6 OnMaximumChanged
Called when the Maximum property changes. (Inherited from RangeBase)
7 OnMinimumChanged
Called when the Minimum property changes. (Inherited from RangeBase)
8 OnValueChanged
Fires the ValueChanged routed event. (Inherited from RangeBase)
9 SetBinding

127
WPF

Attaches a binding to a FrameworkElement, using the provided binding object.


(Inherited from FrameworkElement)
10 SetValue
Sets the local value of a dependency property on a DependencyObject.
(Inherited from DependencyObject)

Example
1. Lets create a new WPF project with the name WPFProgressBarControl.

2. The following example shows how to use the ProgressBar control. Here is the XAML
code in which two ProgressBar controls are created and initialized.

<Window x:Class="WPFProgressBarControl.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:WPFProgressBarControl"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="604">
<Grid>
<StackPanel x:Name="LayoutRoot" Margin="20">
<Border BorderThickness="5" BorderBrush="Green">
<StackPanel Background="White">
<TextBlock HorizontalAlignment="Center" Margin="10"
Text="Value-Based Progress Bar" />
<ProgressBar x:Name="pg1" Value="100" Margin="10" Maximum="200"

Height="15" IsIndeterminate="False" />


</StackPanel>
</Border>
<Border BorderThickness="5" BorderBrush="Green">
<StackPanel Background="White">
<TextBlock HorizontalAlignment="Center"
Margin="10" Text="Indeterminate Progress Bar" />
<ProgressBar x:Name="pg2" Margin="10" Height="15"
IsIndeterminate="True" />
</StackPanel>
</Border>
</StackPanel>
</Grid>
128
WPF

</Window>

When you compile and execute the above code, it will produce the following window.

We recommend that you execute the above example code and try the other properties
and events of the ProgressBar class.

129
25. RADIOBUTTON WPF

A Radio Button is a control that allows a user to select a single option from a group of
options. The user is limited to select a single option from a related list of options which
are mutually exclusive. It has only two options;

Selected
Cleared

The hierarchical inheritance of RadioButton class is as follows:

130
WPF

Commonly Used Properties of RadioButton


Sr. Property & Description
No.
1 Background
Gets or sets a brush that provides the background of the control. (Inherited
from Control)
2 BorderBrush
Gets or sets a brush that describes the border fill of a control. (Inherited from
Control)
3 BorderThickness
Gets or sets the border thickness of a control. (Inherited from Control)
4 Content
Gets or sets the content of a ContentControl. (Inherited from ContentControl)
5 ClickMode
Gets or sets a value that indicates when the Click event occurs, in terms of
device behavior. (Inherited from ButtonBase)
6 ContentTemplate
Gets or sets the data template that is used to display the content of the
ContentControl. (Inherited from ContentControl)
7 FontFamily
Gets or sets the font used to display text in the control. (Inherited from
Control)
8 FontSize
Gets or sets the size of the text in this control. (Inherited from Control)
9 FontStyle
Gets or sets the style in which the text is rendered. (Inherited from Control)
10 FontWeight
Gets or sets the thickness of the specified font. (Inherited from Control)
11 Foreground
Gets or sets a brush that describes the foreground color. (Inherited from
Control)
12 Height
Gets or sets the suggested height of a FrameworkElement. (Inherited from
FrameworkElement)
13 HorizontalAlignment
Gets or sets the horizontal alignment characteristics that are applied to a
FrameworkElement when it is composed in a layout parent, such as a panel
or items control. (Inherited from FrameworkElement)
14 IsChecked
Gets or sets whether the ToggleButton is checked. (Inherited from
ToggleButton)
15 IsEnabled
Gets or sets a value indicating whether the user can interact with the control.
(Inherited from Control)
16 IsPressed
Gets a value that indicates whether a ButtonBase is currently in a pressed
state. (Inherited from ButtonBase)
17 IsThreeState
Gets or sets a value that indicates whether the control supports three states.
(Inherited from ToggleButton)
18 Margin
Gets or sets the outer margin of a FrameworkElement. (Inherited from
FrameworkElement)

131
WPF

19 Name
Gets or sets the identifying name of the object. When a XAML processor
creates the object tree from XAML markup, run-time code can refer to the
XAML-declared object by this name. (Inherited from FrameworkElement)
20 Opacity
Gets or sets the degree of the object's opacity. (Inherited from UIElement)
21 Resources
Gets the locally defined resource dictionary. In XAML, you can establish
resource items as child object elements of a frameworkElement.Resources
property element, through XAML implicit collection syntax. (Inherited from
FrameworkElement)
Style
22 Gets or sets an instance Style that is applied for this object during layout and
rendering. (Inherited from FrameworkElement)
Template
23 Gets or sets a control template. The control template defines the visual
appearance of a control in UI, and is defined in XAML markup. (Inherited from
Control)
VerticalAlignment
24 Gets or sets the vertical alignment characteristics that are applied to a
FrameworkElement when it is composed in a parent object such as a panel or
items control. (Inherited from FrameworkElement)
Visibility
25 Gets or sets the visibility of a UIElement. A UIElement that is not visible is not
rendered and does not communicate its desired size to layout. (Inherited from
UIElement)
Width
26 Gets or sets the width of a FrameworkElement. (Inherited from
FrameworkElement)

Commonly Used Methods of RadioButton


Sr. Method & Description
No.
ClearValue
1 Clears the local value of a dependency property. (Inherited from
DependencyObject)
FindName
2 Retrieves an object that has the specified identifier name. (Inherited from
FrameworkElement)
OnApplyTemplate
Invoked whenever application code or internal processes (such as a rebuilding
3 layout pass) call ApplyTemplate. In simplest terms, this means the method is
called just before a UI element displays in your app. Override this method to
influence the default post-template logic of a class. (Inherited from
FrameworkElement)
OnContentChanged
4 Invoked when the value of the Content property changes. (Inherited from
ContentControl)
5 OnDragEnter
Called before the DragEnter event occurs. (Inherited from Control)
6 OnDragLeave
Called before the DragLeave event occurs. (Inherited from Control)
7 OnDragOver
Called before the DragOver event occurs. (Inherited from Control)

132
WPF

8 OnDrop
Called before the Drop event occurs. (Inherited from Control)
9 OnGotFocus
Called before the GotFocus event occurs. (Inherited from Control)
10 OnKeyDown
Called before the KeyDown event occurs. (Inherited from Control)
11 OnKeyUp
Called before the KeyUp event occurs. (Inherited from Control)
12 OnLostFocus
Called before the LostFocus event occurs. (Inherited from Control)
13 OnToggle
Called when the ToggleButton receives toggle stimulus. (Inherited from
ToggleButton)
14 SetBinding
Attaches a binding to a FrameworkElement, using the provided binding object.
(Inherited from FrameworkElement)

Commonly Used Events of RadioButton


Sr. Event & Description
No.
1 Checked
Fires when a ToggleButton is checked. (Inherited from ToggleButton)
2 Click
Occurs when a button control is clicked. (Inherited from ButtonBase)
3 DataContextChanged
Occurs when the value of the FrameworkElement.DataContext property
changes. (Inherited from FrameworkElement)
4 DragEnter
Occurs when the input system reports an underlying drag event with this
element as the target. (Inherited from UIElement)
5 DragLeave
Occurs when the input system reports an underlying drag event with this
element as the origin. (Inherited from UIElement)
6 DragOver
Occurs when the input system reports an underlying drag event with this
element as the potential drop target. (Inherited from UIElement)
7 DragStarting
Occurs when a drag operation is initiated. (Inherited from UIElement)
8 GotFocus
Occurs when a UIElement receives focus. (Inherited from UIElement)
9 Holding
Occurs when an otherwise unhandled Hold interaction occurs over the hit test
area of this element. (Inherited from UIElement)
10 Intermediate
Fires when the state of a ToggleButton is switched to the indeterminate state.
(Inherited from ToggleButton)
11 IsEnabledChanged
Occurs when the IsEnabled property changes. (Inherited from Control)
12 KeyDown
Occurs when a keyboard key is pressed while the UIElement has focus.
(Inherited from UIElement)
13 KeyUp
Occurs when a keyboard key is released while the UIElement has focus.
(Inherited from UIElement)
133
WPF

14 LostFocus
Occurs when a UIElement loses focus. (Inherited from UIElement)
15 SizeChanged
Occurs when either the ActualHeight or the ActualWidth property changes
value on a FrameworkElement. (Inherited from FrameworkElement)
16 Unchecked
Occurs when a ToggleButton is unchecked. (Inherited from ToggleButton)

Example
1. Lets create a new WPF project with the name WPFDialog.

2. Drag five radio buttons and four text blocks from the Toolbox and arrange them as
shown in the following XAML code.

3. The following example shows how to use a RadioButton. We will display two groups
of RadioButton. When a user selects an option, then the program will display the
message on a TextBlock. Here is the XAML code.

<Window x:Class="WPFRadioButtonControl.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:WPFRadioButtonControl"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="604">
<Grid>
<TextBlock x:Name="textBlock" HorizontalAlignment="Left"
Margin="23,68,0,0" TextWrapping="Wrap"
Text="Gender:" VerticalAlignment="Top"
Width="83"/>
<TextBlock x:Name="textBlock1" HorizontalAlignment="Left"
Margin="23,134,0,0" TextWrapping="Wrap"
Text="Marital Status:" VerticalAlignment="Top"
Width="83"/>
<RadioButton x:Name="rb1" Content="Male" HorizontalAlignment="Left"
Margin="126,68,0,0" VerticalAlignment="Top"
GroupName="Gender" Width="69" Checked="HandleCheck"/>
<RadioButton x:Name="rb2" Content="Female" HorizontalAlignment="Left"
Margin="201,68,0,0" VerticalAlignment="Top"
GroupName="Gender" Width="81" Checked="HandleCheck"/>
<RadioButton x:Name="rb3" Content="Single" HorizontalAlignment="Left"
134
WPF

Margin="126,134,0,0" VerticalAlignment="Top"
GroupName="Status" Width="69" Checked="HandleCheck1"/>
<RadioButton x:Name="radioButton" Content="Engaged" HorizontalAlignment="Left"

Margin="201,134,0,0" VerticalAlignment="Top"
GroupName="Status" Width="89" Checked="HandleCheck1"/>
<RadioButton x:Name="radioButton1" Content="Married"
GroupName="Status" HorizontalAlignment="Left"
Margin="302,134,0,0" VerticalAlignment="Top"
Width="95" Checked="HandleCheck1"/>
<TextBlock x:Name="textBlock2" HorizontalAlignment="Left"
Margin="386,68,0,0" TextWrapping="Wrap"
VerticalAlignment="Top" Width="191" Height="26"/>
<TextBlock x:Name="textBlock3" HorizontalAlignment="Left"
Margin="386,134,0,0" TextWrapping="Wrap"
VerticalAlignment="Top" Width="146" Height="31"/>
</Grid>
</Window>

Here is the implementation in C# for different events.

using System.Windows;
using System.Windows.Controls;

namespace WPFRadioButtonControl
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private void HandleCheck1(object sender, RoutedEventArgs e)


{
RadioButton rb = sender as RadioButton;
135
WPF

textBlock3.Text = "You are " + rb.Content;


}

private void HandleCheck(object sender, RoutedEventArgs e)


{
RadioButton rb = sender as RadioButton;
textBlock2.Text = "You are " + rb.Content;
}
}
}

When you compile and execute the above code, it will produce the following window.

We recommend that you execute the above example code and try the other properties
and events of RadioButton.

136
26. SCROLLVIEWER WPF

A ScrollViewer is a control that provides a scrollable area that can contain other visible
elements. The hierarchical inheritance of ScrollViewer class is as follows:

Commonly Used Properties of ScrollViewer Class


Sr. No. Property & Description

1 ComputedHorizontalScrollBarVisibility
Gets a value that indicates whether the horizontal ScrollBar is visible.
2 ComputedHorizontalScrollBarVisibilityProperty
Identifies the ComputedHorizontalScrollBarVisibility dependency property.
3 HorizontalScrollBarVisibility
Gets or sets a value that indicates whether a horizontal ScrollBar should be
displayed.
4 HorizontalScrollBarVisibilityProperty
Identifies the HorizontalScrollBarVisibility dependency property.

137
WPF

HorizontalScrollMode
5 Gets or sets a value that determines how manipulation input influences
scrolling behavior on the horizontal axis.
HorizontalScrollModeProperty
6 Identifies the HorizontalScrollMode dependency property.
HorizontalSnapPointsAlignment
7 Gets or sets a value that indicates how the existing snap points are
horizontally aligned versus the initial viewport.
8 HorizontalSnapPointsAlignmentProperty
Identifies the HorizontalSnapPointsAlignment dependency property.
9 IsHorizontalScrollChainingEnabled
Gets or sets a value that indicates whether scroll chaining is enabled from
this child to its parent, for the horizontal axis.
10 IsHorizontalScrollChainingEnabledProperty
Identifies the IsHorizontalScrollChainingEnabled dependency property.
11 IsScrollInertiaEnabled
Gets or sets a value that indicates whether scroll actions should include
inertia in their behavior and value.
12 IsScrollInertiaEnabledProperty
Identifies the IsScrollInertiaEnabled dependency property.
IsVerticalScrollChainingEnabled
13 Gets or sets a value that indicates whether scroll chaining is enabled from
this child to its parent, for the vertical axis.
14 IsVerticalScrollChainingEnabledProperty
Identifies the IsVerticalScrollChainingEnabled dependency property.
ScrollableHeight
15 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.
16 ScrollableHeightProperty
Identifies the ScrollableHeight dependency property.
ScrollableWidth
17 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.
18 ScrollableWidthProperty
Identifies the ScrollableWidth dependency property.
VerticalScrollBarVisibility
19 Gets or sets a value that indicates whether a vertical ScrollBar should be
displayed.
20 VerticalScrollBarVisibilityProperty
Identifies the VerticalScrollBarVisibility dependency property.
21 VerticalScrollMode
Gets or sets a value that determines how manipulation input influences
scrolling behavior on the vertical axis.
22 VerticalScrollModeProperty
Identifies the VerticalScrollMode dependency property.

Commonly Used Events of ScrollViewer Class


Sr. No. Event & Description
1 DirectManipulationCompleted
Occurs when any direct manipulation of the ScrollViewer finishes.
2 DirectManipulationStarted
Occurs when any direct manipulation of the ScrollViewer begins.
138
WPF

ViewChanged
3 Occurs when manipulations such as scrolling and zooming have caused the
view to change.
ViewChanging
4 Occurs when manipulations such as scrolling and zooming cause the view
to change.

Commonly Used Methods of ScrollViewer Class


Sr. No. Method & Description
GetHorizontalScrollBarVisibility
1 Gets the value of the HorizontalScrollBarVisibility dependency property /
ScrollViewer.HorizontalScrollBarVisibility XAML attached property from a
specified element.
GetHorizontalScrollMode
2 Gets the value of the HorizontalScrollMode dependency property /
ScrollViewer.HorizontalScrollMode XAML attached property from a specified
element.
GetIsDeferredScrollingEnabled
3 Gets the value of the IsDeferredScrollingEnabled dependency property /
ScrollViewer.IsDeferredScrollingInertiaEnabled XAML attached property
from a specified element.
GetIsHorizontalScrollChainingEnabled
4 Gets the value of the IsHorizontalScrollChainingEnabled dependency
property / ScrollViewer.IsHorizontalScrollChainingEnabled XAML attached
property from a specified element.
GetIsScrollInertiaEnabled
5 Gets the value of the IsScrollInertiaEnabled dependency property /
ScrollViewer.IsScrollInertiaEnabled XAML attached property from a
specified element.
GetIsVerticalScrollChainingEnabled
6 Gets the value of the IsVerticalScrollChainingEnabled dependency property
/ ScrollViewer.IsVerticalScrollChainingEnabled XAML attached property
from a specified element.
GetVerticalScrollBarVisibility
7 Gets the value of the VerticalScrollBarVisibility dependency property /
ScrollViewer.VerticalScrollBarVisibility XAML attached property from a
specified element.
GetVerticalScrollMode
8 Gets the value of the VerticalScrollMode dependency property /
ScrollViewer.VerticalScrollMode XAML attached property from a specified
element.
InvalidateScrollInfo
9 Called when the value of properties that describe the size and location of
the scroll area change.
ScrollToHorizontalOffset
10 Scrolls the content that is within the ScrollViewer to the specified horizontal
offset position.
ScrollToVerticalOffset
11 Scrolls the content that is within the ScrollViewer to the specified vertical
offset position.
SetHorizontalScrollBarVisibility
12 Sets the value of the HorizontalScrollBarVisibility dependency property /
ScrollViewer.HorizontalScrollBarVisibility XAML attached property on a
specified element.
139
WPF

SetHorizontalScrollMode
13 Sets the value of the HorizontalScrollMode dependency property /
ScrollViewer.HorizontalScrollMode XAML attached property on a specified
element.
SetIsDeferredScrollingEnabled
14 Sets the value of the IsDeferredScrollingEnabled dependency property /
ScrollViewer.IsDeferredScrollingEnabled XAML attached property on a
specified element.
SetIsHorizontalScrollChainingEnabled
15 Sets the value of the IsHorizontalScrollChainingEnabled dependency
property / ScrollViewer.IsHorizontalScrollChainingEnabled XAML attached
property on a specified element.
SetIsScrollInertiaEnabled
16 Sets the value of the IsScrollInertiaEnabled dependency property /
ScrollViewer.IsScrollInertiaEnabled XAML attached property on a specified
element.
SetIsVerticalScrollChainingEnabled
17 Sets the value of the IsVerticalScrollChainingEnabled dependency property
/ ScrollViewer.IsVerticalScrollChainingEnabled XAML attached property on
a specified element.
SetVerticalScrollBarVisibility
18 Sets the value of the VerticalScrollBarVisibility dependency property /
ScrollViewer.VerticalScrollBarVisibility XAML attached property on a
specified element.
SetVerticalScrollMode
19 Sets the value of the VerticalScrollMode dependency property /
ScrollViewer.VerticalScrollMode XAML attached property on a specified
element.

Example
1. Lets create a new WPF project with the name WPFScrollViewerControl.

2. The following example shows how to add a ScrollViewer in your XAML application.

3. We will add two Text Boxes and one with a ScrollViewer and initialize them with
some properties and events.

<Window x:Class="WPFScrollViewerControl.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:WPFScrollViewerControl"
mc:Ignorable="d"
Title="MainWindow" Height="420" Width="604">
<Grid>
<StackPanel>
<!-- A large TextBlock. -->

140
WPF

<TextBlock Width="300" TextWrapping="Wrap" Margin="0,0,0,30"


Text="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ac
mi ipsum. Phasellus vel malesuada mauris. Donec pharetra, enim sit amet mattis
tincidunt, felis nisi semper lectus, vel porta diam nisi in augue. Pellentesque
lacus tortor, aliquam et faucibus id, rhoncus ut justo. Sed id lectus odio,
eget pulvinar diam. Suspendisse eleifend ornare libero, in luctus purus aliquet
non. Sed interdum, sem vitae rutrum rhoncus, felis ligula ultrices sem, in
eleifend eros ante id neque." />
<!-- The same large TextBlock, wrapped in a ScrollViewer. -->
<ScrollViewer Height="200" Width="200"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Auto">
<TextBlock Width="300" TextWrapping="Wrap"
Text=" This license governs use of code marked as sample or
example available on this web site without a license agreement, as provided
under the section above titled NOTICE SPECIFIC TO SOFTWARE AVAILABLE ON THIS
WEB SITE. If you use such code (the software), you accept this license. If you
do not accept the license, do not use the software.Lorem ipsum dolor sit amet,
consectetur adipiscing elit. Sed ac mi ipsum. Phasellus vel malesuada mauris.
Donec pharetra, enim sit amet mattis tincidunt, felis nisi semper lectus, vel
porta diam nisi in augue. Pellentesque lacus tortor, aliquam et faucibus id,
rhoncus ut justo. Sed id lectus odio, eget pulvinar diam. Suspendisse eleifend
ornare libero, in luctus purus aliquet non. Sed interdum, sem vitae rutrum
rhoncus, felis ligula ultrices sem, in eleifend eros ante id neque." />
</ScrollViewer>
</StackPanel>
</Grid>
</Window>

When you compile and execute the above code, it will produce the following output:
141
WPF

We recommend that you execute the above example code and try some of the other
properties and events of ScrollViewer class.

142
27. SLIDER WPF

A slider is a control with the help of which a user can select from a range of values by
moving a Thumb control along a track. The hierarchical inheritance of Slider class is as
follows:

Commonly Used Properties of Slider


Sr. No. Property & Description

1 Header
Gets or sets the content for the control's header.
2 HeaderProperty
Identifies the Header dependency property.
3 HeaderTemplate
Gets or sets the DataTemplate used to display the content of the control's
header.
4 HeaderTemplateProperty
Identifies the HeaderTemplate dependency property.
IntermediateValue
5 Gets or sets the value of the Slider while the user is interacting with it, before
the value is snapped to either the tick or step value. The value the Slider snaps
to is specified by the SnapsTo property.
143
WPF

6 IntermediateValueProperty
Identifies the IntermediateValue dependency property.
7 IsDirectionReversed
Gets or sets a value that indicates the direction of increasing value.
8 IsDirectionReversedProperty
Identifies the IsDirectionReversed dependency property.
9 IsThumbToolTipEnabled
Gets or sets a value that determines whether the slider value is shown in a
tool tip for the Thumb component of the Slider.
10 IsThumbToolTipEnabledProperty
Identifies the IsThumbToolTipEnabled dependency property.
11 Orientation
Gets or sets the orientation of a Slider.
12 OrientationProperty
Identifies the Orientation dependency property.
13 StepFrequency
Gets or sets the value part of a value range that steps should be created for.
14 StepFrequencyProperty
Identifies the StepFrequency dependency property.
15 ThumbToolTipValueConverter
Gets or sets the converter logic that converts the range value of the Slider into
tool tip content.
16 ThumbToolTipValueConverterProperty
Identifies the ThumbToolTipValueConverter dependency property.
17 TickFrequency
Gets or sets the increment of the value range that ticks should be created for.
18 TickFrequencyProperty
Identifies the TickFrequency dependency property.
19 TickPlacement
Gets or sets a value that indicates where to draw tick marks in relation to the
track.
20 TickPlacementProperty
Identifies the TickPlacement dependency property.

Commonly Used Events in Slider Class


Sr. No. Event & Description

1 ManipulationCompleted
Occurs when a manipulation on the UIElement is complete. (Inherited from
UIElement)
2 ManipulationDelta
Occurs when the input device changes position during a manipulation.
(Inherited from UIElement)
3 ManipulationInertiaStarting
Occurs when the input device loses contact with the UIElement object during
a manipulation and inertia begins. (Inherited from UIElement)
4 ManipulationStarted
Occurs when an input device begins a manipulation on the UIElement.
(Inherited from UIElement)
5 ManipulationStarting
Occurs when the manipulation processor is first created. (Inherited from
UIElement)
6 ValueChanged
Occurs when the range value changes. (Inherited from RangeBase)
144
WPF

Commonly Used Methods in Slider Class


Sr. No. Method & Description
OnManipulationCompleted
1 Called before the ManipulationCompleted event occurs. (Inherited from
Control)
OnManipulationDelta
2
Called before the ManipulationDelta event occurs. (Inherited from Control)
OnManipulationInertiaStarting
3 Called before the ManipulationInertiaStarting event occurs. (Inherited from
Control)
OnManipulationStarted
4
Called before the ManipulationStarted event occurs. (Inherited from Control)
OnManipulationStarting
5
Called before the ManipulationStarting event occurs. (Inherited from Control)
OnMaximumChanged
6
Called when the Maximum property changes. (Inherited from RangeBase)
OnMinimumChanged
7
Called when the Minimum property changes. (Inherited from RangeBase)
OnValueChanged
8
Fires the ValueChanged routed event. (Inherited from RangeBase)
SetBinding
Attaches a binding to a FrameworkElement, using the provided binding
9
object. (Inherited from FrameworkElement)
SetValue
Sets the local value of a dependency property on a DependencyObject.
10
(Inherited from DependencyObject)

Example
1. Lets create a new WPF project with the name WPFDialog.

2. Drag one slider and two text blocks from the Toolbox.

3. Change the background color from the properties window.

4. The following example shows the usage of Slider in an XAML application. The
following XAML code creates a Slider and text blocks and initializes them with some
properties and events.

<Window x:Class="WPFSliderControl.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:WPFSliderControl"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="604">
<StackPanel>

145
WPF

<TextBlock Text="Slider" Margin="10"/>


<Slider x:Name="slider2"
Minimum="0"
Maximum="100"
TickFrequency="2"
TickPlacement="BottomRight"
ValueChanged="slider2_ValueChanged"
Margin="10">
<Slider.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="Black" Offset="0"/>
<GradientStop Color="#FFF5DCDC" Offset="1"/>
</LinearGradientBrush>
</Slider.Background>
</Slider>
<TextBlock x:Name="textBlock1"
Margin="10"
Text="Current value: 0" />

</StackPanel>
</Window>

Here is the implementation in C# for ValueChanged event.

using System;
using System.Windows;

namespace WPFSliderControl
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void slider2_ValueChanged(object sender,
RoutedPropertyChangedEventArgs<double> e)
{
146
WPF

int val = Convert.ToInt32(e.NewValue);


string msg = String.Format("Current value: {0}", val);
this.textBlock1.Text = msg;
}
}
}

When you compile and execute the above code, it will produce the following output:

We recommend that you execute the above example code and try the other properties
and events of Slider class.

147
28. TEXTBLOCK WPF

A TextBlock is a lightweight control for displaying small amounts of read-only text. The
hierarchical inheritance of TextBlock class is as follows:

Commonly Used Properties of TextBlock Class


Sr. No. Property & Description

1 ContentEnd
Gets a TextPointer object for the end of text content in the TextBlock.
2 ContentStart
Gets a TextPointer object for the start of text content in the TextBlock.
IsTextSelectionEnabled
3 Gets or sets a value that indicates whether text selection is enabled in the
TextBlock, either through user action or calling selection-related API.
4 IsTextSelectionEnabledProperty
Identifies the IsTextSelectionEnabled dependency property.
5 LineHeight
Gets or sets the height of each line of content.
6 MaxLines
Gets or sets the maximum lines of text shown in the TextBlock.
7 SelectedText
Gets a text range of selected text.
8 SelectionEnd
Gets the end position of the text selected in the TextBlock.
9 SelectionHighlightColor
Gets or sets the brush used to highlight the selected text.

148
WPF

10 SelectionStart
Gets the starting position of the text selected in the TextBlock.
11 Text
Gets or sets the text contents of a TextBlock.
12 TextAlignment
Gets or sets a value that indicates the horizontal alignment of text content.
13 TextTrimming
Gets or sets the text trimming behavior to employ when content overflows
the content area.
14 TextWrapping
Gets or sets how the TextBlock wraps text.

Commonly Used Events of TextBlock Class


Sr. No. Event & Description
ContextMenuOpening
1 Occurs when the system processes an interaction that displays a context
menu.
2 SelectionChanged
Occurs when the text selection has changed.

Commonly Used Methods in TextBlock Class


Sr. No. Method & Description
1 Focus
Focuses the TextBlock, as if it were a conventionally focusable control.
2 Select
Selects a range of text in the TextBlock.
3 SelectAll
Selects the entire contents in the TextBlock.

Example
1. Lets create a new WPF project with WPFTextBlockControl.

2. Drag a text block from the toolbox.

3. Change the background color of the text block from the properties window.

4. The following example shows the usage of TextBlock in an XAML application.

5. Here is the XAML code in which a TextBlock is created with some properties.

<Window x:Class="WPFTextBlockControl.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:WPFTextBlockControl"
mc:Ignorable="d"

149
WPF

Title="MainWindow" Height="350" Width="604">


<Grid>
<TextBlock FontFamily="Verdana"
LineStackingStrategy="MaxHeight"
LineHeight="10"
Width="500"
TextWrapping="Wrap" Background="#FFE2B1B1" Margin="48,8,48,10"
>

Use the <Run FontSize="30">LineStackingStrategy</Run> property


to determine how a line box is
created for each line. A value of <Run
FontSize="20">MaxHeight</Run> specifies that the stack
height is the smallest value that contains all the inline
elements on that line when those
elements are properly aligned. A value of <Run
FontSize="20">BlockLineHeight</Run> specifies
that the stack height is determined by the block element
LineHeight property value.
</TextBlock>

</Grid>
</Window>

When you compile and execute the above code, it will produce the following output:

We recommend that you execute the above example code and try the other properties
and events of TextBlock class.

150
29. TOGGLEBUTTON WPF

A Toggle Button is a control that can switch states, such as CheckBox and RadioButton.
The hierarchical inheritance of ToggleButton class is as follows:

Commonly Used Properties in ToggleButton Class


Sr. No. Property & Description
1 IsChecked
Gets or sets whether the ToggleButton is checked.
2 IsCheckedProperty
Identifies the IsChecked dependency property.
3 IsThreeState
Gets or sets a value that indicates whether the control supports three states.
4 IsThreeStateProperty
Identifies the IsThreeState dependency property.
151
WPF

Commonly Used Events in ToggleButton Class


Sr. No. Event & Description
1 Checked
Fires when a ToggleButton is checked.
2 Indeterminate
Fires when the state of a ToggleButton is switched to the indeterminate state.
3 Unchecked
Occurs when a ToggleButton is unchecked.

Example
1. Lets create a new WPF project with WPFToggleButtonControl.

2. Drag a text block and a toggle button from the toolbox.

3. Change the background color of the text block from the properties window.

4. The following example shows the usage of ToggleButton in an XAML application.

5. The following XAML code creates a ToggleButton and initializes it with some
properties.

<Window x:Class="WPFToggleButtonControl.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:WPFToggleButtonControl"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="604">
<StackPanel>
<ToggleButton x:Name="tb"
Content="Toggle"
Checked="HandleCheck"
Unchecked="HandleUnchecked"
Margin="20"
Width="108"
HorizontalAlignment="Center"/>
<TextBlock x:Name="text2"
Margin="20"
Width="300"
HorizontalAlignment="Center"
FontSize="24" Background="#FFFDE0E0"/>
152
WPF

</StackPanel>
</Window>

Here is the C# implementation of Checked and Unchecked events.

using System.Windows;

namespace WPFToggleButtonControl
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void HandleCheck(object sender, RoutedEventArgs e)
{
text2.Text = "Button is Checked";
}

private void HandleUnchecked(object sender, RoutedEventArgs e)


{
text2.Text = "Button is unchecked.";
}

}
}

When you compile and execute the above code, it will produce the following window. When
you click the button, it will change the color and update the text block.

153
WPF

We recommend that you execute the above example code and try the other properties
and events of ToggleButton.

154
30. TOOLTIP WPF

A tooltip is a control that creates a pop-up window that displays information for an element
in the GUI. The hierarchical inheritance of ToolTip class is as follows:

Commonly Used Properties of ToolTip Class


Sr. No. Property & Description

1 IsOpen
Gets or sets a value that indicates whether the ToolTip is visible.
2 IsOpenProperty
Identifies the IsOpen dependency property.
3 Placement
Gets or sets how a ToolTip is positioned in relation to the placement target
element.
4 PlacementProperty
Identifies the Placement dependency property.
PlacementTarget
5 Gets or sets the visual element or control that the tool tip should be
positioned in relation to when opened by the ToolTipService.
155
WPF

6 PlacementTargetProperty
Identifies the PlacementTarget dependency property.
TemplateSettings
7 Gets an object that provides calculated values that can be referenced as
TemplateBinding sources when defining templates for a ToolTip.

Commonly Used Events of ToolTip Class


Sr. No. Event & Description
1 Closed
Occurs when a ToolTip is closed and is no longer visible.
2 Opened
Occurs when a ToolTip becomes visible.

Example
1. Lets create a new WPF project with the name WPFToolTipControl.

2. Drag two text blocks, two text boxes, and one button from the Toolbox.

3. The following example shows how to use a ToolTip in a WPF application.

4. The following XAML code creates a ToolTip with some properties to display ToolTips
on Button and Text boxes.

<Window x:Class="WPFToolTipControl.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:WPFToolTipControl"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="604">
<Grid>
<TextBlock x:Name="textBlock" HorizontalAlignment="Left"
Margin="101,75,0,0" TextWrapping="Wrap"
Text="User Name" VerticalAlignment="Top"/>
<TextBlock x:Name="textBlock1" HorizontalAlignment="Left"
Margin="101,125,0,0" TextWrapping="Wrap"
Text="Password" VerticalAlignment="Top"/>
<TextBox x:Name="textBox" HorizontalAlignment="Left"
Height="24" Margin="199,75,0,0" TextWrapping="Wrap"
VerticalAlignment="Top" Width="219"
ToolTipService.ToolTip = "Enter User Name"/>

156
WPF

<PasswordBox x:Name="passwordBox" HorizontalAlignment="Left"


Margin="199,125,0,0" VerticalAlignment="Top" Width="219"
Height="24" ToolTipService.ToolTip = "Enter Password"/>
<Button x:Name="button" Content="Log in" HorizontalAlignment="Left"
Margin="199,189,0,0" VerticalAlignment="Top" Width="75"
ToolTipService.ToolTip = "Log in"/>
</Grid>
</Window>

When you compile and execute the above code, it will produce the following output. When
the mouse enters the region of the Button or the Text boxes, it will show a tool tip.

We recommend that you execute the above example code and try the other properties
and events of ToolTip class.

157
31. WINDOW WPF

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. The hierarchical inheritance
of Window class is as follows:

Commonly Used Properties of Window Class


Sr. No. Property & Description
1 AllowsTransparency
Gets or sets a value that indicates whether a window's client area supports
transparency.
2 DialogResult
Gets or sets the dialog result value, which is the value that is returned from
the ShowDialog method.
3 Icon
Gets or sets a window's icon.
4 IsActive

158
WPF

Gets a value that indicates whether the window is active.


5 Left
Gets or sets the position of the window's left edge, in relation to the desktop.
6 OwnedWindows
Gets a collection of windows for which this window is the owner.
7 Owner
Gets or sets the Window that owns this Window.
8 ResizeMode
Gets or sets the resize mode.
RestoreBounds
9 Gets the size and location of a window before being either minimized or
maximized.
ShowActivated
10 Gets or sets a value that indicates whether a window is activated when first
shown.
11 ShowInTaskbar
Gets or sets a value that indicates whether the window has a task bar button.
12 SizeToContent
Gets or sets a value that indicates whether a window will automatically size
itself to fit the size of its content.
13 TaskbarItemInfo
Gets or sets the Windows 7 taskbar thumbnail for the Window.
14 Title
Gets or sets a window's title.
15 Top
Gets or sets the position of the window's top edge, in relation to the desktop.
16 Topmost
Gets or sets a value that indicates whether a window appears in the topmost
z-order.
17 WindowStartupLocation
Gets or sets the position of the window when first shown.
18 WindowState
Gets or sets a value that indicates whether a window is restored, minimized,
or maximized.
19 WindowStyle
Gets or sets a window's border style.

Commonly Used Events of Window Class


Sr. No. Event & Description
1 Activated
Occurs when a window becomes the foreground window.
2 Closed
Occurs when the window is about to close.
Closing
3 Occurs directly after Close is called, and can be handled to cancel window
closure.
4 ContentRendered
Occurs after a window's content has been rendered.
5 Deactivated
Occurs when a window becomes a background window.
6 LocationChanged
Occurs when the window's location changes.
7 SourceInitialized

159
WPF

This event is raised to support interoperation with Win32. See HwndSource.


8 StateChanged
Occurs when the window's WindowState property changes.

Commonly Used Methods of Window Class


Sr. No. Method & Description

1 Activate
Attempts to bring the window to the foreground and activates it.
2 Close
Manually closes a Window.
DragMove
3 Allows a window to be dragged by a mouse with its left button down over
an exposed area of the window's client area.
GetWindow
4 Returns a reference to the Window object that hosts the content tree within
which the dependency object is located.
5 Hide
Makes a window invisible.
Show
6 Opens a window and returns without waiting for the newly opened window
to close.
7 ShowDialog
Opens a window and returns only when the newly opened window is closed.

Example
1. When you create a new WPF project, then by default, the Window control is present.
Lets have a look at the following example.

2. The following XAML code starts with a <Window> Tag and ends with a </Window>
tag. The code sets some properties for the window and creates some other controls
like text blocks, button, etc.

<Window x:Class="WPFToolTipControl.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:WPFToolTipControl"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="604">
<Grid>
<TextBlock x:Name="textBlock" HorizontalAlignment="Left"
Margin="101,75,0,0" TextWrapping="Wrap"
Text="User Name" VerticalAlignment="Top"/>
<TextBlock x:Name="textBlock1" HorizontalAlignment="Left"

160
WPF

Margin="101,125,0,0" TextWrapping="Wrap"
Text="Password" VerticalAlignment="Top"/>
<TextBox x:Name="textBox" HorizontalAlignment="Left"
Height="24" Margin="199,75,0,0" TextWrapping="Wrap"
VerticalAlignment="Top" Width="219"
ToolTipService.ToolTip = "Enter User Name"/>
<PasswordBox x:Name="passwordBox" HorizontalAlignment="Left"
Margin="199,125,0,0" VerticalAlignment="Top" Width="219"
Height="24" ToolTipService.ToolTip = "Enter Password"/>
<Button x:Name="button" Content="Log in" HorizontalAlignment="Left"
Margin="199,189,0,0" VerticalAlignment="Top" Width="75"
ToolTipService.ToolTip = "Log in"/>
</Grid>
</Window>

When you compile and execute the above code, it will display the following output. When
the mouse enters the region of the Button or the Textboxes, it will show a tooltip.

We recommend that you execute the above example code and try some other properties
and events of this class.

161
32. THIRD-PARTY CONTROLS WPF

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.

In this chapter, we will be using Telerik controls. So lets start by following the steps given
below.

1. Go to the link http://www.telerik.com/products/wpf/download.aspx which contains


the Telerik WPF controls and download the UI for WPF.

2. Once the download is complete, install the files on your machine.

3. After the installation, open Visual Studio and create a new WPF project with the
name WPF3rdPartyControls.

4. On Toolbox, you will see the Telerik UI controls. In addition, you will observe that
in solution explorer, all the required dll are also added after installation.

162
WPF

5. Lets expand the Telerik UI for WPF input 2015 Q2 in the toolbox. You will
see many built-in controls.

6. Now drag RadCalculator from toolbox box to the design window.

7. Take a look at your XAML window in which RadCalculator tag has been added.

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

163
WPF

<telerik:RadCalculator HorizontalAlignment="Left" Margin="174,25,0,0"


VerticalAlignment="Top"/>
</Grid>
</Window>

8. Lets compile and execute the above code. You will see a fully functional calculator
on your window with just one line of code.

9. Thats the beauty of third-party controls. But it is not free, you will need to buy a
license if you want to use third-party controls in your application.

Lets have a look at another Telerik control. Create a new WPF project with the name
WPF3rdPartyControls. Drag the RadDateTimePicker control from the toolbox. The XAML
code is as follows:

<Window x:Class="RadDateTimePickerDemo.MainWindow"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation"
Title="MainWindow" Height="350" Width="604">
<Grid>
<telerik:RadDateTimePicker VerticalAlignment="Top"
Name="dateTimePicker" />
</Grid>
</Window>

Here is the C# code in which selection changed event is implemented.


164
WPF

using System;
using System.Windows;
using System.Windows.Controls;

namespace RadDateTimePickerDemo
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
dateTimePicker.SelectionChanged += dateTimePicker_SelectionChanged;
}
void dateTimePicker_SelectionChanged( object sender,
SelectionChangedEventArgs e )
{
DateTime? dt = dateTimePicker.SelectedValue;
DateTime? date = dateTimePicker.SelectedDate;
TimeSpan? time = dateTimePicker.SelectedTime;
MessageBox.Show( "Selected date/time: " + dt.ToString() );
}
}
}

When you compile and execute the above code, it will produce the following window.

Select any time and date and it will be displayed on the message box.

165
WPF

Example
Here is an example of RichTextBox. The following XAML code creates three toggle buttons
and a rich textbox.

<Window x:Class="RichTextBoxDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation"
Title="MainWindow" Height="350" Width="604">
<Grid>
<StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton Content="B" x:Name="BoldButton"
Click="BoldButton_Click"/>
<ToggleButton Content="I" x:Name="ItalicButton"
Click="ItalicButton_Click" />
<ToggleButton Content="U"x:Name="UnderlineButton"
Click="UnderlineButton_Click" />
</StackPanel>
<telerik:RadRichTextBox Height="250" Width="400" Name="richTextBox"/>
</StackPanel>
</Grid>
</Window>

Here is the implementation in C# for button click event.

using System.Windows;
namespace RichTextBoxDemo
{
/// <summary>

166
WPF

/// Interaction logic for MainWindow.xaml


/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private void BoldButton_Click( object sender, RoutedEventArgs e )


{
richTextBox.ToggleBold();
}

private void ItalicButton_Click( object sender, RoutedEventArgs e )


{
richTextBox.ToggleItalic();
}

private void UnderlineButton_Click( object sender, RoutedEventArgs e )


{
richTextBox.ToggleUnderline();
}
}
}

167
WPF

When you compile and execute the above code, it will produce the following window. With
the help of the three buttons, you can format the text (bold, italic, underline) typed inside
the rich textbox.

We recommend that you try to use the other controls available in your toolbox and
experiment.

168
33. WPF LAYOUTS WPF

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 doesnt 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:

Stack Panel
Wrap Panel
Dock Panel
Canvas Panel
Grid Panel

Stack Panel
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. It is often used whenever any kind of list is to be created. The hierarchical
inheritance of StackPanel class is as follows:

169
WPF

Commonly Used Properties of StackPanel


Sr. No. Property & Description
1 Background
Gets or sets a Brush that fills the panel content area. (Inherited from Panel)
Children
2 Gets a UIElementCollection of child elements of this Panel. (Inherited from
Panel.)
Height
3 Gets or sets the suggested height of the element. (Inherited from
FrameworkElement.)
ItemHeight
4 Gets or sets a value that specifies the height of all items that are contained
within a WrapPanel.
ItemWidth
5 Gets or sets a value that specifies the width of all items that are contained
within a WrapPanel.
LogicalChildren
6 Gets an enumerator that can iterate the logical child elements of this Panel
element. (Inherited from Panel.)
LogicalOrientation
7 The Orientation of the panel, if the panel supports layout in only a single
dimension. (Inherited from Panel.)
Margin
8 Gets or sets the outer margin of an element. (Inherited from
FrameworkElement.)
Name
9 Gets or sets the identifying name of the element. The name provides a
reference so that code-behind, such as event handler code, can refer to a
170
WPF

markup element after it is constructed during processing by a XAML


processor. (Inherited from FrameworkElement.)
Orientation
10 Gets or sets a value that specifies the dimension in which child content is
arranged.
Parent
11 Gets the logical parent element of this element. (Inherited from
FrameworkElement.)
Resources
12 Gets or sets the locally-defined resource dictionary. (Inherited from
FrameworkElement.)
Style
13 Gets or sets the style used by this element when it is rendered. (Inherited
from FrameworkElement.)
14 Width
Gets or sets the width of the element. (Inherited from FrameworkElement.)

Example
The following example shows how to add child elements into a StackPanel. The following
XAML implementation creates buttons inside a StackPanel with some properties.

<Window x:Class="WPFStackPanel.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:WPFStackPanel"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="604">
<Grid>
<StackPanel Orientation="Horizontal">
<Button x:Name="button" Content="Button" Margin="10" Width="120"
Height="30"/>
<Button x:Name="button1" Content="Button" Margin="10" Width="120"
Height="30"/>
<Button x:Name="button2" Content="Button" Margin="10" Width="120"
Height="30"/>
<Button x:Name="button3" Content="Button" Margin="10" Width="120"
Height="30"/>
</StackPanel>

</Grid>
</Window>

171
WPF

When you compile and execute the above code, it will produce the following window. You
can see that the child elements are arranged in horizontal order. Yan can change the
arrangement by setting the orientation property to Horizontal. By default, child elements
will be arranged in vertical order.

We recommend that you execute the above example code and try the other properties of
this class as well.

Wrap Panel
In WrapPanel, child elements are positioned in sequential order, from left to right or from
top to bottom based on the orientation property. The only difference between StackPanel
and WrapPanel is that it doesnt stack all the child elements in a single line; it wraps the
remaining elements to another line if there is no space left.

WrapPanel is mostly used for tabs or menu items. The hierarchical inheritance of
WrapPanel class is as follows:

172
WPF

Commonly Used Properties of WrapPanel


Sr. No. Property & Description
1 Background
Gets or sets a Brush that fills the panel content area. (Inherited from Panel)
Children
2 Gets a UIElementCollection of child elements of this Panel. (Inherited from
Panel.)
Height
3 Gets or sets the suggested height of the element. (Inherited from
FrameworkElement.)
ItemHeight
4 Gets or sets a value that specifies the height of all items that are contained
within a WrapPanel.
ItemWidth
5 Gets or sets a value that specifies the width of all items that are contained
within a WrapPanel.
LogicalChildren
6 Gets an enumerator that can iterate the logical child elements of this Panel
element. (Inherited from Panel.)
LogicalOrientation
7 The Orientation of the panel, if the panel supports layout in only a single
dimension. (Inherited from Panel.)
Margin
8 Gets or sets the outer margin of an element. (Inherited from
FrameworkElement.)
Name
9 Gets or sets the identifying name of the element. The name provides a
reference so that code-behind, such as event handler code, can refer to a
173
WPF

markup element after it is constructed during processing by a XAML


processor. (Inherited from FrameworkElement.)
Orientation
10 Gets or sets a value that specifies the dimension in which child content is
arranged.
Parent
11 Gets the logical parent element of this element. (Inherited from
FrameworkElement.)
Resources
12 Gets or sets the locally-defined resource dictionary. (Inherited from
FrameworkElement.)
Style
13 Gets or sets the style used by this element when it is rendered. (Inherited
from FrameworkElement.)
14 Width
Gets or sets the width of the element. (Inherited from FrameworkElement.)

Example
The following example shows how to add child elements into a WrapPanel. Here is the
XAML implementation in which Text Blocks and Text Boxes are created inside a WrapPanel
in horizontal direction.

<Window x:Class="WPFWrapPanel.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:WPFWrapPanel"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="604">
<Grid>
<WrapPanel Orientation="Vertical">
<TextBlock Text="Fist Name" Width="60" Height="20" Margin="5"/>
<TextBox Width="200" Height="20" Margin="5"/>
<TextBlock Text="Last Name" Width="60" Height="20" Margin="5"/>
<TextBox Width="200" Height="20" Margin="5"/>
<TextBlock Text="Age" Width="60" Height="20" Margin="5"/>
<TextBox Width="60" Height="20" Margin="5"/>
<TextBlock Text="Title" Width="60" Height="20" Margin="5"/>
<TextBox Width="200" Height="20" Margin="5"/>
</WrapPanel>
</Grid>
</Window>

174
WPF

When you compile and execute the above code, it will produce the following window. You
can change the arrangement from top to bottom by changing the orientation property to
Vertical.

We recommend that you execute the above example code and try the other properties of
this class as well.

Dock Panel
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.

With LastChildFill property, the last child element fill the remaining space regardless of
any other dock value when set for that element. The hierarchical inheritance of DockPanel
class is as follows:

175
WPF

Commonly Used Properties of DockPanel


Sr. No. Property & Description

1 Background
Gets or sets a Brush that fills the panel content area. (Inherited from Panel)
Children
2 Gets a UIElementCollection of child elements of this Panel. (Inherited from
Panel.)
Dock
3 Gets or sets a value that indicates the position of a child element within a
parent DockPanel.
Height
4 Gets or sets the suggested height of the element. (Inherited from
FrameworkElement.)
ItemHeight
5 Gets or sets a value that specifies the height of all items that are contained
within a WrapPanel.
ItemWidth
6 Gets or sets a value that specifies the width of all items that are contained
within a WrapPanel.
LastChildFill
7 Gets or sets a value that indicates whether the last child element within a
DockPanel stretches to fill the remaining available space.
LogicalChildren
8 Gets an enumerator that can iterate the logical child elements of this Panel
element. (Inherited from Panel.)
LogicalOrientation
9 The Orientation of the panel, if the panel supports layout in only a single
dimension. (Inherited from Panel.)

176
WPF

10 Margin
Gets or sets the outer margin of an element. (Inherited from
FrameworkElement.)
Name
11 Gets or sets the identifying name of the element. The name provides a
reference so that code-behind, such as event handler code, can refer to a
markup element after it is constructed during processing by a XAML
processor. (Inherited from FrameworkElement.)
Orientation
12 Gets or sets a value that specifies the dimension in which child content is
arranged.
Parent
13 Gets the logical parent element of this element. (Inherited from
FrameworkElement.)
Resources
14 Gets or sets the locally-defined resource dictionary. (Inherited from
FrameworkElement.)
Style
15 Gets or sets the style used by this element when it is rendered. (Inherited
from FrameworkElement.)
16 Width
Gets or sets the width of the element. (Inherited from FrameworkElement.)

Commonly Used Methods of DockPanel


Sr. Method & Description
No.
1 GetDock
Gets the value of the Dock attached property for a specified UIElement.
2 SetDock
Sets the value of the Dock attached property to a specified element.

Example
The following example shows how to add child elements into a DockPanel. The following
XAML implementation creates buttons inside a DockPanel.

<Window x:Class="WPFDockPanel.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:WPFDockPanel"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="604">
<Grid>
<DockPanel LastChildFill="True">
<Button Content="Top" DockPanel.Dock="Top" Click="Click_Me"/>
<Button Content="Bottom" DockPanel.Dock="Bottom" Click="Click_Me"/>

177
WPF

<Button Content="Left" Click="Click_Me"/>


<Button Content="Right" DockPanel.Dock="Right" Click="Click_Me"/>
<Button Content="Center" Click="Click_Me"/>
</DockPanel>
</Grid>
</Window>

Here is the implementation in C# for event.

using System.Windows;
using System.Windows.Controls;

namespace WPFDockPanel
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Click_Me(object sender, RoutedEventArgs e)
{
Button btn = sender as Button;
string str = btn.Content.ToString() + " button clicked";
MessageBox.Show(str);
}

}
}

178
WPF

When you compile and execute the above code, it will display the following output:

On clicking any button, it will also display a message. For example, when you click the
button which is at the Center, it will display the following message.

We recommend that you execute the above example code and try its other properties as
well.

Canvas Panel
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.

Typically, a Canvas is used for 2D graphic elements (such as Ellipse, Rectangle etc.), but
not for UI elements because specifying absolute coordinates create trouble while resizing,
localizing or scaling your XAML application. The hierarchical inheritance of Canvas class is
as follows:

179
WPF

Commonly Used Properties of Canvas Class


Sr. No. Property & Description

1 Background
Gets or sets a Brush that fills the panel content area. (Inherited from Panel)
2 Children
Gets a UIElementCollection of child elements of this Panel. (Inherited from
Panel.)
3 Height
Gets or sets the suggested height of the element. (Inherited from
FrameworkElement.)
4 ItemHeight
Gets or sets a value that specifies the height of all items that are contained
within a WrapPanel.
5 ItemWidth
Gets or sets a value that specifies the width of all items that are contained
within a WrapPanel.
6 LogicalChildren
Gets an enumerator that can iterate the logical child elements of this Panel
element. (Inherited from Panel.)
7 LogicalOrientation
The Orientation of the panel, if the panel supports layout in only a single
dimension. (Inherited from Panel.)
8 LeftProperty
Identifies the Canvas.Left XAML attached property.
Margin
9 Gets or sets the outer margin of an element. (Inherited from
FrameworkElement.)

180
WPF

Name
10 Gets or sets the identifying name of the element. The name provides a
reference so that code-behind, such as event handler code, can refer to a
markup element after it is constructed during processing by a XAML
processor. (Inherited from FrameworkElement.)
Orientation
11 Gets or sets a value that specifies the dimension in which child content is
arranged.
Parent
12 Gets the logical parent element of this element. (Inherited from
FrameworkElement.)
Resources
13 Gets or sets the locally-defined resource dictionary. (Inherited from
FrameworkElement.)
Style
14 Gets or sets the style used by this element when it is rendered. (Inherited
from FrameworkElement.)
15 TopProperty
Identifies the Canvas.Top XAML attached property.
16 Width
Gets or sets the width of the element. (Inherited from FrameworkElement.)
17 ZIndexProperty
Identifies the Canvas.ZIndex XAML attached property.

Commonly Used Methods of Canvas


Sr. Method & Description
No.
GetLeft
1 Gets the value of the Canvas.Left XAML attached property for the target
element.
GetTop
2 Gets the value of the Canvas.Top XAML attached property for the target
element.
GetZIndex
3 Gets the value of the Canvas.ZIndex XAML attached property for the target
element.
SetLeft
4 Sets the value of the Canvas.Left XAML attached property for a target
element.
5 SetTop
Sets the value of the Canvas.Top XAML attached property for a target element.
SetZIndex
6 Sets the value of the Canvas.ZIndex XAML attached property for a target
element.

Example
The following example shows how to add child elements into a Canvas. The following XAML
implementation creates ellipses inside a Canvas with different offset properties.

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

xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WPFConvas"
mc:Ignorable="d"
Title="MainWindow" Height="400" Width="604">
<Grid>
<Canvas Width="580" Height="360" >
<Ellipse Canvas.Left="30" Canvas.Top="30"
Fill="Gray" Width="200" Height="120" />
<Ellipse Canvas.Right="30" Canvas.Top="30"
Fill="Aqua" Width="200" Height="120" />
<Ellipse Canvas.Left="30" Canvas.Bottom="30"
Fill="Gainsboro" Width="200" Height="120" />
<Ellipse Canvas.Right="30" Canvas.Bottom="30"
Fill="LightCyan" Width="200" Height="120"/>
</Canvas>
</Grid>
</Window>

When you compile and execute the above code, it will produce the following output:

We recommend that you execute the above example code and try the other properties of
this class as well.

182
WPF

Grid Panel
A Grid Panel provides a flexible area which consists of rows and columns. In a Grid, child
elements can be arranged in tabular form. Elements can be added to any specific row and
column by using Grid.Row and Grid.Column properties.

By default, a Grid panel is created with one row and one column. Multiple rows and columns
are created by RowDefinitions and ColumnDefinitions properties. The height of rows and
the width of columns can be defined in the following three ways:

Fixed value: To assign a fixed size of logical units (1/96 inch)

Auto: It will take space which are required for the controls in that specific
row/column.

Star (*): It will take the remaining space when Auto and fixed sized are filled.

The hierarchical inheritance of Canvas class is as follows.

Commonly Used Properties of Grid Class


Sr. No. Property & Description
1 Background
Gets or sets a Brush that fills the panel content area. (Inherited from Panel)
2 Children
Gets a UIElementCollection of child elements of this Panel. (Inherited from
Panel.)
3 ColumnDefinitions
Gets a list of ColumnDefinition objects defined on this instance of Grid.

183
WPF

Height
4 Gets or sets the suggested height of the element. (Inherited from
FrameworkElement.)
ItemHeight
5 Gets or sets a value that specifies the height of all items that are contained
within a WrapPanel.
ItemWidth
6 Gets or sets a value that specifies the width of all items that are contained
within a WrapPanel.
Margin
7 Gets or sets the outer margin of an element. (Inherited from
FrameworkElement.)
Name
8 Gets or sets the identifying name of the element. The name provides a
reference so that code-behind, such as event handler code, can refer to a
markup element after it is constructed during processing by a XAML
processor. (Inherited from FrameworkElement.)
Orientation
9 Gets or sets a value that specifies the dimension in which child content is
arranged.
Parent
10 Gets the logical parent element of this element. (Inherited from
FrameworkElement.)
11 Resources
Gets or sets the locally-defined resource dictionary. (Inherited from
FrameworkElement.)
12 RowDefinitions
Gets a list of RowDefinition objects defined on this instance of Grid.
Style
13 Gets or sets the style used by this element when it is rendered. (Inherited
from FrameworkElement.)
14 Width
Gets or sets the width of the element. (Inherited from FrameworkElement.)

Commonly Used Properties of Grid Class


Sr. No. Method & Description
GetColumn
1 Gets the value of the Grid.Column XAML attached property from the specified
FrameworkElement.
GetColumnSpan
2 Gets the value of the Grid.ColumnSpan XAML attached property from the
specified FrameworkElement.
GetRow
3 Gets the value of the Grid.Row XAML attached property from the specified
FrameworkElement.
SetColumn
4 Sets the value of the Grid.Column XAML attached property on the specified
FrameworkElement.
SetRow
5 Sets the value of the Grid.Row XAML attached property on the specified
FrameworkElement.
SetRowSpan
6 Sets the value of the Grid.RowSpan XAML attached property on the specified
FrameworkElement.
184
WPF

Example
The following example shows how to add child elements into a Grid to specify it in a tabular
form. In the following XAML implementation, Text Blocks are added in the first column and
Text Boxes are added in the second column of the Grid.

<Window x:Class="WPFGrid.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:WPFGrid"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="604">
<Grid x:Name="FormLayoutGrid" Background="AliceBlue">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" Text="Name" Margin="10"
HorizontalAlignment="Left" VerticalAlignment="Center" Width="100"/>

<TextBox Grid.Row="0" Grid.Column="1" Margin="10" />


<TextBlock Grid.Row="1" Grid.Column="0" Text="ID" Margin="10"
HorizontalAlignment="Left" VerticalAlignment="Center" Width="100"/>

<TextBox Grid.Row="1" Grid.Column="1" Margin="10" />


<TextBlock Grid.Row="2" Grid.Column="0" Text="Age" Margin="10"
HorizontalAlignment="Left" VerticalAlignment="Center" Width="100"/>

<TextBox Grid.Row="2" Grid.Column="1" Margin="10" />


</Grid>
</Window>

185
WPF

When you compile and execute the above code, it will produce the following window.

We recommend that you execute the above example code and try some of the other
properties of this class as well.

186
34. NESTING OF LAYOUT WPF

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. In the following example, we will be using stack panels inside a grid.

Lets have a look at the following XAML code.

<Window x:Class="WPFNestingLayouts.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:WPFNestingLayouts"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="604">
<Grid Background="AntiqueWhite">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>

<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Label Content="Employee Info"
FontSize="15" FontWeight="Bold"
Grid.Column="0" Grid.Row="0"/>

<StackPanel Grid.Column="0" Grid.Row="1" Orientation="Horizontal">


<Label Content="Name" VerticalAlignment="Center" Width="70"/>
<TextBox Name="txtName" Text="Muhammad Ali"
VerticalAlignment="Center" Width="200"></TextBox>
</StackPanel>

187
WPF

<StackPanel Grid.Column="0" Grid.Row="2" Orientation="Horizontal">


<Label Content="ID" VerticalAlignment="Center" Width="70"/>
<TextBox Name="txtCity" Text="421" VerticalAlignment="Center"
Width="50"></TextBox>
</StackPanel>

<StackPanel Grid.Column="0" Grid.Row="3" Orientation="Horizontal">


<Label Content="Age" VerticalAlignment="Center" Width="70"/>
<TextBox Name="txtState" Text="32" VerticalAlignment="Center"
Width="50"></TextBox>
</StackPanel>
<StackPanel Grid.Column="0" Grid.Row="4" Orientation="Horizontal">
<Label Content="Title" VerticalAlignment="Center" Width="70"/>
<TextBox Name="txtCountry" Text="Programmer"
VerticalAlignment="Center" Width="200"></TextBox>
</StackPanel>
</Grid>
</Window>

When you compile and execute the above code, it will produce the following window.

We recommend that you execute the above example code and try other nesting layouts.

188
35. WPF INPUT WPF

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. In this chapter, we will discuss the following types of input which can be handled
in WPF applications:

Mouse
Keyboard
ContextMenu or RoutedCommands
Multi Touch

Mouse
There are different types of mouse inputs such as MouseDown, MouseEnter, MouseLeave,
etc. In the following example, we will handle some of the mouse inputs.

1. Lets create a new WPF project with the name WPFMouseInput.

2. Drag a rectangle and three Text blocks to a stack panel and set the following
properties and events as shown in the following XAML file.

<Window x:Class="WPFMouseInput.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:WPFMouseInput"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="604">
<StackPanel>
<Rectangle x:Name="mrRec" Fill="AliceBlue"
MouseEnter="OnMouseEnter"
MouseLeave="OnMouseLeave"
MouseMove="OnMouseMove"
MouseDown="OnMouseDown"
Height="100"
Margin="20">
</Rectangle>
<TextBlock x:Name="txt1" Height="31" HorizontalAlignment="Right"
189
WPF

Width="250" Margin="0,0,294,0" />


<TextBlock x:Name="txt2" Height="31" HorizontalAlignment="Right"
Width="250" Margin="0,0,294,0" />
<TextBlock x:Name="txt3" Height="31" HorizontalAlignment="Right"
Width="250" Margin="0,0,294,0" />
</StackPanel>
</Window>

Here is the C# code in which different mouse events are handled.

using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;

namespace WPFMouseInput
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void OneMouseEnter(object sender, MouseEventArgs e)
{
Rectangle source = e.Source as Rectangle;
if (source != null)
{
source.Fill = Brushes.SlateGray;
}
txt1.Text = "Mouse Entered";
}
private void OnMouseLeave(object sender, MouseEventArgs e)
{
// Cast the source of the event to a Button.
Rectangle source = e.Source as Rectangle;

190
WPF

// If source is a Button.
if (source != null)
{
source.Fill = Brushes.AliceBlue;
}
txt1.Text = "Mouse Leave";
txt2.Text = "";
txt3.Text = "";
}
private void OnMouseMove(object sender, MouseEventArgs e)
{
Point pnt = e.GetPosition(mrRec);
txt2.Text = "Mouse Move: " + pnt.ToString();
}
private void OnMouseDown(object sender, MouseButtonEventArgs e)
{
Rectangle source = e.Source as Rectangle;
Point pnt = e.GetPosition(mrRec);
txt3.Text = "Mouse Click: " + pnt.ToString();
if (source != null)
{
source.Fill = Brushes.Beige;
}
}
}
}

When you compile and execute the above code, it will produce the following window:
191
WPF

When the mouse enters inside the rectangle, the color of the rectangle will automatically
change. In addition, you will get a message that the mouse has entered along with its
coordinates.

When you click inside the rectangle, it will change color and show the coordinates at which
mouse has been clicked.

192
WPF

When the mouse leaves the rectangle, it will show a message that mouse has left and the
rectangle will change to its default color.

Keyboard
There are many types of keyboard inputs such as KeyDown, KeyUp, TextInput, etc. In the
following example, some of the keyboard inputs are handled. The following example
defines a handler for the Click event and a handler for the KeyDown event.

1. Lets create a new WPF project with the name WPFKeyboardInput.

2. Drag a textbox and a button to a stack panel and set the following properties and
events as shown in the following XAML file.

<Window x:Class="WPFKeyboardInput.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:WPFKeyboardInput"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="604">
<Grid>
<StackPanel Orientation="Horizontal" KeyDown="OnTextInputKeyDown">
<TextBox Width="400" Height="30" Margin="10"/>
<Button Click="OnTextInputButtonClick"
193
WPF

Content="Open" Margin="10" Width="50" Height="30"/>


</StackPanel>
</Grid>
</Window>

Here is the C# code in which different keyboard and click events are handled.

using System.Windows;
using System.Windows.Input;
namespace WPFKeyboardInput
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void OnTextInputKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.O && Keyboard.Modifiers == ModifierKeys.Control)
{
handle();
e.Handled = true;
}
}
private void OnTextInputButtonClick(object sender, RoutedEventArgs e)
{
handle();
e.Handled = true;
}
public void handle()
{
MessageBox.Show("Do you want to open a file?");
}

194
WPF

}
}

When the above code is compiled and executed, it will produce the following window:

If you click the Open button or press CTRL+O keys inside textbox, it will display the same
message.

ContextMenu or RoutedCommands
RoutedCommands enable input handling at a more semantic level. These are actually
simple instructions as New, Open, Copy, Cut, and Save. These commands are very useful
and they can be accessed from a Menu or from a keyboard shortcut. It disables the controls
if the command becomes unavailable. The following example defines the commands for
Menu items.

1. Lets create a new WPF project with the name WPFCommandsInput.

195
WPF

2. Drag a menu control to a stack panel and set the following properties and
commands as shown in the following XAML file.

<Window x:Class="WPFContextMenu.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:WPFContextMenu"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<StackPanel x:Name="stack" Background="Transparent">
<StackPanel.ContextMenu>
<ContextMenu>
<MenuItem Header="New" Command="New" />
<MenuItem Header="Open" Command="Open" />
<MenuItem Header="Save" Command="Save" />
</ContextMenu>
</StackPanel.ContextMenu>
<Menu>
<MenuItem Header="File" >
<MenuItem Header="New" Command="New" />
<MenuItem Header="Open" Command="Open" />
<MenuItem Header="Save" Command="Save" />
</MenuItem>
</Menu>
</StackPanel>
</Grid>
</Window>

Here is the C# code in which different commands are handled.

using System.Windows;
using System.Windows.Input;

namespace WPFContextMenu
{

196
WPF

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
CommandBindings.Add(new CommandBinding(ApplicationCommands.New,
NewExecuted, CanNew));
CommandBindings.Add(new CommandBinding(ApplicationCommands.Open,
OpenExecuted, CanOpen));
CommandBindings.Add(new CommandBinding(ApplicationCommands.Save,
SaveExecuted, CanSave));
}
private void NewExecuted(object sender, ExecutedRoutedEventArgs e)
{
MessageBox.Show("You want to create new file.");
}

private void CanNew(object sender, CanExecuteRoutedEventArgs e)


{
e.CanExecute = true;
}
private void OpenExecuted(object sender, ExecutedRoutedEventArgs e)
{
MessageBox.Show("You want to open existing file.");
}

private void CanOpen(object sender, CanExecuteRoutedEventArgs e)


{
e.CanExecute = true;
}
private void SaveExecuted(object sender, ExecutedRoutedEventArgs e)
{
MessageBox.Show("You want to save a file.");
}

197
WPF

private void CanSave(object sender, CanExecuteRoutedEventArgs e)


{
e.CanExecute = true;
}
}
}

When the above code is compiled and executed, it will produce the following window:

Now you can access this menu items, either from the menu or from the shortcut keys
commands. From either option, it will execute the commands.

Multi Touch
Windows 7 and its higher versions have the ability to receive input from multiple touch-
sensitive devices. WPF applications can also handle touch input as other input, such as the
mouse or keyboard, by raising events when a touch occurs.

WPF exposes two types of events when a touch occurs: touch events and manipulation
events. Touch events provide raw data about each finger on a touchscreen and its
movement. Manipulation events interpret the input as certain actions. Both types of events
are discussed in this section.

The following components are required to develop an application that can respond to
touch.

Microsoft Visual Studio 2010 or later versions.


Windows 7 or higher version.
A device, such as a touchscreen, that supports Windows Touch.

The following terms are commonly used when touch input is discussed:

198
WPF

Touch: Type of user input which can be recognized in Windows 7 or later. Touch
input is initiated from a touch-sensitive screen.

Multi Touch: Type of input which occurs from more than one point simultaneously.
In WPF, when touch is discussed, it usually means multi-touch.

Manipulation: Occurs when touch is inferred as a physical action that is applied


to an object. In WPF, manipulation events interpret input as a translation,
expansion, or rotation manipulation.

Touch Device: Represents a device that produces touch input, such as a single
finger on a touchscreen.

Example
To understand all these concepts, lets create a new WPF project with the name
WPFTouchInput.

1. Drag a Rectangle from a toolbox to the design window and fill the rectangle with
an image or any color. If you want to use an image, then dont forget to include
the image in your solution, otherwise the program will not execute.

2. The following XAML code initializes a rectangle with different properties and events.

<Window x:Class="WPFMultiTouchInput.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:WPFMultiTouchInput"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="604">
<Window.Resources>
<MatrixTransform x:Key="InitialMatrixTransform">
<MatrixTransform.Matrix>
<Matrix OffsetX="200" OffsetY="200"/>
</MatrixTransform.Matrix>
</MatrixTransform>
</Window.Resources>
<Canvas>
<Rectangle Name="manRect"
Width="321" Height="241"
RenderTransform="{StaticResource InitialMatrixTransform}"
IsManipulationEnabled="true" Canvas.Left="-70" Canvas.Top="-170">

199
WPF

<Rectangle.Fill>
<ImageBrush ImageSource="Images/DSC_0076.JPG"/>
</Rectangle.Fill>
</Rectangle>
</Canvas>
</Window>

Here is the implementation for different manipulation events:

using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;

namespace WPFMultiTouchInput
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
void Window_ManipulationStarting(object sender,
ManipulationStartingEventArgs e)
{
e.ManipulationContainer = this;
e.Handled = true;
}
void Window_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)

{
Rectangle rectToMove = e.OriginalSource as Rectangle;
Matrix rectsMatrix =
((MatrixTransform)rectToMove.RenderTransform).Matrix;
rectsMatrix.RotateAt(e.DeltaManipulation.Rotation,
e.ManipulationOrigin.X, e.ManipulationOrigin.Y);
rectsMatrix.ScaleAt(e.DeltaManipulation.Scale.X,
e.DeltaManipulation.Scale.X, e.ManipulationOrigin.X, e.ManipulationOrigin.Y);
rectsMatrix.Translate(e.DeltaManipulation.Translation.X,
e.DeltaManipulation.Translation.Y);

200
WPF

rectToMove.RenderTransform = new MatrixTransform(rectsMatrix);

Rect containingRect = new


Rect(((FrameworkElement)e.ManipulationContainer).RenderSize);

Rect shapeBounds = rectToMove.RenderTransform.TransformBounds(new


Rect(rectToMove.RenderSize));

if (e.IsInertial && !containingRect.Contains(shapeBounds))


{
e.Complete();
}
e.Handled = true;
}
void Window_InertiaStarting(object sender,
ManipulationInertiaStartingEventArgs e)
{
e.TranslationBehavior.DesiredDeceleration = 10.0 * 96.0 / (1000.0 *
1000.0);
e.ExpansionBehavior.DesiredDeceleration = 0.1 * 96 / (1000.0 *
1000.0);
e.RotationBehavior.DesiredDeceleration = 720 / (1000.0 * 1000.0);
e.Handled = true;
}

}
}

When you compile and execute the above code, it will produce the following widnow.

201
WPF

Now you can rotate, zoom in, zoom out this image with your finger on touch screen.

202
36. WPF COMMAND LINE WPF

Command line argument is a mechanism where a user can pass a set of parameters or
values to a WPF application when it is executed. These arguments are very important to
control an application from outside, for example, if you want to open a Word document
from the command prompt, then you can use this command C:\> start winword
word1.docx and it will open word1.docx document.

Command line arguments are handled in Startup function. Following is a simple example
which shows how to pass command line arguments to a WPF application. Lets create a
new WPF application with the name WPFCommandLine.

1. Drag one textbox from the toolbox to the design window.

2. In this example, we will pass a txt file path to our application as command line
parameter.

3. The program will read the txt file and then write all the text on the text box.

4. The following XAML code creates a textbox and initializes it with some properties.

<Window x:Class="WPFCommandLine.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:WPFCommandLine"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBox x:Name="textBox" HorizontalAlignment="Left"
Height="180" Margin="100"
TextWrapping="Wrap"
VerticalAlignment="Top" Width="300"/>
</Grid>
</Window>

5. Now subscribe the Startup event in App.xaml file as shown below.

<Application x:Class="WPFCommandLine.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

203
WPF

xmlns:local="clr-namespace:WPFCommandLine"
StartupUri="MainWindow.xaml"
Startup="app_Startup">
<Application.Resources>

</Application.Resources>
</Application>

6. Given below is the implementation of the app_Startup event in App.xaml.cs which will
get the command line arguments.

using System.Windows;

namespace WPFCommandLine
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
public static string[] Args;
void app_Startup(object sender, StartupEventArgs e)
{
// If no command line arguments were provided, don't process them
if (e.Args.Length == 0) return;

if (e.Args.Length > 0)
{
Args = e.Args;
}
}
}
}

7. Now, in the MainWindow class, the program will open the txt file and write all the text
on textbox.

8. If there is some error found, then the program will display an error message on
textbox.

204
WPF

using System;
using System.IO;
using System.Windows;

namespace WPFCommandLine
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
String[] args = App.Args;
try
{ // Open the text file using a stream reader.
using (StreamReader sr = new StreamReader(args[0]))
{
// Read the stream to a string, and write
// the string to the text box
String line = sr.ReadToEnd();
textBox.AppendText(line.ToString());
textBox.AppendText("\n");
}
}
catch (Exception e)
{
textBox.AppendText("The file could not be read:");
textBox.AppendText("\n");
textBox.AppendText(e.Message);
}
}
}
}

9. When the above code is compiled and executed, it will produce a blank window with a
textbox because this program needs a command line argument. So Visual Studio
provides an easy way to execute your application with command line parameters.

205
WPF

10. Right click on your WPF project in the solution explorer and select properties, it will
display the following window.

11. Select Debug option and write the file path in the Command line argument.

12. Create a txt file with Test.txt and write some text in that file and save it on any
location. In this case, the txt file is saved on D:\ hard drive.

13. Save the changes in your project and compile and execute your application now. You
will see the text in TextBox which the program reads from the Text.txt file.

206
WPF

Now lets try and change the file name on your machine from Test.txt to Test1.txt and
execute your program again, then you will see that error message in the text box.

We recommend that you execute the above code and follow all the steps to execute your
application successfully.

207
37. WPF DATA BINDING WPF

Data binding is a mechanism in WPF applications that provides a simple and easy way for
Windows Runtime apps to display and interact with data. In this mechanism, the
management of data is entirely separated from the way data.

Data binding allows the flow of data between UI elements and data object on user
interface. When a binding is established and the data or your business model changes,
then it reflects the updates automatically to the UI elements and vice versa. It is also
possible to bind, not to a standard data source, but to another element on the page.

Data binding is of two types: one-way data binding and two-way data binding.

One-Way Data Binding


In one-way binding, data is bound from its source (that is the object that holds the data)
to its target (that is the object that displays the data)

1. Lets take a simple example to understand one-way data binding in detail. First of
all, create a new WPF project with the name WPFDataBinding.

2. The following XAML code creates two labels, two textboxes, and one button and
initializes them with some properties.

<Window x:Class="WPFDataBinding.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:WPFDataBinding"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="604">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="200" />
</Grid.ColumnDefinitions>
208
WPF

<Label Name="nameLabel" Margin="2">_Name:</Label>


<TextBox Name="nameText" Grid.Column="1" Margin="2"
Text="{Binding Name, Mode=OneWay}"/>

<Label Name="ageLabel" Margin="2" Grid.Row="1">_Age:</Label>


<TextBox Name="ageText" Grid.Column="1" Grid.Row="1" Margin="2"
Text="{Binding Age, Mode=OneWay}"/>

<StackPanel Grid.Row="2" Grid.ColumnSpan="2">


<Button Content="_Show..." Click="Button_Click" />
</StackPanel>
</Grid>
</Window>

3. The text properties of both the textboxes bind to Name and Age which are class
variables of Person class which is shown below.

4. In Person class, we have just two variables Name and Age, and its object is
initialized in MainWindow class.

5. In XAML code, we are binding to a property Name and Age, but we have not
selected what object that property belongs to.

6. The easier way is to assign an object to DataContext whose properties we are


binding in the following C# code in MainWindowconstructor.

using System.Windows;

namespace WPFDataBinding
{
public partial class MainWindow : Window
{
Person person = new Person { Name = "Salman", Age = 26 };
public MainWindow()
{
InitializeComponent();
this.DataContext = person;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
209
WPF

string message = person.Name + " is " + person.Age;


MessageBox.Show(message);
}
}
public class Person
{
private string nameValue;
public string Name
{
get { return nameValue; }
set { nameValue = value; }
}
private double ageValue;
public double Age
{
get { return ageValue; }
set
{
if (value != ageValue)
{
ageValue = value;
}
}
}
}
}

7. Let's run this application and you can see immediately in our MainWindow that we
have successfully bound to the Name and Age of that Person object.

210
WPF

When you press the Show button, it will display the name and age on the message box.

Lets change the Name and Age in the dialog box.

If you now click the Show button, it will again display the same message.

This because data binding mode is set to one-way in the XAML code. To show the updated
data, you will need to understand two-way data binding.
211
WPF

Two-Way Data Binding


In two-way binding, the user can modify the data through the user interface and have that
data updated in the source. If the source changes while the user is looking at the view,
you want the view to be updated.

Lets take the same example but here, we will change the binding mode from One Way to
Two Way in the XAML code.

<Window x:Class="WPFDataBinding.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:WPFDataBinding"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="604">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="200" />
</Grid.ColumnDefinitions>
<Label Name="nameLabel" Margin="2">_Name:</Label>
<TextBox Name="nameText" Grid.Column="1" Margin="2"
Text="{Binding Name, Mode=TwoWay}"/>

<Label Name="ageLabel" Margin="2" Grid.Row="1">_Age:</Label>


<TextBox Name="ageText" Grid.Column="1" Grid.Row="1" Margin="2"
Text="{Binding Age, Mode=TwoWay}"/>

<StackPanel Grid.Row="2" Grid.ColumnSpan="2">


<Button Content="_Show..." Click="Button_Click" />
</StackPanel>
</Grid>

212
WPF

</Window>

Let's run this application again.

It will produce the same output:

Lets now change the Name and Age values:

If you click the Show button now, it will display the updated message.

213
WPF

We recommend that you execute the above code with both the cases for a better
understanding of the concept.

214
38. WPF RESOURCES WPF

Resources are normally definitions connected with some object that you just anticipate to
use more often than once. It is the ability to store data locally for controls or for the current
window or globally for the entire applications.

Defining an object as a resource allows us to access it from another place. What it means
is that the object can be reused. Resources are defined in resource dictionaries and any
object can be defined as a resource effectively making it a shareable asset. A unique key
is specified to an XAML resource and with that key, it can be referenced by using a
StaticResource markup extension.

Resources can be of two types:

StaticResource
DynamicResource

A StaticResource is a onetime lookup, whereas a DynamicResource works more like a data


binding. It remembers that a property is associated with a particular resource key. If the
object associated with that key changes, dynamic resource will update the target property.

Example
Here's a simple application for the SolidColorBrush resource.

1. Lets create a new WPF project with the name WPFResouces.


2. Drag two Rectangles and set their properties as shown in the following XAML code.

<Window x:Class="WPFResources.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:WPFResources"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<SolidColorBrush x:Key="brushResource" Color="Blue" />
</Window.Resources>
<StackPanel>
<Rectangle Height="50" Margin="20" Fill="{StaticResource
brushResource}" />

215
WPF

<Rectangle Height="50" Margin="20" Fill="{DynamicResource


brushResource}"/>
<Button x:Name="changeResourceButton" Content="_Change Resource"
Click="changeResourceButton_Click" />
</StackPanel>
</Window>

3. In the above XAML code, you can see that one rectangle has StaticResource and
the other one has DynamicResource and the color of brushResource is Bisque.

4. When you compile and execute the code, it will produce the following MainWindow.

When you click the "Change Resource" button, you will see that the rectangle with
DynamicResource will change its color to Red.

216
WPF

Resource Scope
Resources are defined in resource dictionaries, but there are numerous places where a
resource dictionary can be defined. In the above example, a resource dictionary is defined
on Window/page level. In what dictionary a resource is defined immediately limits the
scope of that resource. So the scope, i.e. where you can use the resource, depends on
where you've defined it.

Define the resource in the resource dictionary of a grid and it's accessible by that
grid and by its child elements only.

Define it on a window/page and it's accessible by all elements on that window/page.

The app root can be found in App.xaml resources dictionary. It's the root of our
application, so the resources defined here are scoped to the entire application.

As far as the scope of the resource is concerned, the most often are application level, page
level, and a specific element level like a Grid, StackPanel, etc.

The above application has resources in its Window/page level.

Resource Dictionaries
Resource dictionaries in XAML apps imply that the resource dictionaries are kept in
separate files. It is followed in almost all XAML apps. Defining resources in separate files
can have the following advantages:

Separation between defining resources in the resource dictionary and UI related


code.

Defining all the resources in a separate file such as App.xaml would make them
available across the app.

217
WPF

So, how do we define our resources in a resource dictionary in a separate file? Well, it is
very easy, just add a new resource dictionary through Visual Studio by following steps
given below:

In your solution, add a new folder and name it ResourceDictionaries.

Right-click on this folder and select Resource Dictionary from Add submenu item
and name it DictionaryWithBrush.xaml

Example
Lets now take the same example, but here, we will define the resource dictionary in app
level. The XAML code for MainWindow.xaml is as follows:

<Window x:Class="WPFResources.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:WPFResources"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<Rectangle Height="50" Margin="20" Fill="{StaticResource
brushResource}" />
<Rectangle Height="50" Margin="20" Fill="{DynamicResource
brushResource}"/>
<Button x:Name="changeResourceButton" Content="_Change Resource"
Click="changeResourceButton_Click" />
</StackPanel>
</Window>

Here is the implementation in DictionaryWithBrush.xaml:

<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<SolidColorBrush x:Key="brushResource" Color="Blue" />
</ResourceDictionary>

Here is the implementation in app.xaml:

<Application x:Class="WPFResources.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
218
WPF

StartupUri="MainWindow.xaml">
<Application.Resources>
<ResourceDictionary Source="
XAMLResources\ResourceDictionaries\DictionaryWithBrush.xaml"/>
</Application.Resources>
</Application>

When the above code is compiled and executed, it will produce the following output:

When you click the Change Resource button, the rectangle will change its color to Red.

We recommend that you execute the above code and try some more resources (for
example, background color).

219
39. WPF TEMPLATES WPF

A template describes the overall look and visual appearance of a control. For each control,
there is a default template associated with it which gives the control its appearance. In
WPF applications, you can easily create your own templates when you want to customize
the visual behavior and visual appearance of a control.

Connectivity between the logic and the template can be achieved by data binding. The
main difference between styles and templates are listed below:

Styles can only change the appearance of your control with default properties of
that control.

With templates, you can access more parts of a control than in styles. You can also
specify both existing and new behavior of a control.

There are two types of templates which are most commonly used:

Control Template
Data Template

Control Template
The Control Template defines the visual appearance of a control. All of the UI elements
have some kind of appearance as well as behavior, e.g., Button has an appearance and
behavior. Click event or mouse hover event are the behaviors which are fired in response
to a click and hover and there is also a default appearance of button which can be changed
by the Control template.

Example
Lets take a simple example. We will create two buttons (one is with template and the
other one is the default button) and initialize them with some properties.

<Window x:Class="TemplateDemo.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>
<ControlTemplate x:Key="ButtonTemplate" TargetType="Button">
<Grid>
<Ellipse x:Name="ButtonEllipse" Height="100" Width="150" >
<Ellipse.Fill>
<LinearGradientBrush StartPoint="0,0.2"
EndPoint="0.2,1.4">
220
WPF

<GradientStop Offset="0" Color="Red"/>


<GradientStop Offset="1" Color="Orange"/>
</LinearGradientBrush>
</Ellipse.Fill>
</Ellipse>
<ContentPresenter Content="{TemplateBinding Content}"
HorizontalAlignment="Center"
VerticalAlignment="Center" />
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="ButtonEllipse" Property="Fill" >
<Setter.Value>
<LinearGradientBrush StartPoint="0,0.2"
EndPoint="0.2,1.4">
<GradientStop Offset="0" Color="YellowGreen"/>

<GradientStop Offset="1" Color="Gold"/>


</LinearGradientBrush>
</Setter.Value>
</Setter>
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter Property="RenderTransform">
<Setter.Value>
<ScaleTransform ScaleX="0.8" ScaleY="0.8"
CenterX="0" CenterY="0" />
</Setter.Value>
</Setter>
<Setter Property="RenderTransformOrigin"
Value="0.5,0.5" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Window.Resources>
<StackPanel>
<Button Content="Round Button!"

221
WPF

Template="{StaticResource ButtonTemplate}"
Width="150" Margin="50" />
<Button Content="Default Button!" Height="40"
Width="150" Margin="5" />
</StackPanel>
</Window>

When you compile and execute the above code, it will display the following MainWindow.

When you hove the mouse over the button with custom template, it will change its color
as shown below.

Data Template
A Data Template defines and specifies the appearance and structure of a collection of data.
It provides the flexibility to format and define the presentation of the data on any UI
element. It is mostly used on data related Item controls such as ComboBox, ListBox, etc.

222
WPF

Example
1. Lets take a simple example to understand the concept of data template. Create a
new WPF project with the name WPFDataTemplates.

2. In the following XAML code, we will create a Data Template as resource to hold
labels and textboxes. There is a button and a list box as well which to display the
data.

<Window x:Class="WPFDataTemplates.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:WPFDataTemplates"
xmlns:loc="clr-namespace:WPFDataTemplates"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<DataTemplate DataType="{x:Type loc:Person}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="200" />
</Grid.ColumnDefinitions>
<Label Name="nameLabel" Margin="10"/>
<TextBox Name="nameText" Grid.Column="1" Margin="10"
Text="{Binding Name}"/>

<Label Name="ageLabel" Margin="10" Grid.Row="1"/>


<TextBox Name="ageText" Grid.Column="1" Grid.Row="1" Margin="10"

Text="{Binding Age}"/>
</Grid>
</DataTemplate>
</Window.Resources>

223
WPF

<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>

<ListBox ItemsSource="{Binding}" />

<StackPanel Grid.Row="1" >


<Button Content="_Show..." Click="Button_Click" Width="80"
HorizontalAlignment="Left" Margin="10"/>
</StackPanel>
</Grid>
</Window>

Here is implementation in C# in which a list of Person objects are assigned to


DataContext, implementation of Person class and button click event.

using System.Collections.Generic;
using System.Windows;

namespace WPFDataTemplates
{
public partial class MainWindow : Window
{
Person src = new Person { Name = "Ali", Age = 27 };
List<Person> people = new List<Person>();
public MainWindow()
{
InitializeComponent();
people.Add(src);
people.Add(new Person { Name = "Mike", Age = 62 });
people.Add(new Person { Name = "Brian", Age = 12 });

this.DataContext = people;
}
private void Button_Click(object sender, RoutedEventArgs e)

224
WPF

{
string message = src.Name + " is " + src.Age;
MessageBox.Show(message);
}
}
public class Person
{
private string nameValue;
public string Name
{
get { return nameValue; }
set { nameValue = value; }
}

private double ageValue;


public double Age
{
get { return ageValue; }
set
{
if (value != ageValue)
{
ageValue = value;
}
}
}
}
}

When you compile and execute the above code, it will produce the following window. It
contains one list and inside the list box, each list box item contains the Person class object
data which are displayed on Labels and Text boxes.

225
WPF

226
40. WPF STYLES WPF

The .NET framework provides several strategies to personalize and customize the
appearance of an application. 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.

Styles are used to give a uniform look or appearance to a set of controls. Implicit styles
are used to apply an appearance to all the controls of a given type and simplify the
application. Imagine three buttons, all of them have to look the same, same width and
height, same font size, same foreground color, etc. We can set all those properties on the
button elements themselves and that's still quite okay for all of the buttons. Take a look
at the following diagram.

But in a real-life applications, you'll typically have a lot more of these that need to look
exactly the same. And not only buttons of course, you'll typically want your text blocks,
text boxes, and combo boxes etc. to look the same across your application. Surely, there
must be a better way to achieve this and it is known as styling. You can think of a style
as a convenient way to apply a set of property values to more than one element. Take a
look at the following diagram.

227
WPF

Example
Lets take a simple example to understand this concept. Start by creating a new WPF
project.

1. Drag three buttons from the toolbox to the design window.

2. The following XAML code creates three buttons and initializes them with some
properties.

<Window x:Class="WPFStyle.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: WPFStyle"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="604">
<StackPanel>
<Button Content="Button1"
Height="30"
Width="80"
Foreground="Blue"
FontSize="12"
Margin="10"/>
<Button Content="Button2"

228
WPF

Height="30"
Width="80"
Foreground="Blue"
FontSize="12"
Margin="10"/>
<Button Content="Button3"
Height="30"
Width="80"
Foreground="Blue"
FontSize="12"
Margin="10"/>
</StackPanel>
</Window>

When you look at the above code, you will see that for all the buttons height, width,
foreground color, font size and margin properties are same. Now when the above code is
compiled and executed the following window will be displayed.

Now lets have a look at the same example, but this time, we will be using style.

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

229
WPF

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>

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.

In the above example, 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.

When you compile and execute the above code, it will display the following window (the
same output).

230
WPF

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.

In what level a style is defined instantaneously limits the scope of that style. So the scope,
i.e. where you can use the style, depends on where you've defined it. Styles can be defined
on the following levels:

Control level
Layout level
Window level
Application level

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.

<Window x:Class="XAMLControlLevelStyle.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Control Level Styles" Height="350" Width="604">
<StackPanel Margin="10" VerticalAlignment="Top">
<TextBlock Text="TextBlock">
<TextBlock.Style>
<Style>
<Setter Property="TextBlock.FontSize" Value="24" />
231
WPF

<Setter Property="TextBlock.Width" Value="400" />


<Setter Property="TextBlock.Height" Value="40" />
<Setter Property="TextBlock.Background" Value="Gray" />
<Setter Property="TextBlock.Margin" Value="50" />
</Style>
</TextBlock.Style>
</TextBlock>
<Button Content="Button">
<Button.Style>
<Style>
<Setter Property="TextBlock.Width" Value="100" />
<Setter Property="TextBlock.Height" Value="40" />
<Setter Property="TextBlock.Margin" Value="50" />
</Style>
</Button.Style>
</Button>
</StackPanel>
</Window>

When the above code is compiled and executed, it will produce the following window:

Layout Level
Defining a style on any layout level will make it accessible by that layout and its child
elements only. Given below is an example of layout level where all the three buttons have
common style.

232
WPF

<Window x:Class="XAMLLayoutLevelStyle.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">
<StackPanel Margin="10">
<StackPanel.Resources>
<Style TargetType="Button">
<Setter Property="Foreground" Value="Blue" />
<Setter Property="FontStyle" Value="Italic" />
<Setter Property="Width" Value="100" />
<Setter Property="Height" Value="40" />
<Setter Property="Margin" Value="10" />
</Style>
</StackPanel.Resources>
<Button>Button 1</Button>
<Button>Button 2</Button>
<Button Foreground="Blue">Button 3</Button>
</StackPanel>
</Window>

When you compile and execute the above code, it will produce the following window.

233
WPF

Window Level
Defining a style on a window level can make it accessible by all the elements on that
window. Given below is an example of window level where all the three text blocks have
a common style.

<Window x:Class="Styles.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 TargetType="TextBlock">
<Setter Property="FontSize" Value="24" />
<Setter Property="Margin" Value="5" />
<Setter Property="FontWeight" Value="Bold" />
</Style>
<Style TargetType="TextBox">
<Setter Property="HorizontalAlignment" Value="Left" />
<Setter Property="FontSize" Value="24" />
<Setter Property="Margin" Value="5" />
<Setter Property="Width" Value="200" />
<Setter Property="Height" Value="40" />
</Style>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="2*" />
</Grid.ColumnDefinitions>
<TextBlock Text="First Name: "/>
<TextBox Name="FirstName" Grid.Column="1" />
<TextBlock Text="Last Name: " Grid.Row="1" />

234
WPF

<TextBox Name="LastName" Grid.Column="1" Grid.Row="1" />


<TextBlock Text="Email: " Grid.Row="2" />
<TextBox Name="Email" Grid.Column="1" Grid.Row="2"/>
</Grid>
</Window>

When you compile and execute the above code, it will produce the following window.

Application Level
Defining a style on app level can make it accessible throughout the entire application. Lets
take the same example, but here, we will put the styles in app.xaml file to make it
accessible throughout application. Here is the XAML code in app.xaml.

<Application x:Class="Styles.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml">
<Application.Resources>
<Style TargetType="TextBlock">
<Setter Property="FontSize" Value="24" />
<Setter Property="Margin" Value="5" />
<Setter Property="FontWeight" Value="Bold" />
</Style>
<Style TargetType="TextBox">
235
WPF

<Setter Property="HorizontalAlignment" Value="Left" />


<Setter Property="FontSize" Value="24" />
<Setter Property="Margin" Value="5" />
<Setter Property="Width" Value="200" />
<Setter Property="Height" Value="40" />
</Style>
</Application.Resources>
</Application>

Here is the XAML code to create text blocks and text boxes.

<Window x:Class="Styles.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>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="2*" />
</Grid.ColumnDefinitions>
<TextBlock Text="First Name: "/>
<TextBox Name="FirstName" Grid.Column="1" />
<TextBlock Text="Last Name: " Grid.Row="1" />
<TextBox Name="LastName" Grid.Column="1" Grid.Row="1" />
<TextBlock Text="Email: " Grid.Row="2" />
<TextBox Name="Email" Grid.Column="1" Grid.Row="2"/>
</Grid>
</Window>

When you compile and execute the above code, it will produce the following window.

236
WPF

We recommend that you execute the above code and try to insert more features into it.

237
41. WPF TRIGGERS WPF

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. There are three types of triggers:

Property Triggers
Data Triggers
Event Triggers

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.

The following example code shows how to change the foreground color of a button when
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"

238
WPF

Style="{StaticResource TriggerStyle}"
Content="Trigger"/>
</Grid>
</Window>

When you compile and execute the above code, it will produce the following window:

When the mouse hovers over the button, its foreground color will change to green.

Data Triggers
A data trigger performs some actions when the bound data satisfies some conditions. Lets
have a look at the following XAML code in which a checkbox and a text block are created

239
WPF

with some properties. When the checkbox is checked, it will change its 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>

When the above code is compiled and executed, it will produce the following output:

240
WPF

When you tick the checkbox, the text block will change its foreground color to red.

Event Triggers
An event trigger performs some actions when a specific event is fired. It is usually used to
accomplish some animation on control such DoubleAnumatio, ColorAnimation, etc. In the
following example, we will create a simple button. When the click event is fired, it will
expand the button width and height.

<Window x:Class="WPFEventTrigger.MainWindow"
241
WPF

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>
242
WPF

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

When you compile and execute the above code, it will produce the following window:

Upon clicking the button, you will observe that it will start expanding in both dimensions.

We recommend that you compile and execute the above examples and apply the triggers
to other properties as well.

243
42. WPF DEBUGGING WPF

It is a systematic mechanism of identifying and fixing the bugs or defects in a piece of


code which are not behaving the same as you are expecting. Debugging a complex
application where the subsystems are tightly coupled are not that easy, because fixing
bugs in one subsystem can create bugs in another subsystem.

Debugging in C#
In WPF applications, programmers deal with two languages such as C# and XAML. If you
are familiar with debugging in any procedural language such as C# or C/C++ and you also
know the usage of break points, then you can debug the C# part of your application easily.

Lets take a simple example to demonstrate how to debug a C# code. Create a new WPF
project with the name WPFDebuggingDemo. Drag four labels, three textboxes, and one
button from the toolbox. Take a look at the following XAML code.

<Window x:Class="WPFDebuggingDemo.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="400" Width="604">
<Grid>
<TextBox Height="23" Margin="0,44,169,0" Name="textBox1"
VerticalAlignment="Top"
HorizontalAlignment="Right" Width="120" />
<TextBox Height="23" Margin="0,99,169,0" Name="textBox2"
VerticalAlignment="Top"
HorizontalAlignment="Right" Width="120" />
<TextBox HorizontalAlignment="Right" Margin="0,153,169,0"
Name="textBox3" Width="120" Height="23"
VerticalAlignment="Top" />
<Label Height="28" Margin="117,42,0,0" Name="label1"
VerticalAlignment="Top" HorizontalAlignment="Left"
Width="120">Item 1</Label>
<Label Height="28" HorizontalAlignment="Left"
Margin="117,99,0,0" Name="label2"
VerticalAlignment="Top" Width="120">Item 2</Label>
<Label HorizontalAlignment="Left" Margin="117,153,0,181"
Name="label3" Width="120">Item 3</Label>

244
WPF

<Button Height="23" HorizontalAlignment="Right"


Margin="0,0,214,127" Name="button1"
VerticalAlignment="Bottom" Width="75"
Click="button1_Click">Total</Button>
<Label Height="28" HorizontalAlignment="Right"
Margin="0,0,169,66" Name="label4"
VerticalAlignment="Bottom" Width="120"/>
</Grid>
</Window>

Given below is the C# code in which a button click event is implemented.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WPFDebuggingDemo
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}

245
WPF

private void button1_Click(object sender, RoutedEventArgs e)


{
if (textBox1.Text.Length > 0 && textBox2.Text.Length > 0 &&
textBox2.Text.Length > 0)
{
double total = Convert.ToDouble(textBox1.Text) +
Convert.ToDouble(textBox2.Text) + Convert.ToDouble(textBox3.Text);
label4.Content = total.ToString();
}
else
{
MessageBox.Show("Enter the value in all field.");
}
}
}
}

When you compile and execute the above code, it will produce the following window. Now
enter values in the textboxes and press the Total button. You will get the total value after
summation of all the values entered in the textboxes.

If you try to enter values other than real values, then the above application will crash. To
find and resolve the issue (why it is crashing), you can insert break points in the button
click event.

Lets write "abc" in item 1 as shown below.

246
WPF

Upon clicking the Total button, you will see that the program stops at the break point

Now move the cursor towards the textbox1.Text and you will see that the program is trying
to add abc value with the other values which is why the program is crashing.

247
WPF

Debugging in XAML
If you are expecting the same kind of debugging in XAML, then you will be surprised to
know that it is not possible yet to debug the XAML code like debugging any other
procedural language code. When you hear the term debugging in XAML code, it means try
and find an error.

In data binding, your data doesn't show up on screen and you don't know why

Or an issue is related to complex layouts.

Or an alignment issue or issues in margin color, overlays, etc. with some extensive
templates like ListBox and combo box.

Debugging an XAML program is something you typically do to check if your bindings work;
and if it is not working, then to check what's wrong. Unfortunately setting breakpoints in
XAML bindings isn't possible except in Silverlight, but we can use the Output window to
check for data binding errors. Let's take a look at the following XAML code to find the error
in data binding.

<Window x:Class="DataBindingOneWay.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>
<StackPanel Name="Display">
<StackPanel Orientation="Horizontal" Margin="50, 50, 0, 0">
<TextBlock Text="Name: " Margin="10" Width="100"/>
<TextBlock Margin="10" Width="100"
Text="{Binding FirstName}"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="50,0,50,0">
<TextBlock Text="Title: " Margin="10" Width="100"/>
<TextBlock Margin="10" Width="100"
Text="{Binding Title}" />
</StackPanel>
</StackPanel>
</Grid>
</Window>

Text properties of two text blocks are set to Name and Title statically, while other two
text blocks Text properties are bind to FirstName and Title but class variables are Name
and Title in Employee class which is shown below.

248
WPF

We have intentionally written an incorrect variable name so as to understand where can


we find this type of a mistake when the desired output is not shown.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataBindingOneWay
{
public class Employee
{
public string Name { get; set; }
public string Title { get; set; }

public static Employee GetEmployee()


{
var emp = new Employee()
{
Name = "Ali Ahmed",
Title = "Developer"
};
return emp;
}

}
}

Here is the implementation of MainWindow class in C# code.

using System;
using System.Windows;
using System.Windows.Controls;

namespace DataBindingOneWay
{
/// <summary>
/// Interaction logic for MainWindow.xaml
249
WPF

/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = Employee.GetEmployee();
}
}
}

Let's run this application and you can see immediately in our MainWindow that we have
successfully bound to the Title of that Employee object but the name is not bound.

To check what happened with the name, lets look into the output window where a lot of
log is generated.

The easy to find an error is just to search for the error and you will find the following error
which says BindingExpression path error: 'FirstName' property not found on 'object'
''Employe

System.Windows.Data Error: 40 : BindingExpression path error: 'FirstName'


property not found on 'object' ''Employee' (HashCode=11611730)'.
BindingExpression:Path=FirstName; DataItem='Employee' (HashCode=11611730);
target element is 'TextBlock' (Name=''); target property is 'Text' (type
'String')

250
WPF

Which clearly indicate that FirstName is not a member of Employee class, so it helps to fix
this type of issues in your application.

When you change the FirstName to Name again, then you will see the desired output.

UI Debugging Tools for XAML


UI debugging tools were introduced for XAML with Visual Studio 2015 to inspect the XAML
code at runtime. With the help of these tools, XAML code is presented in the form of a
visual tree of your running WPF application and also the different UI element properties in
the tree. To enable these tools, follow the steps given below.

1. Go to the Tools menu and select Options from the Tools menu.

2. It will open the following dialog box.

3. Go to the General Options under Debugging item on the left side.

4. Tick the highlighted option, i.e., Enable UI Debugging Tools for XAML and click
the OK button.

Now run any XAML application or use the following XAML code.

<Window x:Class="XAMLTestBinding.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">
<StackPanel>
<ComboBox Name="comboBox" Margin="50" Width="100">
<ComboBoxItem Content="Green"/>
<ComboBoxItem Content="Yellow" IsSelected="True"/>
251
WPF

<ComboBoxItem Content="Orange" />


</ComboBox>
<TextBox Name="textBox" Margin="50" Width="100" Height="23"
VerticalAlignment="Top"
Text ="{Binding ElementName=comboBox,
Path=SelectedItem.Content,
Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged}"
Background="{Binding ElementName=comboBox, Path=SelectedItem.Content}">

</TextBox>
</StackPanel>
</Window>

When you execute the application, it will show the Live Visual Tree where all the elements
are shown in a tree.

252
WPF

This Live Visual Tree shows the complete layout structure to understand where the UI
elements are located. But this option is only available in Visual Studio 2015. If you are
using an older option of Visual Studio, then you cant use this tool, however there is
another tool which can be integrated with Visual Studio such as XAML Spy for Visual Studio.
You can download it from http://xamlspy.com/download.

253
43. WPF CUSTOM CONTROLS WPF

WPF applications allows to create custom controls which makes it very easy to create
feature-rich and customizable controls. Custom controls are used when all the built-in
controls provided by Microsoft are not fulfilling your criteria or you dont want to pay for
third-party controls.

In this chapter, you will learn how to create custom controls. Before we start taking a look
at Custom Controls, let's take a quick look at a User Control first.

User Control
User Controls provide a way to collect and combine different built-in controls together and
package them into re-usable XAML. User controls are used in following scenarios:

If the control consists of existing controls, i.e., you can create a single control of
multiple, already existing controls.

If the control doesn't need support for theming. User Controls do not support
complex customization, control templates, and difficult to style.

If a developer prefers to write controls using the code-behind model where a view
and then a direct code behind for event handlers.

You won't be sharing your control across applications.

Example
Lets go to an example of User control and follow the steps given below.

1. Create a new WPF project and then right-click on your solution and select Add >
New Item...

254
WPF

2. The following window will open. Now select User Control (WPF) and name it
MyUserControl.

255
WPF

3. Click the Add button and you will see that two new files (MyUserControl.xaml and
MyUserControl.cs) will be added in your solution.

Here is the XAML code in which a button and a text box is created with some properties in
MyUserControl.xaml file.

<UserControl x:Class="WPFUserControl.MyUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<TextBox Height="23"
HorizontalAlignment="Left"
Margin="80,49,0,0" Name="txtBox"
VerticalAlignment="Top"
Width="200" />
<Button Content="Click Me"
Height="23"
HorizontalAlignment="Left"
Margin="96,88,0,0"
Name="button"
VerticalAlignment="Top"
Width="75"
Click="button_Click" />
</Grid>
</UserControl>

Given below is the C# code for button click event in MyUserControl.cs file which updates
the text box.

using System;
using System.Windows;
using System.Windows.Controls;

namespace WPFUserControl
{
/// <summary>

256
WPF

/// Interaction logic for MyUserControl.xaml


/// </summary>
public partial class MyUserControl : UserControl
{
public MyUserControl()
{
InitializeComponent();
}

private void button_Click(object sender, RoutedEventArgs e)


{
txtBox.Text = "You have just clicked the button";
}
}
}

Here is the implementation in MainWindow.xaml to add the user control.

<Window x:Class="XAMLUserControl.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:control="clr-namespace:WPFUserControl"
Title="MainWindow" Height="350" Width="525">
<Grid>
<control:MyUserControl/>
</Grid>
</Window>

257
WPF

When you compile and execute the above code, it will produce the following window.

Upon clicking the "Click Me" button, you will notice that the text inside the textbox is
updated.

Custom Controls
A custom control is a class which offers its own style and template which are normally
defined in generic.xaml. Custom controls are used in the following scenarios:

If the control doesn't exist and you have to create it from scratch.

If you want to extend or add functionality to a preexisting control by adding an


extra property or an extra functionality to fit your specific scenario.

If your controls need to support theming and styling.

If you want to share your control across applications.


258
WPF

Example
Lets take an example to understand how custom controls work. Create a new WPF project
and then right-click on your solution and select Add > New Item...

It will open the following window. Now select Custom Control (WPF) and name it
MyCustomControl.

259
WPF

Click the Add button and you will see that two new files (Themes/Generic.xaml and
MyCustomControl.cs) will be added in your solution.

Here is the XAML code in which style is set for the custom control in Generic.xaml file.

<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WPFCustomControls">

<Style TargetType="{x:Type local:MyCustomControl}" BasedOn="{StaticResource


{x:Type Button}}">
<Setter Property="Background" Value="LightSalmon" />
<Setter Property="Foreground" Value="Blue"/>
</Style>
</ResourceDictionary>

Here is the C# code for MyCustomControl class which is inherited from the button class
and in constructor it overrides the metadata.

using System;
using System.Windows;
using System.Windows.Controls;

namespace WPFCustomControls
{
public class MyCustomControl : Button
{
static MyCustomControl()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(MyCustomControl),
new FrameworkPropertyMetadata(typeof(MyCustomControl)));
}
}
}

Here is the custom control click event implementation in C# which updates the text of the
text block.

using System;
using System.Windows;
using System.Windows.Controls;
260
WPF

namespace WPFCustomControls
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private void customControl_Click(object sender, RoutedEventArgs e)


{
txtBlock.Text = "You have just click your custom control";
}
}
}

Here is implementation in MainWindow.xaml to add the custom control and a TextBlock.

<Window x:Class="WPFCustomControls.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:control="clr-namespace:WPFCustomControls"
Title="MainWindow" Height="350" Width="604">
<StackPanel>
<control:MyCustomControl x:Name="customControl"
Content="Click Me"
Width="70"
Margin="10"
Click="customControl_Click"/>
<TextBlock Name="txtBlock"
Width="250"
Height="30"/>
</StackPanel>

261
WPF

</Window>

When you compile and execute the above code, it will produce the following window with
a custom control which is a customized button.

Upon clicking the customized button, you will see that the text inside text block is updated.

262
44. WPF EXCEPTION HANDLING WPF

An exception is any error condition or an unexpected behavior that is encountered during


the execution of a program. Exceptions can be raised due to many reasons, some of them
are as follows:

Fault in your code or in code that you call (such as a shared library),

Unavailable operating system resources,

Unexpected conditions that a common language runtime encounters (such as code


that cannot be verified)

Syntax
Exceptions have the ability to transfer the flow of a program from one part to another. In
.NET framework, exception handling has the following four keywords:

try: In this block, the program identifies a certain condition which raises some
exception.

catch: The catch keyword indicates the catching of an exception. A try block is
followed by one or more catch blocks to catch an exception with an exception
handler at the place in a program where you want to handle the problem.

finally: The finally block is used to execute a given set of statements, whether an
exception is thrown or not thrown. For example, if you open a file, it must be closed
whether an exception is raised or not.

throw: A program throws an exception when a problem shows up. This is done
using a throw keyword.

The syntax to use these four keywords goes as follows:

try
{
///This will still trigger the exception
}
catch (ExceptionClassName e)
{
// error handling code
}
catch (ExceptionClassName e)
{
// error handling code
263
WPF

}
catch (ExceptionClassName e)
{
// error handling code
}
finally
{
// statements to be executed
}

Multiple catch statements are used in those cases where a try block can raise more than
one exception depending on the situation of a program flow.

Hierarchy
Almost all the exception classes in the .NET framework are directly or indirectly derived
from the Exception class. The most important exception classes derived from the Exception
class are:

ApplicationException class It supports exceptions which are generated by


programs. When developer want to define exception then class should be derived
from this class.

SystemException class It is the base class for all predefined runtime system
exceptions. The following hierarchy shows the standard exceptions provided by the
runtime.

Object

Exception

System
Exception

IndexOutOfRa NullReference AccessViolatio InvalidOperati ArgumentExce ExternalExcept


ngeException Exception nException onException ption ion

ArgumentOut
ArgumentNull
OfRangeExcep SEHException
Exception
tion

264
WPF

The following table lists the standard exceptions provided by the runtime and the
conditions under which you should create a derived class.

Exception type Base type Description

Exception Object Base class for all


exceptions.
SystemException Exception Base class for all runtime-
generated errors.
IndexOutOfRangeException SystemException Thrown by the runtime
only when an array is
indexed improperly.
NullReferenceException SystemException Thrown by the runtime
only when a null object is
referenced.
AccessViolationException SystemException Thrown by the runtime
only when invalid memory
is accessed.
InvalidOperationException SystemException Thrown by methods when
in an invalid state.
ArgumentException SystemException Base class for all argument
exceptions.
ArgumentNullException ArgumentException Thrown by methods that do
not allow an argument to
be null.
ArgumentOutOfRangeException ArgumentException Thrown by methods that
verify that arguments are
in a given range.
ExternalException SystemException Base class for exceptions
that occur or are targeted
at environments outside
the runtime.
SEHException ExternalException Exception encapsulating
Win32 structured exception
handling information.

Example
Lets take a simple example to understand the concept better. Start by creating a new
WPF project with the name WPFExceptionHandling.

Drag one textbox from the toolbox to the design window. The following XAML code creates
a textbox and initializes it with some properties.

<Window x:Class="WPFExceptionHandling.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:WPFExceptionHandling"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="604">
265
WPF

<Grid>
<TextBox x:Name="textBox" HorizontalAlignment="Left"
Height="241" Margin="70,39,0,0"
TextWrapping="Wrap" VerticalAlignment="Top"
Width="453"/>
</Grid>
</Window>

Here is the file reading with exception handling in C#.

using System;
using System.IO;
using System.Windows;

namespace WPFExceptionHandling
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
ReadFile(0);
}
void ReadFile(int index)
{
string path = @"D:\Test.txt";
StreamReader file = new StreamReader(path);
char[] buffer = new char[80];
try
{
file.ReadBlock(buffer, index, buffer.Length);
string str = new string(buffer);
str.Trim();
textBox.Text = str;
}
catch (Exception e)
{

266
WPF

MessageBox.Show("Error reading from "+ path + "\nMessage = "+


e.Message);
}
finally
{
if (file != null)
{
file.Close();
}
}
}
}
}

When you compile and execute the above code, it will produce the following window in
which a text is displayed inside the textbox.

When there is an exception raised or you throw it manually (as in the following code), then
it will show a message box with error.

using System;
using System.IO;
using System.Windows;

namespace WPFExceptionHandling
267
WPF

{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
ReadFile(0);
}
void ReadFile(int index)
{
string path = @"D:\Test.txt";
StreamReader file = new StreamReader(path);
char[] buffer = new char[80];
try
{
file.ReadBlock(buffer, index, buffer.Length);
string str = new string(buffer);
throw new Exception();
str.Trim();
textBox.Text = str;
}
catch (Exception e)
{
MessageBox.Show("Error reading from "+ path + "\nMessage = "+
e.Message);
}
finally
{
if (file != null)
{
file.Close();
}
}
}
}
}

268
WPF

When an exception is raised while executing the above code, it will display the following
message.

We recommend that you execute the above code and experiment with its features.

269
45. WPF LOCALIZATION WPF

Localization is the translation of application resources into localized versions for the specific
cultures that the application supports.

When you develop your application and your application is available in only one language,
then you are limiting the number of your customers and the size of your business. If you
want to increase your customer base which will also increase your business, then your
product must be available and reachable to a global audience. Cost-effective localization
of your product is one of the best and most economical ways to reach out to more
customers.

In WPF, localizable applications are very easy to create with resx file which is the simplest
solution for localization. Lets take a simple example to understand how it works:

Create a new WPF project with the name WPFLocalization.

In your solution explorer, you will see the Resources.resx file under Properties
folder.

270
WPF

Change the access modifier from internal to public so that it can be accessible in
XAML file.

Now add the following strings name and values which we will be using in our
application.

271
WPF

Make two copies of Resources.resx file with the names Resources.en.resx and
Resources.ru-RU.resx. These are naming conventions specific to language and
country/region name, and it can be found on National Language Support (NLS) API
Reference (https://msdn.microsoft.com/en-us/goglobal/bb896001.aspx) page.

Change the values in Resources.ru-RU.resx to Russian words, as shown below.

272
WPF

Lets go to the design window and drag three textboxes, three labels, and three
buttons.

In the XAML file, first add the namespace declaration to use localize resources
xmlns:p="clr-namespace:WPFLocalization.Properties"

Set the properties of all the controls as shown below. In this example, we will not
use hardcoded strings for the content of labels, buttons, and Title of the window in
XAML file. We will be using the strings which are defined in *.resx files. For
example, for the Title of window, we use the Title string which is defined in *.resx
file like this Title="{x:Static p:Resources.Title}"

Here is the XAML file in which controls are created and initialized with different
properties.

<Window x:Class="WPFLocalization.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WPFLocalization"
xmlns:p="clr-namespace:WPFLocalization.Properties"

273
WPF

Title="{x:Static p:Resources.Title}" Height="350" Width="604">


<Grid>
<TextBox x:Name="textBox" HorizontalAlignment="Left" Height="23"
Margin="128,45,0,0" TextWrapping="Wrap"
VerticalAlignment="Top" Width="304"/>
<Label x:Name="label" Content="{x:Static p:Resources.Name}"
HorizontalAlignment="Left" Margin="52,45,0,0"
VerticalAlignment="Top" Width="86"/>
<TextBox x:Name="textBox1" HorizontalAlignment="Left" Height="23"
Margin="128,102,0,0" TextWrapping="Wrap"
VerticalAlignment="Top" Width="304"/>
<Label x:Name="label1" Content="{x:Static p:Resources.Address}"
HorizontalAlignment="Left" Margin="52,102,0,0"
VerticalAlignment="Top" Width="86"/>
<TextBox x:Name="textBox2" HorizontalAlignment="Left" Height="23"
Margin="128,157,0,0" TextWrapping="Wrap"
VerticalAlignment="Top" Width="80"/>
<Label x:Name="label2" Content="{x:Static p:Resources.Age}"
HorizontalAlignment="Left" Margin="52,157,0,0"
VerticalAlignment="Top" Width="86"/>
<Button x:Name="button" Content="{x:Static p:Resources.OK_Button}"
HorizontalAlignment="Left" Margin="163,241,0,0"
VerticalAlignment="Top" Width="75"/>
<Button x:Name="button1" Content="{x:Static p:Resources.Cancel_Button}"
HorizontalAlignment="Left" Margin="282,241,0,0"
VerticalAlignment="Top" Width="75"/>
<Button x:Name="button2" Content="{x:Static p:Resources.Help_Button}"
HorizontalAlignment="Left" Margin="392,241,0,0"
VerticalAlignment="Top" Width="75"/>
</Grid>
</Window>

When the above code is compiled and executed you will see the following window
which contains different controls.

274
WPF

By default, the program uses the default Resources.resx. If you want to show the
text in Russian language which are defined in Resources.ru-RU.resx file, then you
will need to set the culture explicitly when the program starts in App.xaml file as
shown below.

using System.Windows;

namespace WPFLocalization
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
App()
{
System.Threading.Thread.CurrentThread.CurrentUICulture = new
System.Globalization.CultureInfo("ru-RU");
//System.Threading.Thread.CurrentThread.CurrentUICulture = new
System.Globalization.CultureInfo("en");
}
}
}

275
WPF

When you run your application, you will see all the text in Russian language.

We recommend that you execute the above code and create resx files for other cultures
as well.

276
46. WPF INTERACTION WPF

In WPF, an interaction shows how a view interacts with controls located in that view. The
most commonly known interactions are of two types:

Behaviors
Drag and Drop

Behaviors
Behaviors were introduced with Expression Blend 3 which can encapsulate some of the
functionality into a reusable component. To add additional behaviors, you can attach these
components to the controls. Behaviors provide more flexibility to design complex user
interactions easily.

Lets take a look at a simple example in which a ControlStoryBoardAction behavior is


attached to controls.

Create a new WPF project with the name WPFBehavior.

The following XAML code creates an ellipse and two buttons to control the
movement of the ellipse.

<Window
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:WPFBehaviors"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
x:Class="WPFBehaviors.MainWindow"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="604">
<Window.Resources>
<Storyboard x:Key="Storyboard1" RepeatBehavior="Forever"
AutoReverse="True">
<DoubleAnimationUsingKeyFrames
Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children
)[3].(TranslateTransform.X)" Storyboard.TargetName="ellipse">
<EasingDoubleKeyFrame KeyTime="0:0:1" Value="301.524"/>
<EasingDoubleKeyFrame KeyTime="0:0:2" Value="2.909"/>
</DoubleAnimationUsingKeyFrames>
277
WPF

<DoubleAnimationUsingKeyFrames
Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children
)[3].(TranslateTransform.Y)" Storyboard.TargetName="ellipse">
<EasingDoubleKeyFrame KeyTime="0:0:1" Value="-0.485"/>
<EasingDoubleKeyFrame KeyTime="0:0:2" Value="0"/>
</DoubleAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames
Storyboard.TargetProperty="(ContentControl.Content)"
Storyboard.TargetName="button">
<DiscreteObjectKeyFrame KeyTime="0" Value="Play"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames
Storyboard.TargetProperty="(ContentControl.Content)"
Storyboard.TargetName="button1">
<DiscreteObjectKeyFrame KeyTime="0" Value="Stop"/>
<DiscreteObjectKeyFrame KeyTime="0:0:2" Value="Stop"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</Window.Resources>
<Window.Triggers>
<EventTrigger RoutedEvent="FrameworkElement.Loaded">
<BeginStoryboard Storyboard="{StaticResource Storyboard1}"/>
</EventTrigger>
</Window.Triggers>
<Grid>
<Ellipse x:Name="ellipse" Fill="#FFAAAAC5" HorizontalAlignment="Left"
Height="50.901" Margin="49.324,70.922,0,0" Stroke="Black"
VerticalAlignment="Top" Width="73.684" RenderTransformOrigin="0.5,0.5">
<Ellipse.RenderTransform>
<TransformGroup>
<ScaleTransform/>
<SkewTransform/>
<RotateTransform/>
<TranslateTransform/>
</TransformGroup>
</Ellipse.RenderTransform>
</Ellipse>

278
WPF

<Button x:Name="button" Content="Play" HorizontalAlignment="Left"


Height="24.238" Margin="63.867,0,0,92.953" VerticalAlignment="Bottom"
Width="74.654">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<ei:ControlStoryboardAction Storyboard="{StaticResource
Storyboard1}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
<Button x:Name="button1" Content="Stop" HorizontalAlignment="Left"
Height="24.239" Margin="160.82,0,0,93.922" VerticalAlignment="Bottom"
Width="75.138">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<ei:ControlStoryboardAction ControlStoryboardOption="Stop"
Storyboard="{StaticResource Storyboard1}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>

</Grid>
</Window>

When you compile and execute the above code, it will produce the following window which
contains an ellipse and two buttons.

279
WPF

When you press the play button, it will start moving from left to right and then will return
to its original position. The stop button will stop the movement the ellipse.

Drag and Drop


Drag and Drop on user interface can significantly advance the efficiency and productivity
of the application. There are very few applications in which drag and drop features are
used because people think it is difficult to implement. To an extent, it is difficult to handle
a drag and drop feature, but in WPF, you can handle it quite easily.

280
WPF

Lets take a simple example to understand how it works. We will create an application
wherein you can drag and drop color from one rectangle to another.

1. Create a new WPF project with the name WPFDragAndDrop.

2. Drag five rectangles to the design window and set the properties as shown in the
following XAML file.

<Window x:Class="WPFDragAndDrop.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:WPFDragAndDrop"
mc:Ignorable="d"
Title="MainWindow" Height="402.551" Width="604">
<Grid>
<Rectangle Name="Target" Fill="AliceBlue" HorizontalAlignment="Left"
Height="345" Margin="10,10,0,0" Stroke="Black"
VerticalAlignment="Top" Width="387" AllowDrop="True"
Drop="Target_Drop"/>
<Rectangle Fill="Beige" HorizontalAlignment="Left" Height="65"
Margin="402,10,0,0" Stroke="Black" VerticalAlignment="Top"
Width="184" MouseLeftButtonDown="Rect_MLButtonDown"/>
<Rectangle Fill="LightBlue" HorizontalAlignment="Left" Height="65"
Margin="402,80,0,0" Stroke="Black" VerticalAlignment="Top"
Width="184" MouseLeftButtonDown="Rect_MLButtonDown"/>
<Rectangle Fill="LightCoral" HorizontalAlignment="Left" Height="65"
Margin="402,150,0,0" Stroke="Black" VerticalAlignment="Top"
Width="184" MouseLeftButtonDown="Rect_MLButtonDown"/>
<Rectangle Fill="LightGray" HorizontalAlignment="Left" Height="65"
Margin="402,220,0,0" Stroke="Black" VerticalAlignment="Top"
Width="184" MouseLeftButtonDown="Rect_MLButtonDown"/>
<Rectangle Fill="OliveDrab" HorizontalAlignment="Left" Height="65"
Margin="402,290,0,-7" Stroke="Black" VerticalAlignment="Top"
Width="184" MouseLeftButtonDown="Rect_MLButtonDown"/>

</Grid>
</Window>

281
WPF

3. The first rectangle is the target rectangle, so the user can drag the color from the
other rectangle to the target rectangle.

4. Given below are the events implementation in C# for drag and drop.

using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;

namespace WPFDragAndDrop
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private void Rect_MLButtonDown(object sender, MouseButtonEventArgs e)


{
Rectangle rc = sender as Rectangle;
DataObject data = new DataObject(rc.Fill);
DragDrop.DoDragDrop(rc, data,DragDropEffects.Move);
}

private void Target_Drop(object sender, DragEventArgs e)


{
SolidColorBrush scb =
(SolidColorBrush)e.Data.GetData(typeof(SolidColorBrush));
Target.Fill = scb;
}
}
}

When you run your application, it will produce the following window.

282
WPF

If you drag a color from the rectangle on the right side and drop it on the large rectangle
to the left, you will see its effect immediately.

Lets drag the 4th one from the right side.

You can see that the color of the target rectangle has changed. We recommend that you
execute the above code and experiment with its features.

283
47. WPF 2D GRAPHICS WPF

WPF provides a wide range of 2D graphics which can be enhanced as per your application
requirements. WPF supports both Drawing and Shape objects that are used for drawing
graphical content.

Shapes and Drawing


Shape class is derived from the FrameworkElement class, Shape objects can be
used inside panels and most controls.

WPF provides some basic shape objects which are derived from the Shape class
such as Ellipse, Line, Path, Polygon, Polyline, and Rectangle.

Drawing objects, on the other hand, do not derive from the FrameworkElement
class and provide a lighter-weight implementation.

Drawing objects are simpler as compared to Shape objects. They have better
performance characteristics as well.

Example
Lets take a simple example to understand how to use different shapes object.

Create a new WPF project with the name WPF2DGraphics.

The following code creates different types of shapes.

<Window x:Class="WPF2DGraphics.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:WPF2DGraphics"

xmlns:PresentationOptions="http://schemas.microsoft.com/winfx/2006/xaml/present
ation/options"
mc:Ignorable="PresentationOptions"
Title="MainWindow" Height="400" Width="604">
<StackPanel>
<Ellipse Width="100" Height="60" Name="sample" Margin="10">
<Ellipse.Fill>
<RadialGradientBrush>

284
WPF

<GradientStop Offset="0" Color="AliceBlue"/>


<GradientStop Offset="1" Color="Gray"/>
<GradientStop Offset="2" Color="Red"/>
</RadialGradientBrush>
</Ellipse.Fill>
</Ellipse>
<Path Stroke="Red" StrokeThickness="5" Data="M 10,70 L 200,70"
Height="42.085" Stretch="Fill" Margin="140.598,0,146.581,0" />
<Path Stroke="BlueViolet" StrokeThickness="5" Data="M 20,100 A 100,56
42 1 0 200,10" Height="81.316" Stretch="Fill" Margin="236.325,0,211.396,0" />
<Path Fill="LightCoral" Margin="201.424,0,236.325,0" Stretch="Fill"
Height="124.929">
<Path.Data>
<PathGeometry>
<PathFigure StartPoint="50,0" IsClosed="True">
<LineSegment Point="100,50"/>
<LineSegment Point="50,100"/>
<LineSegment Point="0,50"/>
</PathFigure>
</PathGeometry>
</Path.Data>
</Path>
</StackPanel>
</Window>

When you compile and execute the above code, it will produce an ellipse, a straight line,
an arc, and a polygon.

285
WPF

Example
Lets have a look at another example that shows how to paint an area with a drawing.

1. Create a new WPF project with the name WPF2DGraphics1.

2. The following XAML code shows how to paint different with image drawing.

<Window x:Class="WPF2DGraphics1.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:PresentationOptions="http://schemas.microsoft.com/winfx/2006/xaml/present
ation/options"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="PresentationOptions"
xmlns:local="clr-namespace:WPF2DGraphics1"
Title="MainWindow" Height="350" Width="604">
<Grid>
<Border BorderBrush="Gray" BorderThickness="1"
HorizontalAlignment="Left" VerticalAlignment="Top"
Margin="20">
<Image Stretch="None">

286
WPF

<Image.Source>
<DrawingImage PresentationOptions:Freeze="True">
<DrawingImage.Drawing>
<DrawingGroup>
<ImageDrawing Rect="300,100,300,180"
ImageSource="Images\DSC_0104.JPG"/>
<ImageDrawing Rect="0,100,250,100"
ImageSource="Images\DSC_0104.JPG"/>
<ImageDrawing Rect="150,0,25,25"
ImageSource="Images\DSC_0104.JPG"/>
<ImageDrawing Rect="0,0,75,75"
ImageSource="Images\DSC_0104.JPG"/>
</DrawingGroup>
</DrawingImage.Drawing>
</DrawingImage>
</Image.Source>
</Image>
</Border>
</Grid>
</Window>

When you run your application, it will produce the following output:

We recommend that you execute the above code and try more 2D shapes and drawings.

287
48. WPF 3D GRAPHICS WPF

Windows Presentation Foundation (WPF) provides a functionality to draw, transform, and


animate 3D graphics as per your application requirement. It doesnt support full fledge 3D
game development, but to some level, you can create 3D graphics.

By combining 2D and 3D graphics, you can also create rich controls, provide complex
illustrations of data, or enhance the user experience of an application's interface. The
Viewport3D element hosts a 3D model into our WPF application.

Example
Lets take a simple example to understand how to use 3D graphics.

Create a new WPF project with the name WPF3DGraphics.

The following XAML code shows how to create a 2D object using in 3D geometry.

<Window x:Class="WPF3DGraphics.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:WPF3DGraphics"
mc:Ignorable="d"
Title="MainWindow" Height="500" Width="604">
<Grid>
<Viewport3D>
<Viewport3D.Camera>
<PerspectiveCamera Position="2,0,10" LookDirection="0.2,0.4,-1"
FieldOfView="65" UpDirection="0,1,0" />
</Viewport3D.Camera>
<ModelVisual3D>
<ModelVisual3D.Content>
<Model3DGroup>
<AmbientLight Color="Bisque" />
<GeometryModel3D>
<GeometryModel3D.Geometry>
<MeshGeometry3D
Positions="0,0,0 0,8,0 10,0,0 8,8,0"

288
WPF

Normals="0,0,1 0,0,1 0,0,1 0,0,1"


TriangleIndices="0,2,1 1,2,3"/>
</GeometryModel3D.Geometry>
<GeometryModel3D.Material>
<DiffuseMaterial Brush="Bisque" />
</GeometryModel3D.Material>
</GeometryModel3D>
</Model3DGroup>
</ModelVisual3D.Content>
</ModelVisual3D>
</Viewport3D>
</Grid>
</Window>

When you compile and execute the above code, it will produce a 2D object in 3D.

Example
Lets have a look at another example which shows a 3D object.

1. Create a new WPF project with the name WPF3DGraphics1.

2. The following XAML code creates a 3D object and a slider. With the help of the
slider, you can rotate this 3D object.

289
WPF

<Window x:Class="WPF3DGraphics1.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:WPF3DGraphics1"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Viewport3D Name="viewport3D1">
<Viewport3D.Camera>
<PerspectiveCamera x:Name="camMain" Position="6 5 4"
LookDirection="-6 -5 -4">
</PerspectiveCamera>
</Viewport3D.Camera>
<ModelVisual3D>
<ModelVisual3D.Content>
<DirectionalLight x:Name="dirLightMain" Direction="-1,-1,-1">

</DirectionalLight>
</ModelVisual3D.Content>
</ModelVisual3D>
<ModelVisual3D x:Name="MyModel">
<ModelVisual3D.Content>
<GeometryModel3D>
<GeometryModel3D.Geometry>
<MeshGeometry3D x:Name="meshMain"
Positions="0 0 0 1 0 0 0 1 0 1 1 0 0 0 1 1
0 1 0 1 1 0 1 1"
TriangleIndices="2 3 1 3 1 0 7 1 3 7 5 1 6
5 7 6 4 5 6 2 0 2 0 4 2 7 3 2 6 7 0 1 5 0 5 4">
</MeshGeometry3D>
</GeometryModel3D.Geometry>
<GeometryModel3D.Material>
<DiffuseMaterial x:Name="matDiffuseMain">
<DiffuseMaterial.Brush>
<SolidColorBrush Color="Bisque"/>
</DiffuseMaterial.Brush>

290
WPF

</DiffuseMaterial>
</GeometryModel3D.Material>
</GeometryModel3D>
</ModelVisual3D.Content>
<ModelVisual3D.Transform>
<RotateTransform3D>
<RotateTransform3D.Rotation>
<AxisAngleRotation3D x:Name="rotate" Axis="1 2 1"/>
</RotateTransform3D.Rotation>
</RotateTransform3D>
</ModelVisual3D.Transform>
</ModelVisual3D>
</Viewport3D>
<Slider Height="23" HorizontalAlignment="Left"
Margin="145,271,0,0" Name="slider1"
VerticalAlignment="Top" Width="269"
Maximum="360"
Value="{Binding ElementName=rotate, Path=Angle}" />
</Grid>
</Window>

When you run your application, it will produce a 3D object and a slider on your window.

291
WPF

When you slide the slider, the object on your window will also rotate.

We recommend that you execute the above code and try more 3D geometry.

292
49. WPF MULTIMEDIA WPF

WPF applications support video and audio using MediaElement. It allows you to integrate
audio and video into an application. The MediaElement class works in a similar way as
Image class. You just point it at the media and it renders it. The main difference is that it
will be a moving image, but if you point it to the file that contains just audio and no video
such as an MP3, it will play that without showing anything on the screen.

WPF supports all types of video/audio format depending on the machine configuration. If
a media file plays a Media Player, it will also work in WPF on the same machine.

Example
Lets take an example to understand how to integrate multimedia in your application.

Create a new WPF project with the name WPFMultimedia.

The following XAML code creates a media element and three buttons, and initializes
them with some properties.

<Window x:Class="WPFMultimedia.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:WPFMultimedia"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="604">
<Grid>
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
<MediaElement Name="myMedia" Source="D:\MicrosoftMVA.mp4"
LoadedBehavior="Manual" Width="591" Height="274" />
<StackPanel Orientation="Horizontal" Margin="0,10,0,0">
<Button Content="Play" Margin="0,0,10,0"
Padding="5" Click="mediaPlay" />
<Button Content="Pause" Margin="0,0,10,0"
Padding="5" Click="mediaPause" />
<Button x:Name="muteButt" Content="Mute"
Padding="5" Click="mediaMute" />
</StackPanel>
</StackPanel>
293
WPF

</Grid>
</Window>

Here is the Click events implementation in C# for different buttons.

using System;
using System.Windows;

namespace WPFMultimedia
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
myMedia.Volume = 100;
myMedia.Play();
}
void mediaPlay(Object sender, EventArgs e)
{
myMedia.Play();
}

void mediaPause(Object sender, EventArgs e)


{
myMedia.Pause();
}
void mediaMute(Object sender, EventArgs e)
{
if (myMedia.Volume == 100)
{
myMedia.Volume = 0;
muteButt.Content = "Listen";
}
else
{
myMedia.Volume = 100;

294
WPF

muteButt.Content = "Mute";
}
}
}
}

When you compile and execute the above code, it will produce the following window. You
can play the video and control its playback with the three buttons.

With the buttons you can pause, mute, and play the video.

Speech Synthesizer
WPF has features to convert text to speech. This API is included in System.Speech
namespace. SpeechSynthesizer class transforms text into spoken words.

Example
Lets have a look at a simple example.

1. Create a new WPF project with the name WPFTextToSpeech.

2. We will need System.Speech assembly to add as reference for SpeechSynthesizer


class to work.

3. Right click on References and Select Add Reference.

295
WPF

4. Reference Manager dialog will open. Now check the System.Speech check box

296
WPF

5. Click the Ok button. You can see the System.Speech assembly in your References.

6. Now drag a button and a textbox into the design window from the toolbox.

7. The following XAML code creates a button and a textbox, and initializes them with
some properties.

<Window x:Class="WPFTextToSpeech.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:WPFTextToSpeech"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="604">
<Grid>
<Button x:Name="button" Content="Speak"
HorizontalAlignment="Left" Margin="218,176,0,0"
VerticalAlignment="Top" Width="75"/>

297
WPF

<TextBox x:Name="textBox" HorizontalAlignment="Left"


Height="23" Margin="60,104,0,0" TextWrapping="Wrap"
VerticalAlignment="Top" Width="418"/>
</Grid>
</Window>

8. Here is the simple implementation in C# which will convert the Text inside the
textbox into spoken words.

using System.Speech.Synthesis;
using System.Windows;

namespace WPFTextToSpeech
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void button_Click(object sender, RoutedEventArgs e)
{
if (textBox.Text != "")
{
SpeechSynthesizer speechSynthesizer = new SpeechSynthesizer();
speechSynthesizer.Speak(textBox.Text);

}
else
{
MessageBox.Show("Write some thing in the textbox!");
}
}
}

298
WPF

When you compile and execute the above code, it will produce the following window. Now,
type Hello World inside the textbox and click the Speak button.

It will produce the sound "Hello World". If you dont type anything in the textbox, then it
will flash the following message.

We recommend that you execute the above examples.

299

Potrebbero piacerti anche