Windows Presentation Foundation (WPF) Tutorial

This C#.Net tutorial, we will discuss what is Windows Presentation Foundation (WPF) in C#.Net, WPF Controls, and Layout, Data Binding and Graphics in WPF, Transforms in WPF and their types, MVVM with WPF, Role of XAML in WPF, how to give Tooltips in WPF in Asp.Net, etc.

Introduction to Windows Presentation Foundation (WPF)

Windows Presentation Foundation (WPF) is a next-generation presentation system for building Windows client applications with visually stunning user experiences. With WPF, you can create a wide range of both standalone and browser-hosted applications.

WPF extends the core with a comprehensive set of application-development features that include Extensible Application Markup Language (XAML), controls, data binding, layout, 2-D and 3-D graphics, animation, styles, templates, documents, media, text, and typography.

Programming with WPF

WPF exists as a subset of .NET Framework types that are for the most part located in the System.Windows namespace. like ASP.NET and Windows Forms, the fundamental WPF programming experience should be familiar; you instantiate classes, set properties, call methods, and handle events, all using your favorite .NET Framework programmings language, such as C#.Net or Visual Basic.

WPF includes additional programming constructs that enhance properties and events: dependency properties and routed events.

WPF offers additional programming enhancements for Windows client application development. like the ability to develop an application using both markup and code-behind. You generally use Extensible Application Markup Language (XAML) markup to implement the appearance of an application while using managed programming languages (code-behind) to implement its behavior. This separation of appearance and behavior has the following benefits:

  • Development and maintenance costs are reduced.
  • Development is more efficient because designers can implement an application’s appearance simultaneously with developers who are implementing the application’s behavior.
  • Multiple design tools can be used to implement and share XAML markup, to target the requirements of the application development contributors; Microsoft Expression Blend provides an experience that suits designers, while Visual Studio 2010 targets developers.
  • Globalization and localization for WPF applications is greatly simplified.

Role of XAML in WPF

Now, we will discuss how XAML is playing an important role in WPF.

XAML, or Extensible Application Markup Language, is an XML based markup language created by Microsoft which is fundamental to WPF as HTML for web development.

XAML pronounced as zammel is the language used for creating user interfaces in WPF. It’s an XML-based markup language similar to HTML. XAML has applicability well beyond defining user interfaces. In fact, it’s even possible to represent data with XAML, such as an array of strings or an instance of an object.

Even though Visual Studio 2008 provides a WYSIWYG editor with drag and drop support for producing and manipulating XAML, you will often need to edit your markup directly. The default file extension is .xaml.

<Button Name = "button" Width = "100" Height = "40" Background = "Blue" Content = "Click Me" />

Property Element:

<Button Name = "button" Width = "100" Height = "40">
<Button.Background>
<SolidColorBrush Color = "Blue"/>
  </Button.Background>
</Button>

Content Property:

<Button Content = "Click" />
<Button> Click </Button>
<Button>
<Button.Content> Click </Button.Content>
<Button>
<Button>
<Button.Content>
<Ellipse Width = "24" Height = "24" Fill = "Yellow"/ >
</Button.Content>
<Button>
<Button Background = "{StaticResource ResourceKey=mycolor}" Content = "Click" />
<Button Background = "{StaticResource mycolor}" Content = "Click" />
<Application.Resources>
        <Color x:Key="mycolor">Red</Color>
    </Application.Resources>

Markup Extensions:

Sometimes we need to specify values in our markup that are either difficult to express in XAML or outside the scope of the XAML processor. XAML has a feature called markup extensions and it allows us to handle these awkward situations.

With WPF, we can store the color with a lookup key in an application’s resources and then we can set the background of the buttons to the color we stored in the resources. If we want to change the color, we need do so in only one place. To handle this in XAML we use the markup extensions.

The XAML with the markup extension might look like this:

<Button Background = "{StaticResource ResourceKey = <key>}" />

Markup extensions are identified by the presence of curly braces. The first word in the markup extensions tells WPF what kind of extension it is which is followed by a set of named parameters optionally. In this case, the extension is for retrieving a shared resource from a library or resources.

The name of the extension is StaticResource, and we provide a value for the ResourceKey parameter. Many extensions have a default parameter which doesn’t require to be referenced explicitly. In the above case ResourceKey is the default parameter so it can be written as:

<Button Background = "{StaticResource <key>}" />

Markup Extensions supported in XAML:

  • Binding: The extension used for binding data.
  • StaticResource: This is used for retrieving data from an application’s resources. Static resources are not expected to change while the application is running.

DynamicResource Similar to StaticResource, except that the data in the resource might change during runtime.

  • x:Null: Used for specifying a null value in XAML.
  • x:Type: This is used for supplying a System.Type object.
  • x: Array: This allows you to define an array of objects in XAML.

How to give Tooltips in WPF

Now we will see how to give Tooltips in WPF. How we can set tooltip in WPF as well as we will discuss different tooltip properties.

Tooltips in WPF are content controls, you can place virtually anything inside a tooltip. You can also tweak various timing settings to control how quickly tooltips appear and disappear. WPF has a flexible model for tooltips.

The easiest way to show a tooltip doesn’t involve using the ToolTip class directly. Instead, you simply set the ToolTip property of your element. The ToolTip property is defined in the FrameworkElement class, so it’s available on anything you’ll place in a WPF window.

Example:

<Button ToolTip="This is a way of my tooltip">Raj button</Button>

In this case, When you hover over this button, the text “This is a way of my tooltip” appears in the familiar yellow box.

If more than one tooltip overlaps, the most specific tooltip wins.

The ToolTip is a content control, so you can adjust standard properties such as the background (so it isn’t a yellow box), Padding, and Font. You can also modify the members that are defined in the ToolTip class

The below are some tooltip properties:

  • HasDropShadow
  • Placement
  • HorizontalOffset and VerticalOffset
  • PlacementTarget
  • PlacementRectangle
  • CustomPopupPlacementCallback
  • StaysOpen

The below some strategies you can use to place a tooltip:

  • Based on the current position of the mouse- This is the standard behavior, which relies on Placement being set to Mouse. The top-left corner of the tooltip box is lined up with the bottom-left corner of the invisible “bounding box” around the mouse pointer.
  • Based on the position of the moused-over element- Set the Placement property to Left,Right, Top, Bottom, or Center, depending on the edge of the element you want to use.
  • Based on the position of another element- Set the Placement property in the same way you would if you were lining the tooltip up with the current element.
  • Using absolute coordinates- Set Placement to Absolute and use the HorizontalOffset and VerticalOffset properties to set some space between the tooltip and the top-left corner of the window.

WPF Controls and Layout

Now, will discuss different Controls and Layout in WPF.

WPF Controls

In WPF, “control” applies to a category of WPF classes that are hosted in either a window or a page, have a user interface (UI), and implement some behavior.

The built-in WPF controls are listed here.

  • Buttons: Button and RepeatButton.
  • Dialog Boxes: OpenFileDialog, PrintDialog, and SaveFileDialog.
  • Digital Ink: InkCanvas and InkPresenter.
  • Documents: DocumentViewer, FlowDocumentPageViewer, FlowDocumentReader, FlowDocumentScrollViewer, and StickyNoteControl.
  • Input: TextBox, RichTextBox, and PasswordBox.
  • Layout: Border, BulletDecorator, Canvas, DockPanel, Expander, Grid, GridView, GridSplitter, GroupBox, Panel, ResizeGrip, Separator, ScrollBar, ScrollViewer, StackPanel, Thumb, Viewbox, VirtualizingStackPanel, Window, and WrapPanel.
  • Media: Image, MediaElement, and SoundPlayerAction.
  • Menus: ContextMenu, Menu, and ToolBar.
  • Navigation: Frame, Hyperlink, Page, NavigationWindow, and TabControl.
  • Selection: CheckBox, ComboBox, ListBox, TreeView, and RadioButton, Slider.
  • User Information: AccessText, Label, Popup, ProgressBar, StatusBar, TextBlock, and ToolTip.

Controls most often detect and respond to user input. The WPF input system uses both direct and routed events to support text input, focus management, and mouse positioning. Applications often have complex input requirements. WPF provides a command system that separates user input actions from the code that responds to those actions.

WPF Layout

When you create a UI, you arrange your controls by location and size to form a layout. A key requirement of any layout is to adapt to changes in window size and display settings. Rather than forcing you to write the code to adapt a layout in these circumstances, WPF provides a first-class, extensible layout system for you.

The aim of the layout system is relative positioning, which increases the ability to adapt to changing window and display conditions. In addition, the layout system manages the negotiation between controls to determine the layout. The negotiation is a two-step process: first, a control tells its parent what location and size it requires; second, the parent tells the control what space it can have.

The layout system is exposed to child controls through base WPF classes. For common layouts such as grids, stacking, and docking, WPF includes several layout controls:

  • Canvas: Child controls provide their own layout.
  • DockPanel: Child controls are aligned to the edges of the panel.
  • Grid: Child controls are positioned by rows and columns.
  • StackPanel: Child controls are stacked either vertically or horizontally.
  • VirtualizingStackPanel: Child controls are virtualized and arranged on a single line that is either horizontally or vertically oriented.
  • WrapPanel: Child controls are positioned in left-to-right order and wrapped to the next line when there are more controls on the current line than space allows.

Data Binding and Graphics in WPF

Now, we will discuss on Data Binding and Graphics in WPF

For WPF applications, the work of storing and accessing data is already provided for by technologies such as Microsoft SQL Server and ADO.NET. After the data is accessed and loaded into an application’s managed objects, work for WPF applications begins.

Essentially, this involves two things:

  • Copying the data from the managed objects into controls, where the data can be displayed and edited.
  • Ensuring that changes made to data by using controls are copied back to the managed objects.

To simplify application development, WPF provides a data binding engine to automatically perform these steps.

The core unit of the data binding engine is the Binding class, whose job is to bind a control (the binding target) to a data object (the binding source).

Graphics in WPF

Graphics in WPF

WPF introduces an extensive, scalable, and flexible set of graphics features that have the following benefits:

Resolution-independent and device-independent graphics
The basic unit of measurement in the WPF graphics system is the device-independent pixel, which is 1/96th of an inch, regardless of actual screen resolution. Each device-independent pixel automatically scales to match the dots-per-inch (dpi) setting of the system it renders on.

Improved precision
The WPF coordinate system is measured with double-precision floating-point numbers rather than single-precision. Transformations and opacity values are also expressed as double-precision.

Advanced graphics and animation support
WPF simplifies graphics programming by managing animation scenes for you; there is no need to worry about scene processing, rendering loops, and bilinear interpolation. Additionally, WPF provides hit-testing support and full alpha-compositing support.

Hardware acceleration
The WPF graphics system takes advantage of graphics hardware to minimize CPU usage.

2-D Shapes
WPF provides a library of common vector-drawn 2-D shapes, such as the rectangles and ellipses that are shown in the following illus.

An interesting capability of shapes is that they are not just for display; shapes implement many of the features that you expect from controls, including keyboard and mouse input.

Data Binding and Graphics in WPF

Transforms in WPF and their types

Now, we will discuss how Transforms in WPF takes the responsibility of rendering the objects.

Some visuals would be difficult or impossible to achieve directly, so for achieving it, WPF provides transforms, which will take the responsibility of rendering the objects.

Those are:

  • Translate Transform: It does nothing more than shifting an element away from its current location. The important properties on this are X and Y, setting these properties controls how the element will be translated along the x or y-axis.
  • Skew Transform: It distorts the original element by shearing or shifting it along the x or y-axis. To control this, you can use the AngleX and Angle Y properties with values from -90 to 90.
  • Rotate Transform: It alters an element by rotating it based on a specified angle. It should be no surprise that this is accomplished by setting the Angle property.
  • Scale Transform: If you need to alter an element’s size, use this transform. It has ScaleX and ScaleY properties, which enable this functionality. Setting these properties to different values will cause the element to be stretched along either the x or y-axis. A value of 1 represents the normal size, whereas using a 2 would be double the size.
  • Transform Group: Many times you cannot get the desired transformation by a single transform, in this case, you should use the Transform Group. It has a children’s property which can be set to an arbitrary number of transform instances.
  • Bitmap Effects: The final piece of WPF’s visual puzzle is bitmap effects. Every UIElement has a BitmapEffect property that can be used to add various special shader like effects to the element. Several built-in effects represent things that designers use frequently.
  • DropShadowBitmapEffect: it is one of the most common effects you’ll want to apply to an element. It adds a shadow behind the element, cast by a configurable light source. Normally the default effect works for most needs, but you can customize it by using several properties. The most common properties you will use are ShadowDepth, Color, and Direction.
  • OuterGlowBitmapEffect: it adds a halo to the element it is applied to. This can add a very nice, subtle effect to text and is great for providing user feedback for mouseover events. GlowColor and GlowSize are handy properties for controlling the main aspects of the halo.
  • BlurBitmapEffect: if you want to make an element appear unfocused or blurry, use this effect. You will likely want to adjust its Radius property to set the degree of blurriness.
  • EmbossBitmapEffect: To add texture or depth to an object, you may use this effect.
  • BevelBitmapEffect: if you want to give the element an appearance of being raised, you can add this effect. It has LightAngle and Relief properties, but it can be further customized by setting its BevelWidth, EdgeProfile, and Smoothness.
  • BitmapEffectGroup: if you desire to apply multiple effects to a single element, you would use this effect.
  • Triggers: these are special features of Style, DataTemplate and Framework Element. Thru the careful use of triggers, you can declaratively enable your UI and graphics to respond to mouse events, changes in dependency properties, and even changes in your application’s data model.

Each trigger in the collection is connected to a specific property and value. When the specified property matches the value declared in the trigger, it uses its setter’s collection to alter the UI. When the trigger’s value ceases to match the property, the effects of the setters are removed.

If multiple triggers alter the same UI properties, the last one wins.

The setter elements used in a trigger are the same as those used in a style.

There’s no limit to the number of setters and triggers you can define. The only stipulation is that you must trigger and alter dependency properties only.

MVVM (Model view and view Model) pattern in WPF

Here in this article we will discuss about MVVM pattern in WPF and one example how to implement this pattern.

MVVM is nothing but the Model view and viewModel. This is the best architecture for WPF.

View:
A View is defined in XAML and should not have any logic in the code-behind. It binds to the view-model by only using data binding.

The View contains the visual controls that will be shown to the user.This is the UI.

Normally the View is only aware of the ViewModel but there might be cases in which it may make sense to expose the Model directly to it.

Model:
This is simply a class representing your data. It has no functionality but the ability to hold data. It is your data or classes that represent entities in your application.

ViewModel:
This object of the MVVM pattern represents the interface between your business logic and your user interface. This is the way you connect your model to a specific View.

Advantages of MVVM pattern in WPF:

  • A clean separation between application logic and the UI will make an application easier to test, maintain. It improves code re-use opportunities.developer-designer can able to work on the same time.
  • During the development process, developers and designers can work more independently and concurrently on their components.The designers can concentrate on the view, and if they are using Expression Blend, they can easily generate sample data to work with, while the developers can work on the view model and model components.
  • It is easy to redesign the UI of the application without touching the code because the view is implemented entirely in XAML.

Example:

Now we will see one small implementation,where we are binding the values from the Model class through viewmodel to a ComboBox which is present in our view.

Open your VisualStudio,Go to File->New->Project->select Visual C#->Windows->Select “WPF Application” from the template window and Give the name as “EASYMVVM”->Then click on “OK”.

Then You will find some default file created that are Properties,References,App.Xaml and MainWindow.xaml.

Now just create 3 new folders like “View”,”ViewModel” and “Model”.

Then now Right click on the “Model” folder->Add NewItem->Choose Class->give the class name as Model.cs. So now inside Model we have a class named as “Model.cs”.

As per my example my content of the Model.cs class is like below.

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;

namespace EasyMVVM.Model
{
public class Model
{
private ObservableCollection<string> objCollection = new ObservableCollection<string>();
public ObservableCollection<string> GetData()
{
//You can place here any query a database or any other buisness logic.
objCollection.Add("Your Choice");
objCollection.Add("Raj");
objCollection.Add("Kishore");
objCollection.Add("Sahoo");

return objCollection;
}

}
}

Here in above we are taking one generic observable collection which will contain string type data.

Now the time for ViewModel class.Now Right click on the ViewModel folder->Add NewItem->Choose Class->give the class name as “MainWindowVM.cs”

In my example the MainWindowVM.cs class will contain the below part of the code

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows;
using EasyMVVM.Model;

namespace EasyMVVM.ViewModel
{
public class MainWindowVM : DependencyObject,INotifyPropertyChanged
{

public MainWindowVM()
{
EasyMVVM.Model.Model objModel = new EasyMVVM.Model.Model();
BoundProperty = objModel.GetData();
}

//set up a private class varialbe that holds the value of the _Backing Property
private ObservableCollection<string> _Property;
//This is the publically viewable Property for this class
public ObservableCollection<string> BoundProperty
{
get
{
return _Property;
}
set
{
_Property = value;
PropChanged("BoundProperty");
}
}
//This event will be fired to notify any listeners of a change in a property value.
public event PropertyChangedEventHandler PropertyChanged;
//It will say WPF Binding that this property value has changed
public void PropChanged(String propertyName)
{

if (PropertyChanged != null)
{
//Tell WPF that this property changed
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}

Note: As we are using ObservableCollection here so if we won’t use “INotifyPropertyChanged” interface to notify the view, It will also work because if you will go inside the ObservableCollection,you can able to see “INotifyCollectionChanged” and “INotifyPropertyChanged” interfaces it is calling internally.

Now our modelview class over and now let’s go to the view. Now cut the “MainWindow.xaml” and paste into the “View” folder and modify the view accordingly.

Note: Open the App.Xaml file and change the startup uri like “StartupUri=”View/MainWindow.xaml”.As we moved the “MainWindow.xaml” file to the “View” file.

Here in the view we need to add the below two part of the code.

Part-1

xmlns:vm=”clr-namespace:EasyMVVM.ViewModel”

The below part also we added.

Part-2

<StackPanel>
<StackPanel.Resources>
<vm:MainWindowVM x:Key="vm"></vm:MainWindowVM>
</StackPanel.Resources>
<ComboBox Height="30″ Width="100″ Margin="100,50,90,50″ ItemsSource="{Binding Source={StaticResource vm}, Path=BoundProperty}" Cursor="Arrow" SelectedIndex="0″/>
</StackPanel>

Here is my complete view code.

<Window x:Class="EasyMVVM.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:EasyMVVM.ViewModel"
Title="MainWindow" Height="350″ Width="525″>
<StackPanel>
<StackPanel.Resources>
<vm:MainWindowVM x:Key="vm"></vm:MainWindowVM>
</StackPanel.Resources>
<ComboBox Height="30″ Width="100″ Margin="100,50,90,50″ ItemsSource="{Binding Source={StaticResource vm}, Path=BoundProperty}" Cursor="Arrow" SelectedIndex="0″/>
</StackPanel>
</Window>

Here in this view we are taking one combobox which will bind all the values from Model class through viewModel.

We need to mention BInding, Source, path here and “Path=BoundProperty” here BoundProperty is the property declared in our MainWindowVM.cs class.

You may like following C#.Net tutorials:

This WPF tutorial, we learned the below things:

  • Introduction to Windows Presentation Foundation (WPF)
  • Role of XAML in WPF
  • How to give Tooltips in WPF
  • WPF Controls and Layout
  • Data Binding and Graphics in WPF
  • Transforms in WPF and their types
  • MVVM (Model view and view Model) pattern in WPF
  • Advantages of MVVM pattern in WPF
Donwload Hub site pdf

Download SharePoint Online Tutorial PDF FREE!

Get update on Webinars, video tutorials, training courses etc.

Bijay Kumar

I am Bijay from Odisha, India. Currently working in my own venture TSInfo Technologies in Bangalore, India. I am Microsoft Office Servers and Services (SharePoint) MVP (5 times). I works in SharePoint 2016/2013/2010, SharePoint Online Office 365 etc. Check out My MVP Profile.. I also run popular SharePoint web site SPGuides.com

>