WPF Tutorial PDF
WPF Tutorial PDF
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.
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 [email protected]
i
WPF
Table of Contents
About the Tutorial .................................................................................................................................. i
Audience ................................................................................................................................................ i
Prerequisites .......................................................................................................................................... i
WPF Features...................................................................................................................................... 2
Installation ............................................................................................................................................ 3
ii
WPF
9. BUTTON ........................................................................................................................... 37
18. IMAGE.............................................................................................................................. 99
iv
WPF
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,
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.
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
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
2
2. WPF ENVIRONMENT SETUP WPF
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.
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.
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.
7
WPF
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.
<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>
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.
The Object element must be closed by a forward slash (/) followed immediately by
a right angle bracket (>).
13
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;
}
}
}
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.
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
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:
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.
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.
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.
<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.
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.
21
WPF
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
}
}
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.
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
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();
}
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;
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
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:
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
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
30
WPF
if (button != null)
button.Click += Button_Click;
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();
}
}
}
}
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.
All of the standard WPF controls can be found in the Toolbox which is a part of the
System.Windows.Controls.
34
WPF
The following table contains a list of controls which we will discuss in the subsequent
chapters.
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
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)
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)
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.
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
</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();
}
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:
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.
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().)
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>
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();
}
}
}
}
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
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)
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)
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.
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>
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.";
}
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
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)
64
WPF
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.
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();
}
{
textBox.Text = comboBox.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
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)
71
WPF
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>
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;
}
74
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 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:
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
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.
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>
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 MainWindow() {
InitializeComponent();
dataGrid.ItemsSource = Employee.GetEmployees();
}
}
81
WPF
82
WPF
return employees;
}
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:
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.
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)
Example
1. Lets create a new WPF project with the name WPFDatePickerControl.
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>
using System;
using System.Windows;
using System.Windows.Controls;
namespace WPFDatePickerControl
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
88
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 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:
Example
Lets take an example to understand the concept of Dialog Box. First of all, create a new
WPF project with the name WPFDialog.
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>
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:
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)
95
WPF
when a keyboard key is released while the UIElement has focus. (Inherited
from UIElement)
Example
1. Lets take an example to understand the concept better. Start by creating a new
WPF project with the name WPFGridView.
<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>
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
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.
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.
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.
<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:
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.)
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)
Example
1. Lets create a new WPF project with the name WPFLabelControl.
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
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:
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
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
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:
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.)
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.
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>
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:
119
WPF
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
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:
123
WPF
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
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:
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.
127
WPF
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"
</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
130
WPF
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)
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)
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>
using System.Windows;
using System.Windows.Controls;
namespace WPFRadioButtonControl
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
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:
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.
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.
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
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:
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.
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
Example
1. Lets create a new WPF project with the name WPFDialog.
2. Drag one slider and two text blocks from the Toolbox.
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
</StackPanel>
</Window>
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
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:
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.
Example
1. Lets create a new WPF project with WPFTextBlockControl.
3. Change the background color of the text block from the properties window.
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
</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:
Example
1. Lets create a new WPF project with WPFToggleButtonControl.
3. Change the background color of the text block from the properties window.
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>
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";
}
}
}
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:
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.
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.
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
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
158
WPF
159
WPF
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.
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.
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
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>
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>
using System.Windows;
namespace RichTextBoxDemo
{
/// <summary>
166
WPF
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:
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
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
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
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.)
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
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
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.
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:
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.
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.)
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"/>
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.
<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"/>
187
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 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.
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
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.
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
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.
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>
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.");
}
197
WPF
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.
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.
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>
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
}
}
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.
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>
<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.
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
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.
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
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.
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
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}"/>
212
WPF
</Window>
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.
StaticResource
DynamicResource
Example
Here's a simple application for the SolidColorBrush resource.
<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
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.
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.
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:
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:
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>
<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>
<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
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}"/>
Text="{Binding Age}"/>
</Grid>
</DataTemplate>
</Window.Resources>
223
WPF
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
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; }
}
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.
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.
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
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
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
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
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
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
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.
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 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
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; }
}
}
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
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.
1. Go to the Tools menu and select Options from the Tools menu.
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
</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.
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
<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.
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">
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();
}
<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
Fault in your code or in code that you call (such as a shared library),
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.
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:
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
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.
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>
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
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:
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.
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
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.
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
</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.
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.
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();
}
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.
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.
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.
<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
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.
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
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.
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
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.
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.
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>
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();
}
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.
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
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.
299