ASP.NET – How to Work With Windows Presentation Foundation (WPF)

Windows Presentation Foundation

Introduction to Windows Presentation Foundation

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. Some examples are Yahoo! Messenger as well as the Contoso Healthcare Sample Application that is shown in the following figure.

The core of WPF is a resolution-independent and vector-based rendering engine that is built to take advantage of modern graphics hardware. 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. WPF is included in the Microsoft .NET

Framework, so you can build applications that incorporate other elements of the .NET Framework class library.

Programming with WPF

WPF exists as a subset of .NET Framework types that are for the most part located in the System.Windows namespace. If you have previously built applications with .NET Framework using managed technologies 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 programming language, such as C# or Visual Basic.

To support some of the more powerful WPF capabilities and to simplify the programming experience, WPF includes additional programming constructs that enhance properties and events: dependency properties and routed events.

Markup and Code-Behind

WPF offers additional programming enhancements for Windows client application development. One obvious enhancement is the ability to develop an application using both markup and code-behind, an experience that ASP.NET developers should be familiar with. 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 because appearance-specific markup is not tightly coupled with behavior-specific code.
  • 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 2005 targets developers.
  • Globalization and localization for WPF applications is greatly simplified (see WPF Globalization and Localization Overview).

The following is a brief introduction to WPF markup and code-behind. For more information on this programming model, see XAML Overview and Code-Behind and XAML.

Markup

XAML is an XML-based markup language that is used to implement an application’s appearance declaratively. It is typically used to create windows, dialog boxes, pages, and user controls, and to fill them with controls, shapes, and graphics.

<Window

xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;

Title=”Window with Button”

Width=”250″ Height=”100″>

<Button Name=”button”>Click Me!</Button>

</Window>

Specifically, this XAML defines a window and a button by using the Window and Button elements, respectively. Each element is configured with attributes, such as the Window element’s Title attribute to specify the window’s title-bar text. At run time, WPF converts the elements and attributes that are defined in markup to instances of WPF classes. For example, the Window element is converted to an instance of the Window class whose Title property is the value of the Title attribute.

Button button=new Button();

Button.Content = “Click Me!”;

Since XAML is XML-based, the UI that you compose with it is assembled in a hierarchy of nested elements known as an element tree. The element tree provides a logical and intuitive way to create and manage UIs. For more information, see Trees in WPF.

Code-Behind

The main behavior of an application is to implement the functionality that responds to user interactions, including handling events (for example, clicking a menu, tool bar, or button) and calling business logic and data access logic in response. In WPF, this behavior is generally implemented in code that is associated with markup. This type of code is known as code-behind. The following example shows the code-behind and updated markup from the previous example.

<Window

xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;

xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml&#8221;

x:Class=”SDKSample.AWindow”

Title=”Window with Button”

Width=”250″ Height=”100″>

<Button Name=”button” Click=”button_Click”>Click Me!</Button>

</Window>

using System.Windows;

namespace SDKSample

{

public partial class AWindow : Window

{

public AWindow()

{ InitializeComponent(); }

void button_Click(object sender, RoutedEventArgs e)

{ MessageBox.Show(“Hello, Windows Presentation

Foundation!”);

}

}}

Controls

The user experiences that are delivered by the application model are constructed controls. In WPF, “control” is an umbrella term that 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.

Input and Commanding

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.

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

Most applications are created to provide users with the means to view and edit data. 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, the hard work for WPF applications begins. Essentially, this involves two things:

  1. Copying the data from the managed objects into controls, where the data can be displayed and edited.
  2. 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). This relationship is illustrated by the following figure.

Graphics

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, and provides the foundation for resolution-independent and device-independent rendering. 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. WPF also supports a wide color gamut (scRGB) and provides integrated support for managing inputs from different color spaces.
  • 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 illustration.

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. The following example shows the MouseUp event of an Ellipse being handled.

XAML:

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 array of strings or an instance of 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>

StaticResource ResourceKey=mycolor}” Content = “Click” />

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.

For example, suppose we have a specific color we want to use as the background for several buttons in a WPF application. We could set the Background property on each of the buttons to use the same color, but it would become tedious if we ever needed to change that color. 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.

Transforms:

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 shift 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 AngleY 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 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 property which can be set to an arbitrary number of transform instances.

Note: When applying multiple transforms by using a Transform Group, remember that the order of the transforms can have a strong impact on the result.

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.

Animations:

It is one of the most complicated topics to discuss in WPF, not because it is technically more difficult, but because it has many prerequisites. To fully understand animation, you need to have knowledge of routed events, dependency properties, triggers and many others aspects of WPF.

Before we dig into deep let us first understand the fundamentals of animation. At its root, an animation is a series of images in rapid succession to give the illusion of motion i.e. continuous change. The practical difficulty of producing animation is that it takes a large number of images to create even a few seconds of motion.

The individual images in an animation are referred as frames. The number of frames per second (fps) is called the frame rate. Most television and film is somewhere between 20 and 30 fps. The higher the frame rate, the smoother the animation will seem. Computer graphics generally target a frame rate around 60 fps.

Teams of animators are employed to create all the necessary frames. However, a lead animator draws the key frames. Key frames are the frames that represent significant points in the motion, such as the start and end points. All the remaining frames, those in between the key frames, are called tweens.

The animation system of WPF, as well as that of adobe flash, allows you to define the key frames, and then it will handle the tweens for you. For example, say that you have a circle that you want to move along a linear path from the right side of the screen to the left, you can specify the starting position and the ending position of the circle, and then allow WPF to interpolate all the necessary positions in between.

One of the central concepts behind animation in WPF is timelines. (In fact, timelines are central to most computer animation frameworks). A timeline is a segment of time; it has a beginning point and duration. In other words, it is “when does the animation start” and “how long does it last.” In some cases, you will designate key frames at certain points along the timelines, but in many cases the key frames will be implied from the beginning and the end of the timeline.

Timeline has two implicit key frames. The first is right at the beginning, that is 0:0:0 and the second is what we need to specify in h:m:s format.

To animate something, we need to answer a few questions for WPF:

-What object are we targeting for the animation?

-Which property on the target object we are going to animate?

-When does the animation start? Or what triggers the animation?

-How long does the animation last?

-How does the property change over the course of the animation?

Properties of TimeLine:

AccelearationRadio: Percentage of duration that the animation will speed up at the beginning. Values are between 0.0 to 1.0.

DecelarationRadio: Percentage of duration that the animation will slow down at the end. Values are between 0.0 to 1.0.

AutoReverse: If true, the animation will play in reverse after its first forward playback.

BeginTime: This allows you to set an offset for when the animation will begin-for example, if you want the playback to start 2 seconds after the animation is triggered.

RepeatBehavior: Allows you to control if and how an animation will repeat. For example, it might repeat just once or forever. There are 3 ways to set the behavior. The value “Forever” causes the animation to repeat forever. You can specify a specific number of iterations with a number followed by x. for example, 2x will repeat twice. Finally you can specify duration in the same format we’ve seen before “h:m:s”.

Controlling an Animation:

BeginStoryboard Starts the animation.

PauseStoryboard Pauses the animation.

RemoveStoryboard Removes the storyboard.

ResumeStoryboard Resumes play for the paused storyboard.

SetStoryboardSpeedRatio Allows you to change the speed of playback.

StopStoryboard Stops playback.

Reference : Dilip Kumar Jena ( https://mstechexplore.wordpress.com )

Advertisements

One thought on “ASP.NET – How to Work With Windows Presentation Foundation (WPF)

  1. Pingback: Reinventing Wheels: drawing graphs in .NET | Azoft Spotlight

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s