Windows Presentation Foundation

From Wikipedia, the free encyclopedia
Windows Presentation Foundation (WPF)
Original author(s)Microsoft
Developer(s).NET Foundation
Initial releaseNovember 21, 2006; 17 years ago (2006-11-21)
Stable release
v8.0.0 / November 14, 2023; 6 months ago (2023-11-14)[1]
Repository
Written inC#, C++, C
Operating systemMicrosoft Windows
Platform.NET Framework, .NET
TypeSoftware framework
LicenseMIT License
Websitelearn.microsoft.com/en-us/dotnet/desktop/wpf/

Windows Presentation Foundation (WPF) is a free and open-source user interface framework for Windows-based desktop applications. WPF applications are based in .NET, and are primarily developed using C# and XAML.[2]

Originally developed by Microsoft, WPF was initially released as part of .NET Framework 3.0 in 2006. In 2018, Microsoft released WPF as open source under the MIT License.

Overview[edit]

WPF employs XAML, an XML-based language, to define and link various interface elements, and uses C# to define program behavior.[3] WPF applications are deployed as standalone desktop programs.

WPF aims to unify a number of common user interface elements, such as 2D/3D rendering, fixed and adaptive documents, typography, vector graphics, runtime animation, and pre-rendered media. These elements can then be linked and manipulated based on various events, user interactions, and data bindings.[4]

WPF runtime libraries are included with all versions of Microsoft Windows since Windows Vista and Windows Server 2008.

At the Microsoft Connect event on December 4, 2018, Microsoft announced releasing WPF as open source project on GitHub. It is released under the MIT License. Windows Presentation Foundation has become available for projects targeting the .NET software framework, however, the system is not cross-platform and is still available only on Windows.[5][6]

Code examples[edit]

Screenshot of developing a basic Windows Presentation Foundation (WPF) UI application in Visual Studio 2022. XAML is used to define the layout, while C# is used to define the interactive behavior.

In WPF, screens and other UI elements are defined using a pair of files: a XAML file and an associated C# file with the extension .xaml.cs, often referred to as a "code-behind". The XAML file declaratively defines the layout, contents and other properties of the UI element, while the C# file allows exposure of code entry points for interactivity.[3]

A basic example of an interactive Hello, World! program could be created like so:

MainWindow.xaml:

 <Window x:Class="WpfExample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="200" Width="300">
    <StackPanel Orientation="Vertical">
        <TextBlock Text="What is your name?"/>
        <TextBox x:Name="NameInputTextBox"/>
        <Button x:Name="SubmitButton" Click="SubmitButton_Click">
            <TextBlock Text="Submit"/>
        </Button>
        <TextBlock x:Name="ResultTextBlock"/>
    </StackPanel>
</Window>

MainWindow.xaml.cs:

using System.Windows;

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

        private void SubmitButton_Click(object sender, RoutedEventArgs e)
        {
            var name = this.NameInputTextBox.Text;
            this.ResultTextBlock.Text = $"Hello {name}!";
        }
    }
}

In the above example, a UI element called MainWindow is declared as a subclass of the built-in Window class. The XAML file defines the layout, which in this example is a vertical collection of controls - a textblock outlining instructions to the user, a textbox for the user to type their name, a button to submit, and a results text box. When the button is clicked, the method SubmitButton_Click is called, which is defined in the .xaml.cs file. This function updates the final textblock to contain a message greeting the user, addressing them by their submitted name.

Features[edit]

Direct3D[edit]

Graphics, including desktop items like windows, are rendered using Direct3D. This allows the display of more complex graphics and custom themes, at the cost of GDI's wider range of support and uniform control theming. It allows Windows to offload some graphics tasks to the GPU. This reduces the workload on the computer's CPU. GPUs are optimized for parallel pixel computations. This tends to speed up screen refreshes at the cost of decreased compatibility in markets where GPUs are not necessarily as powerful, such as the netbook market.

WPF's emphasis on vector graphics allows most controls and elements to be scaled without loss in quality or pixelization, thus increasing accessibility. With the exception of Silverlight, Direct3D integration allows for streamlined 3D rendering. In addition, interactive 2D content can be overlaid on 3D surfaces natively.[7][8]

Data binding[edit]

  • WPF has a built-in set of data services to enable application developers to bind and manipulate data within applications. It supports four types of data binding:
    1. one time: where the client ignores updates on the server.
    2. one way: where the client has read-only access to data.
    3. two way: where client can read from and write data to the server
    4. one way to source: where the client has write-only access to data
  • LINQ queries, including LINQ to XML, can also act as data sources for data binding.[8]
  • Binding of data has no bearing on its presentation. WPF provides data templates to control presentation of data.
  • A set of built-in controls is provided as part of WPF, containing items such as button, menu, grids, and list box.
  • Dependency Properties can be added to Behaviours or Attached Properties to add custom binding properties.
  • A powerful concept in the WPF is the logical separation of a control from its appearance.
    • A control's template can be overridden to completely change its visual appearance.
    • A control can contain any other control or layout, allowing for a high degree of control over composition.
  • Features retained mode graphics. Repainting the display isn't always necessary.

Media services[edit]

  • The WPF provides an integrated system for building user interfaces with common media elements like vector and raster images, audio, and video. WPF also provides an animation system and a 2D/3D rendering system.[9]
  • WPF provides shape primitives for 2D graphics along with a built-in set of brushes, pens, geometries, and transforms.
  • The 3D capabilities in WPF are a subset of the full-feature set provided by Direct3D. However, WPF provides tighter integration with other features like user interfaces, documents, and media. This makes it possible to have 3D user interfaces, 3D documents, or 3D media.
  • There is support for most common image formats: BMP, JPEG, PNG, TIFF, Windows Media Photo, GIF, and ICON.
  • WPF supports the video formats WMV, MPEG and some AVI files by default, but since it has Windows Media Player running beneath, WPF can use all the codecs installed for it.

Templates[edit]

  • In WPF you can define the look of an element directly, via its properties, or indirectly with a template or style. At its simplest a style is a combination of property settings that can be applied to a UI element with a single property attribute. Templates are a mechanism for defining alternative UI for portions of your WPF application. There are several template types available in WPF (ControlTemplate, DataTemplate, HierarchicalDataTemplate, and ItemsPanelTemplate).

Control templates

  • Underlying all UI controls in WPF is a new composition model. Every control is composed of one or more ‘visuals’. These visual sub-elements are turned into a hierarchical visual tree by WPF and eventually rendered by the GPU. Because WPF controls are not wrappers for standard Windows controls their UI can be radically changed without affecting the normal behavior of the control.
  • Every control in WPF has a default ‘template’ that defines its visual tree. The default template is created by the control author and is replaceable by other developers and designers. The substitute UI is placed within a ControlTemplate.

Data templates

  • WPF has a flexible data binding system. UI elements can be populated and synchronized with data from an underlying data model. Rather than showing simple text for the bound data, WPF can apply a data template (replaceable UI for .NET types) before rendering to the visual tree.

Animations[edit]

  • WPF supports time-based animations, in contrast to the frame-based approach. This decouples the speed of the animation from how the system is performing.
  • WPF supports low level animation via timers and higher level abstractions of animations via the Animation classes.
    • Any WPF element property can be animated as long as it is registered as a dependency property.
    • Animation classes are based on the .NET type of property to be animated. For instance, changing the color of an element is done with the ColorAnimation class and animating the width of an element (which is typed as a double) is done with the DoubleAnimation class.
  • Animations can be grouped into Storyboards.
    • Storyboards are the primary way to start, stop, pause and otherwise manipulate the animations.
  • Animations can be triggered by external events, including user action.[10]
  • Scene redraws are time triggered.[10]
  • Presentation timers are initialized and managed by WPF.[10]
  • Animation effects can be defined on a per-object basis, which can be accessed directly from XAML markup.[10]

Imaging[edit]

  • WPF can natively access Windows Imaging Component (WIC) code and APIs allowing developers to write image codecs for their specific image file formats.

Effects[edit]

  • WPF 3.0 provides for Bitmap effects (BitmapEffect class), which are raster effects applied to a Visual. These raster effects are written in unmanaged code and force rendering of the Visual to be performed on the CPU and not hardware accelerated by the GPU. BitmapEffects were deprecated in .NET 3.5 SP 1.
  • .NET Framework 3.5 SP1 adds the Effect class, which is a Pixel-Shader 2.0 effect that can be applied to a visual, which allows all rendering to remain on the GPU.
  • The Effect class is extensible, allowing applications to specify their own shader effects.
  • The Effect class, in .NET 3.5 SP1 and 4.0, ships with two built-in effects, BlurEffect and DropShadowEffect. There are no direct replacements for OuterGlowBitmapEffect, EmbossBitmapEffect and BevelBitmapEffect, previously provided by the deprecated BitmapEffect class. However, there are other ways of achieving the same results with the Effect class. For example, developers can get an outer glow effect by using the DropShadowEffect with its ShadowDepth set to 0.
  • Although the BitmapEffect class was marked as deprecated in .Net Framework 3.5 SP1, its use was still allowed and these effects would still render correctly. In .Net Framework 4.0 the BitmapEffect class was effectively deprecated - code referencing BitmapEffect still builds without errors, but no effect gets actually rendered.

Documents[edit]

  • WPF natively supports paginated documents. It provides the DocumentViewer class, which is for reading fixed layout documents. The FlowDocumentReader class offers different view modes such as per-page or scrollable and also reflows text if the viewing area is resized.
  • Natively supports XML Paper Specification documents.
  • Supports reading and writing paginated documents using Open Packaging Conventions.

Text[edit]

  • WPF includes a number of text rendering features that were not available in GDI. This is the first Microsoft programming interface to expose OpenType features to software developers, supporting OpenType, TrueType, and OpenType CFF (Compact Font Format) fonts.
  • Support for OpenType typographic features includes:
  • WPF handles texts in Unicode, and handles texts independent of global settings, such as system locale. In addition, fallback mechanisms are provided to allow writing direction (horizontal versus vertical) handled independent of font name; building international fonts from composite fonts, using a group of single-language fonts; composite fonts embedding. Font linking and font fallback information is stored in a portable XML file, using composite font technology.[11] The XML file has extension .CompositeFont.
  • The WPF text engine also supports built-in spell checking. It also supports such features as automatic line spacing, enhanced international text, language-guided line breaking, hyphenation, and justification, bitmap effects, transforms, and text effects such as shadows, blur, glow, rotation etc. Animated text is also supported; this refers to animated glyphs, as well as real-time changes in position, size, color, and opacity of the text.
  • WPF text rendering takes advantage of advances in ClearType technology, such as sub-pixel positioning, natural advance widths, Y-direction anti-aliasing, hardware-accelerated text rendering, as well as aggressive caching of pre-rendered text in video memory.[12] ClearType cannot be turned off in older WPF 3.x applications.[13] Unlike the ClearType in GDI or GDI+, WPF ClearType does not snap glyphs to pixels horizontally, leading to a loss of contrast disliked by some users.[14] The text rendering engine has been rewritten in WPF 4.0, correcting this issue.[15]
  • The extent to which glyphs are cached is dependent on the video card. DirectX 10 cards are able to cache the font glyphs in video memory, then perform the composition (assembling of character glyphs in the correct order, with the correct spacing), alpha-blending (application of anti-aliasing), and RGB blending (ClearType's sub-pixel color calculations), entirely in hardware. This means that only the original glyphs need to be stored in video memory once per font (Microsoft estimates that this would require 2 MB of video memory per font), and other operations such as the display of anti-aliased text on top of other graphics—including video—can also be done with no computation effort on the part of the CPU. DirectX 9 cards are only able to cache the alpha-blended glyphs in memory, thus requiring the CPU to handle glyph composition and alpha-blending before passing this to the video card. Caching these partially rendered glyphs requires significantly more memory (Microsoft estimates 5 MB per process). Cards that don't support DirectX 9 have no hardware-accelerated text rendering capabilities.

Interoperability[edit]

  • Windows Forms is also possible through the use of the ElementHost and WindowsFormsHost classes.

To enable the use of WinForms, the developer executes this from their WPF C# code:

 System.Windows.Forms.Integration.WindowsFormsHost.EnableWindowsFormsInterop();

Alternative input[edit]

  • WPF supports digital ink-related functionality.
  • WPF 4.0 supports multi-touch input on Windows 7 and above.

Accessibility[edit]

  • WPF supports Microsoft UI Automation to allow developers to create accessible interfaces.
  • This API also allows automated test scripts to interact with the UI.[16]

XAML[edit]

Following the success of markup languages for web development, WPF introduces eXtensible Application Markup Language (XAML; /ˈzæməl/), which is based on XML. XAML is designed as a more efficient method of developing application user interfaces.[17] The specific advantage that XAML brings to WPF is that XAML is a completely declarative language, allowing the developer (or designer) to describe the behavior and integration of components without the use of procedural programming. Although it is rare that an entire application will be built completely in XAML, the introduction of XAML allows application designers to more effectively contribute to the application development cycle. Using XAML to develop user interfaces also allows for separation of model and view, which is considered a good architectural principle. In XAML, elements and attributes map to classes and properties in the underlying APIs.

As in web development, both layouts and specific themes are well suited to markup, but XAML is not required for either. Indeed, all elements of WPF may be coded in a .NET language (C#, VB.NET). The XAML code can ultimately be compiled into a managed assembly in the same way all .NET languages are.

Deployment[edit]

WPF applications are Windows-only standalone desktop executables.

Historically, WPF supported compiling to XBAP, a file format intended to be shown in web browsers via a NPAPI plugin, but NPAPI and XBAP support was phased out of support by browsers, and XBAP compilation is now no longer included for WPF for .NET.[18][19]

Related Software[edit]

Development Tools[edit]

A number of development tools are available for developing Windows Presentation Foundation applications.

  • Microsoft Visual Studio is a developer-oriented IDE that contains a combination XAML editor and WPF visual designer, beginning with Visual Studio 2008.
  • Prior to Visual Studio 2008, the WPF designer add-in, codenamed Cider, was the original release of a WYSIWYG editor for creating WPF windows, pages, and user controls. It was available for Visual Studio 2005 as a Visual Studio 2005 extensions for .NET Framework 3.0 CTP for the initial release of WPF.[20]
  • Microsoft Blend is a designer-oriented tool that provides an artboard for the creation of WPF applications with 2D and 3D graphics, text and forms content. It generates XAML that may be exported into other tools and shares solution (sln files) and project formats (csproj, vbproj) with Microsoft Visual Studio.
  • Microsoft Expression Design is a bitmap and 2D-vector graphics tool for exporting to XAML.

Related UI Frameworks[edit]

WPF is related to a host of other UI frameworks, including:

References[edit]

  1. ^ "v8.0.0". github.com. 2023-11-14. Retrieved 2023-11-21.
  2. ^ "What is Windows Presentation Foundation - WPF .NET". learn.microsoft.com. 2023-06-02. Retrieved 2024-05-15.
  3. ^ a b dotnet-bot. "XAML Overview (WPF)". msdn.microsoft.com. Retrieved 31 March 2018.
  4. ^ Sells, Chris; Griffiths, Ian (2007). Programming WPF: Building Windows UI with Windows Presentation Foundation. "O'Reilly Media, Inc.". ISBN 9780596554798.
  5. ^ Martin, Jeff (4 December 2018). "Microsoft Open Sources WPF, WinForms, and WinUI". InfoQ. Retrieved 2018-12-06.
  6. ^ Hanselman, Scott (4 December 2018). "Announcing WPF, WinForms, and WinUI are going Open Source". Retrieved 2018-12-06.
  7. ^ "Introducing Windows Presentation Foundation". msdn.microsoft.com. Retrieved 31 March 2018.
  8. ^ a b "What's New in WPF 3.5? Here's Fifteen Cool Features..." Retrieved 2007-10-14.
  9. ^ Graphics and Multimedia. Msdn.Microsoft.com. Retrieved on 2013-08-29.
  10. ^ a b c d "Animation overview". MSDN. Retrieved 2007-10-14.
  11. ^ "Typography in Windows Presentation Foundation". msdn.microsoft.com. Retrieved 31 March 2018.
  12. ^ dotnet-bot. "ClearType Overview". msdn.microsoft.com. Retrieved 31 March 2018.
  13. ^ "Disable Antialiasing". social.msdn.microsoft.com. Retrieved 31 March 2018.
  14. ^ "My first thoughts on WPF with VS 2008 RTM and a few questions". social.msdn.microsoft.com. Retrieved 31 March 2018.
  15. ^ WPF 4 (VS 2010 and .NET 4.0 Series) - ScottGu's Blog. Weblogs.asp.net. Retrieved on 2013-08-29.
  16. ^ Xansky. "UI Automation Overview". msdn.microsoft.com. Retrieved 31 March 2018.
  17. ^ MacDonald, Matthew (2010). Pro WPF in VB 2010: Windows Presentation Foundation in .NET 4. Apress. ISBN 9781430272403.
  18. ^ adegeo. "FAQ about XBAP supportability". learn.microsoft.com. Retrieved 2024-05-15.
  19. ^ kexugit (2011-03-09). "IE9 - XBAPs Disabled in the Internet Zone". learn.microsoft.com. Retrieved 2024-05-15.
  20. ^ Retrieved from http://www.microsoft.com/en-au/download/details.aspx?id=23072.
  21. ^ "Avalonia UI - Cross-Platform UI Framework for .NET". Avalonia UI. Retrieved 2024-05-16.
  22. ^ "The Official Microsoft ASP.NET Site". The Official Microsoft ASP.NET Site. Retrieved 31 March 2018.

Bibliography[edit]

External links[edit]