SlideShare a Scribd company logo
WPF, Windows Presentation Foundation A platform for building rich user experiences on Windows  An Architect overview By Shahzad sarwar
Presentation Scope What's covered: XMAL Basic Elements of WPF Architecture Property System / Dependency Property Routed Events Binding System Styling / Templating What’s Not covered: Controls Library Graphics / Multi Media Documents
What is WPF? Next-generation presentation system for building Windows client applications with visually stunning user experiences. Resolution-independent Vector-based rendering engine (advantage of modern graphics hardware) Coverage: Extensible Application Markup Language (XAML), controls, data binding, layout, 2-D and 3-D graphics, animation, styles, templates, documents, media, text, and typography. Types Of Applications: 1. Standalone Applications:  Window class to create windows and dialog boxes  Accessed from menu bars and tool bars. 2. Browser-Hosted Applications: (XAML browser applications (XBAPs)) Create pages (Page) and page functions (PageFunction(T))  Navigate between using hyperlinks (Hyperlink classes).
Tech Analysis Reference:  http:// windowsclient.net/wpf/white-papers/when-to-adopt-wpf.aspx X X         3D Graphics X     X     2D Graphics X   X       Video / Audio X     X     Images X       X   Complex text X     X   X Forms, Controls WPF Direct3D Windows Media Player WinForms + GDI PDF WinForms
The Application Class Additional application-scoped services, including  Creating and managing common application infrastructure. Tracking and interacting with application lifetime. Startup Activated Deactivated ShutdownMode (OnLastWindowClose,OnMainWindowClose, OnExplicitShutdown) SessionEnding (Logging off,Shutting down,Restarting,Hibernating) Exit Retrieving and processing command-line parameters. Example Sharing application-scope properties and resources. Examples in Code Detecting and responding to unhandled exceptions. Example in Code
The Application Class Returning exit codes. Example in Code Managing windows in standalone applications  Tracking and managing navigation  using System.Windows.Navigation;   1.  <Hyperlink  Control <Hyperlink NavigateUri=&quot;UriOfPageToNavigateTo.xaml&quot;> Navigate to Another Page </Hyperlink> 2. Via NavigationService // Instantiate the page to navigate to PageWithNonDefaultConstructor page =  new   PageWithNonDefaultConstructor(&quot;Hello!&quot;); // Navigate to the page, using the NavigationService this .NavigationService.Navigate(page);
The Application Class 3.Programmatic Navigation with a Pack URI // Create a pack URI Uri uri =  new  Uri(&quot;AnotherPage.xaml&quot;, UriKind.Relative); // Get the navigation service that was used to  // navigate to this page, and navigate to  // AnotherPage.xaml this .NavigationService.Navigate(uri); Configuring the Host Window's Title, Width, and Height Fragment Navigation Navigation to a content fragment PageURI # ElementName
Navigation Lifetime Navigating . Occurs when a new navigation is requested. Can be used to cancel the navigation. NavigationProgress . Occurs periodically during a download to provide navigation progress information. Navigated . Occurs when the page has been located and downloaded. NavigationStopped . Occurs when the navigation is stopped (by calling StopLoading), or when a new navigation is requested while a current navigation is in progress. NavigationFailed . Occurs when an error is raised while navigating to the requested content. LoadCompleted . Occurs when content that was navigated to is loaded and parsed, and has begun rendering. FragmentNavigation  Occurs when navigation to a content fragment begins, which happens: Immediately, if the desired fragment is in the current content. After the source content has been loaded, if the desired fragment is in different content.
Navigation Lifetime
Navigation Lifetime Journal /  journal entry( JournalEntry class ) The back stack, the forward stack 1. Declarative mechanisms provided by WPF <Hyperlink Members of the NavigationService  classCommand=&quot;NavigationCommands.BrowseBack&quot;>Back</Hyperlink> 2. Programmatic mechanisms provided by WPF GoBack GoForward CanGoBack CanGoForward Retaining Content State with Navigation History New Page, so data is destroyed, But there is a mechanism to restore state via Journal like navigation history. Custom implementation is also provided System.Windows.Navigation.CustomContentState
Navigation Lifetime Structured Navigation Overview Structured Navigation with PageFunction Other Types of Structured Navigation NavigationWindow Class browser-style navigation into your standalone applications Navigation Hosts Configuring the Application Definition for MSBuild In MSBuild project <ApplicationDefinition Include=&quot;App.xaml&quot; /> Getting the Current Application // Get strongly-typed current application App app = (App)App.Current; Two way to Start Window or Page  1. ByCode void App_Startup(object sender, StartupEventArgs e) { ((NavigationWindow)this.MainWindow).Navigate(new Uri(&quot;HomePage.xaml&quot;, UriKind.Relative)); } 2. StartupUri=&quot;MainWindow.xaml&quot;
WPF Architecture
WPF Architecture More declarative, &quot;property centric&quot; model of programming   System.Threading.DispatcherObject Support for concurrency and threading. messaging system implemented by the dispatcher. Create a CLR object that has STA behavior. Thread affinity: A component uses the identity of the executing thread to store some type of state. OLE 2.0, the clipboard, and Internet Explorer all require single thread affinity (STA) execution. The dispatcher: Basic message dispatching system, with multiple prioritized queues Examples of messages include: Raw input notifications (mouse moved) Framework functions (layout) User commands (execute this method).
WPF Architecture System.Windows.DependencyObject Dependency Properties: To compute the value of a property based on the value of other inputs System properties such as themes and user preference Just-in-time property determination mechanisms such as data binding and animations/storyboards  Multiple-use templates such as resources and styles Values known through parent-child relationships with other elements in the element tree Also For: Self-contained validation Default values Callbacks that monitor changes to other properties A system that can coerce property values based on potentially runtime information.
WPF Architecture System.Windows.Media.Visual Building a tree of visual objects Drawing instructions and metadata about how to render those instructions  (clipping, transformation, etc.). Point of connection between these two subsystems, the managed API and the unmanaged milcore.
WPF Architecture Composition: In User32 and GDI: (Immediate mode clipping system) a clipping bounds outside of which the component isn’t allowed to touch the pixels, and then the component is asked to paint pixels in that box. Good for memory constrained environment. In WPF: &quot;Painter's algorithm&quot; painting model. To render from the back to the front of the display. Each component to paint over the previous component's display. Complex, partially transparent shapes. Better for new type of graphics object.
WPF Architecture System.Windows.UIElement Core subsystems including Layout, Input, and Events. Layout: 1.  A fixed set of layout models (HTML supports three models for layout; flow, absolute, and tables) 2. No model for layout (User32 really only supports absolute positioning) A flexible, extensible layout model, which could be driven by property values rather than imperative logic. A two phase model with Measure and Arrange passes. Measure Phase: To determine how much size it would like to take. A parent element will ask a child to measure several times to determine its optimal position and size. Rule: Size to content. Arrange phase: To allows a parent to position and determine the final size of each child. Input: On a kernel mode device driver. Gets routed to the correct process and thread by involving the Windows kernel and User32. Routed to WPF. WPF raw input message and sent to the dispatcher. Raw input events to be converted to multiple actual events.
WPF Architecture Routing through the element tree. Events are said to &quot;bubble&quot; if they traverse from a target up the tree to the root. Events are said to &quot;tunnel&quot; if that start at the root and traverse down to a target. In the dispatcher for your application you would call TranslateAccelerator which would sniff the input messages in User32 and determine if any matched a registered accelerator. CommandBindings. To define functionality in terms of a command end point – something that implements ICommand. Enable an element to define a mapping between an input gesture (Ctrl+N) and a command (New).
WPF Architecture System.Windows.FrameworkElement A set of policies and customizations on the subsystems introduced in lower layers of WPF. A set of new subsystems Policies: Application layout Direct access to animation through the BeginStoryboard method The data binding subsystem: one or more properties from a given element to be bound to a piece of data Styling Subsystem: Bind a set of properties from a shared definition to one or more instances of an element. System.Windows.Controls.Control Templating allows a control to describe it’s rendering in a parameterized, declarative manner. The implementation of a control provides a data model and interaction model This split between the data model (properties), interaction model (commands and events), and display model (templates) enables complete customization of a control’s look and behavior.
WPF property system A set of services that can be used to extend the functionality of a common language runtime (CLR) property. Dependency property: A property that is backed by the WPF property system. What For? 1. A way to compute the value of a property based on the value of other inputs System properties such as themes and user preference Just-in-time property determination mechanisms such as data binding and animations/storyboards Multiple-use templates such as resources and styles Values known through parent-child relationships with other elements in the element tree. 2. To provide self-contained validation, default values, callbacks that monitor changes to other properties 3. A system that can coerce property values based on potentially runtime information. 4. Derived classes can also change some specific characteristics of an existing property by overriding dependency property metadata, rather than overriding the actual implementation of existing properties or creating new properties.
Common Terms DependencyProperty:  Extend property functionality by providing a type that backs a property  DependencyObject:  The base class that can register and own a dependency property  Dependency property identifier:  A DependencyProperty instance, which is obtained as a return value when registering a dependency property, and then stored as a member of a class. CLR &quot;wrapper&quot;:  The actual get and set implementations for the property public static readonly DependencyProperty IsSpinningProperty =  DependencyProperty.Register( ... ); public bool IsSpinning { get { return (bool)GetValue(IsSpinningProperty); } set { SetValue(IsSpinningProperty, value); } }
Setting Property Values 1. XAML attribute <Button Background=&quot;Red&quot; Content=&quot;Button!&quot;/> 2. Property element syntax. <Button Content=&quot;Button!&quot;> <Button.Background> <ImageBrush ImageSource=&quot;wavy.jpg&quot;/> </Button.Background> </Button> 3. Setting Properties in Code Button myButton =  new  Button(); myButton.Width = 200.0;
Routed events A type of event that can invoke handlers on multiple listeners in an element tree, rather than just on the object that raised the event. CLR event that is backed by an instance of the RoutedEvent class and is processed by the Windows Presentation Foundation (WPF) event system. Routed events are events who navigate up or down the visual tree acording to their RoutingStrategy. Top-level Scenarios for Routed Events Control composition and encapsulation: Eg: Rich content model. Like an image inside of a Button. Singular handler attachment points: To attach the same handler multiple times to process events that could be raised from multiple elements. Example Code Class handling:  Permit a static handler that is defined by the class. (the opportunity to handle an event before any attached instance handlers can. Referencing an event without reflection: Creates a RoutedEvent field as an identifier, which provides a robust event identification technique that does not require static or run-time reflection.
How Routed Events Are Implemented // Register the routed event public   static   readonly  RoutedEvent SelectedEvent =  EventManager.RegisterRoutedEvent( &quot;Selected&quot;, RoutingStrategy.Bubble,  typeof (RoutedEventHandler),  typeof (MyCustomControl));  // .NET wrapper public   event  RoutedEventHandler Selected{  add { AddHandler(SelectedEvent, value); }  remove { RemoveHandler(SelectedEvent, value); }}  // Raise the routed event &quot;selected“ RaiseEvent( new  RoutedEventArgs(MyCustomControl.SelectedEvent));
Routing Strategies: Bubbling:   Event handlers on the event source are invoked.  Then routes to successive parent elements until reaching the element tree root. To report input or state changes from distinct controls or other UI elements. Direct:  Only the source element itself is given the opportunity to invoke handlers in response. Analogous to the &quot;routing&quot; that Windows Forms uses for events. unlike a standard CLR event, direct routed events support class handling. Tunneling: Event handlers at the element tree root are invoked. Then The routed event then travels a route through successive child elements along the route, towards the node element that is the routed event source. Compositing for a control, such that events from composite parts can be deliberately suppressed or replaced by events that are specific to the complete control. Input events provided in WPF often come implemented as a tunneling/bubbling pair. Tunneling events are also sometimes referred to as Preview events, because of a naming convention that is used for the pairs.
Resource StaticResource: A simple way to reuse commonly defined objects and values. Provides a value for a XAML property by substituting the value of an already defined resource. Static resource lookup behavior For the requested key within the resource dictionary defined by the element that sets the property. Traverses the logical tree upward, to the parent element and its resource dictionary. Application resources When: No intention of changing the value of the resource after it is referenced the first time. Not reevaluated based on runtime behaviors such as reloading a page. So some performance benefit. For Value of property that is not on a DependencyObject or a Freezable. Compiled into a DLL, and packaged as part of the application or shared between applications Creating a theme for a custom control, and are defining resources that are used within the themes.
DynamicResource Provides a value for a XAML property by deferring that value to be a run-time reference to a resource. When: The value of the resource depends on conditions that are not known until runtime. Like SystemColors, SystemFonts, or SystemParameters Creating or referencing theme styles for a custom control. To adjust the contents of a ResourceDictionary during an application lifetime. A forward reference may be required The resource might not be used immediately when the page loads. (Static resource references always load from XAML when the page loads; however, a dynamic resource reference does not load until it is actually used.) Applying resources to elements that might be reparented in the logical tree during application lifetime.
Dynamic resource Dynamic resource lookup behavior Within the resource dictionary defined by the element that sets the property. If the element defines a Style property, the Resources dictionary within the Style is checked. If the element defines a Template property, the Resources dictionary within the FrameworkTemplate is checked. Traverses the logical tree upward, to the parent element and its resource dictionary. Application resources Theme resource dictionary System resources Merged Resource Dictionary A way to define the resources portion of a WPF application outside of the compiled XAML application. (Resources can then be shared across applications)
Data Binding Overview The process that establishes a connection between the application UI and business logic. Elements can be bound to data from a variety of data sources in the form of common language runtime (CLR) objects and XML. Features: ContentControls such as Button and ItemsControls such as ListBox and ListView have built-in functionality to enable flexible styling of single data items or collections of data items. Sort, filter, and group views can be generated on top of the data. Basic Data Binding Concepts
Data Binding Overview Direction of the Data Flow What Triggers Source Updates
Animation Overview Animation is an illusion that is created by quickly cycling through a series of images, each slightly different from the last. WPF includes an efficient timing system that is exposed through managed code and Extensible Application Markup Language (XAML) and that is deeply integrated into the WPF framework. For a property to have animation capabilities, it must meet the following three requirements: It must be a dependency property. It must belong to a class that inherits from DependencyObject and implements the IAnimatable interface. There must be a compatible animation type available. Controls such as Button and TabControl, and also Panel and Shape objects inherit from DependencyObject.
Storyboards Overview A Storyboard is a type of container timeline that provides targeting information for the timelines it contains. A Storyboard can contain any type of Timeline, including other container timelines and animations. Storyboard objects enable you to combine timelines that affect a variety of objects and properties into a single timeline tree, making it easy to organize and control complex timing behaviors. How to Apply Animations with a Storyboard To use a Storyboard to organize and apply animations, you add the animations as child timelines of the Storyboard. The Storyboard class provides the Storyboard.TargetName and Storyboard.TargetProperty attached properties. You set these properties on an animation to specify its target object and property. Sample Code
Triggers  Overview Represents a trigger that applies property values or performs actions conditionally. Example: WPF defines properties that correspond to end-user actions, such as the IsMouseOver property that is set to  true  when the user hovers the cursor over a UIElement or the corresponding IsMouseOver property of a ContentElement. Representing end-user actions in property values, along with the  Trigger  element, allows WPF styles to change property values based on those end-user actions, all from within markup. Sample Code
Styles and Templates Overview Styling and templating refer to a suite of features (styles, templates, triggers, and storyboards) that allow an application, document, or user interface (UI) designer to create visually compelling applications and to standardize on a particular look for their product.
Trees in WPF The Logical Tree: Why: Content models can readily iterate over their possible child elements, and so that content models can be extensible. A framework for certain notifications, such as when all elements in the logical tree are loaded. Resource references are resolved by looking upwards through the logical tree for Resources collections on the initial requesting element and then parent elements.
Trees in WPF The Visual Tree The structure of visuals represented by the Visual base class. When you write a template for a control, you are defining or redefining the visual tree that applies for that control. That event routes for a routed event mostly travel along the visual tree, not the logical tree. For Lower-level control over drawing for performance and optimization reasons Sample Code
Attached Events A handler for a particular event to an arbitrary element rather than to an element that actually defines or inherits the event. Sample Code:
Input System Subsystem provides a powerful API for obtaining input from a variety of devices, including the mouse, keyboard, and stylus. Where: UIElement, ContentElement, FrameworkElement, and FrameworkContentElement Plus the Keyboard class and Mouse classes For example: The key down event is associated with the KeyDown and PreviewKeyDown events. Preview events  tunneling down the element tree from the root element to the target element. Bubbling events  bubbling up from the target element to the root element.
Commanding Overview Different from a simple event handler attached to a button or a timer that Commands separate the semantics and the originator of an action from its logic. The semantics of the command are consistent across applications and classes, but the logic of the action is specific to the particular object acted upon. Implement the ICommand. Example Code Four Main Concepts in WPF Commanding The  command : The action to be executed. The  command source: T he object which invokes the command. The  command target:  The object that the command is being executed on.  The  command binding:  The object which maps the command logic to the command.  The Paste command is the command, the MenuItem is the command source, the TextBox is the command target, and the command binding is supplied by the TextBox control. Commands By implementing the ICommand interface. ICommand exposes two methods, Execute, and CanExecute, and an event, CanExecuteChanged. Similar to Routedevents, there are RoutedCommand 
Commanding Overview Command Sources: The object which invokes the command Examples: MenuItem, Button, and KeyGesture. Implement the ICommandSource interface. ICommandSource exposes three properties: Command, CommandTarget, and CommandParameter. CommandBinding: Associates a command with the event handlers that implement the command. The CommandBinding class contains a Command property, and PreviewExecuted, Executed, PreviewCanExecute, and CanExecute events. Example Code Command Library ApplicationCommands, NavigationCommands, MediaCommands, EditingCommands, and the ComponentCommands. Creating Custom Commands Example Code
References: http://msdn.microsoft.com http://windowsclient.net http://www.wpftutorial.net http://joshsmithonwpf.wordpress.com http://idealprogrammer.com http://www.msdev.com http://www.wpfdev.com http:// WPFpedia .com
A soft copy will be available at: http://softarchitect.wordpress.com For Future discussion, join  http://tech.groups.yahoo.com/group/SoftArchitect/
If  you want to master a technology, start teaching it to others.

More Related Content

Similar to WPF Windows Presentation Foundation A detailed overview Version1.2 (20)

PPTX
Chpater1
Engleang Sam
 
PPTX
WPF Deep Dive
Aniruddha Chakrabarti
 
PPT
Presentation wpf
Mahesh Sherkar
 
PPSX
Introduction to WPF
Munish Arora
 
PPT
A Tour of Windows Presentation Foundation (WPF)
ukdpe
 
PPT
Introduction to XAML and WPF
Doncho Minkov
 
PPT
MSDN Unleashed: WPF Demystified
Dave Bost
 
PPS
WPF (Windows Presentation Foundation Unit 01)
Prashanth Shivakumar
 
PPT
Wpf architecture
lostseeker
 
PPT
Wpf architecture
lostseeker
 
PPTX
Yahoo! On Microsoft .NET 3.0 and Microsoft Expression
goodfriday
 
PPT
WPF Applications, It's all about XAML these days
Dave Bost
 
DOCX
unit 4.docx
Sadhana Sreekanth
 
PPT
2 Day - WPF Training by Adil Mughal
Adil Mughal
 
PPT
Re-use Your Skills and Code to Expand the Reach of Your Apps with Silverlight
Frank La Vigne
 
PPTX
XAML: One Language to Rule Them All
Frank La Vigne
 
PPT
Btb017 David
Rohit Ray
 
PDF
WPF - the future of GUI is near
Bartlomiej Filipek
 
PPTX
Windows presentation foundation (wpf) and infragistics
choprasagar
 
PPT
WPF
Vishwa Mohan
 
Chpater1
Engleang Sam
 
WPF Deep Dive
Aniruddha Chakrabarti
 
Presentation wpf
Mahesh Sherkar
 
Introduction to WPF
Munish Arora
 
A Tour of Windows Presentation Foundation (WPF)
ukdpe
 
Introduction to XAML and WPF
Doncho Minkov
 
MSDN Unleashed: WPF Demystified
Dave Bost
 
WPF (Windows Presentation Foundation Unit 01)
Prashanth Shivakumar
 
Wpf architecture
lostseeker
 
Wpf architecture
lostseeker
 
Yahoo! On Microsoft .NET 3.0 and Microsoft Expression
goodfriday
 
WPF Applications, It's all about XAML these days
Dave Bost
 
unit 4.docx
Sadhana Sreekanth
 
2 Day - WPF Training by Adil Mughal
Adil Mughal
 
Re-use Your Skills and Code to Expand the Reach of Your Apps with Silverlight
Frank La Vigne
 
XAML: One Language to Rule Them All
Frank La Vigne
 
Btb017 David
Rohit Ray
 
WPF - the future of GUI is near
Bartlomiej Filipek
 
Windows presentation foundation (wpf) and infragistics
choprasagar
 

More from Shahzad (20)

DOC
Srs sso-version-1.2-stable version-0
Shahzad
 
DOCX
To study pcms pegasus erp cargo management system-release-6 from architectu...
Shahzad
 
PPT
Pakistan management
Shahzad
 
PPS
Corporate lessons
Shahzad
 
DOC
What is future of web with reference to html5 will it devalue current present...
Shahzad
 
DOC
Software architecture to analyze licensing needs for pcms- pegasus cargo ma...
Shahzad
 
DOC
A cross referenced whitepaper on cloud computing
Shahzad
 
DOC
Software architecture case study - why and why not sql server replication
Shahzad
 
PPT
Software Architecture New Features of Visual Studio 2010 / .Net 4.0 - Part 1...
Shahzad
 
PPT
From Windows Presentation Foundation To Silverlight
Shahzad
 
DOC
To Study The Tips Tricks Guidelines Related To Performance Tuning For N Hib...
Shahzad
 
DOC
To Study E T L ( Extract, Transform, Load) Tools Specially S Q L Server I...
Shahzad
 
DOC
To Study E T L ( Extract, Transform, Load) Tools Specially S Q L Server I...
Shahzad
 
DOC
To Analyze Cargo Loading Optimization Algorithm
Shahzad
 
DOC
Asp
Shahzad
 
DOC
Whitepaper To Study Filestream Option In Sql Server
Shahzad
 
DOC
White Paper On ConCurrency For PCMS Application Architecture
Shahzad
 
DOC
Case Study For Replication For PCMS
Shahzad
 
PPT
Data Structure In C#
Shahzad
 
DOC
Software Bugs A Software Architect Point Of View
Shahzad
 
Srs sso-version-1.2-stable version-0
Shahzad
 
To study pcms pegasus erp cargo management system-release-6 from architectu...
Shahzad
 
Pakistan management
Shahzad
 
Corporate lessons
Shahzad
 
What is future of web with reference to html5 will it devalue current present...
Shahzad
 
Software architecture to analyze licensing needs for pcms- pegasus cargo ma...
Shahzad
 
A cross referenced whitepaper on cloud computing
Shahzad
 
Software architecture case study - why and why not sql server replication
Shahzad
 
Software Architecture New Features of Visual Studio 2010 / .Net 4.0 - Part 1...
Shahzad
 
From Windows Presentation Foundation To Silverlight
Shahzad
 
To Study The Tips Tricks Guidelines Related To Performance Tuning For N Hib...
Shahzad
 
To Study E T L ( Extract, Transform, Load) Tools Specially S Q L Server I...
Shahzad
 
To Study E T L ( Extract, Transform, Load) Tools Specially S Q L Server I...
Shahzad
 
To Analyze Cargo Loading Optimization Algorithm
Shahzad
 
Whitepaper To Study Filestream Option In Sql Server
Shahzad
 
White Paper On ConCurrency For PCMS Application Architecture
Shahzad
 
Case Study For Replication For PCMS
Shahzad
 
Data Structure In C#
Shahzad
 
Software Bugs A Software Architect Point Of View
Shahzad
 
Ad

Recently uploaded (20)

PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
Python basic programing language for automation
DanialHabibi2
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PPTX
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
PDF
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
PDF
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
Python basic programing language for automation
DanialHabibi2
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
Ad

WPF Windows Presentation Foundation A detailed overview Version1.2

  • 1. WPF, Windows Presentation Foundation A platform for building rich user experiences on Windows An Architect overview By Shahzad sarwar
  • 2. Presentation Scope What's covered: XMAL Basic Elements of WPF Architecture Property System / Dependency Property Routed Events Binding System Styling / Templating What’s Not covered: Controls Library Graphics / Multi Media Documents
  • 3. What is WPF? Next-generation presentation system for building Windows client applications with visually stunning user experiences. Resolution-independent Vector-based rendering engine (advantage of modern graphics hardware) Coverage: Extensible Application Markup Language (XAML), controls, data binding, layout, 2-D and 3-D graphics, animation, styles, templates, documents, media, text, and typography. Types Of Applications: 1. Standalone Applications: Window class to create windows and dialog boxes Accessed from menu bars and tool bars. 2. Browser-Hosted Applications: (XAML browser applications (XBAPs)) Create pages (Page) and page functions (PageFunction(T))  Navigate between using hyperlinks (Hyperlink classes).
  • 4. Tech Analysis Reference: http:// windowsclient.net/wpf/white-papers/when-to-adopt-wpf.aspx X X         3D Graphics X     X     2D Graphics X   X       Video / Audio X     X     Images X       X   Complex text X     X   X Forms, Controls WPF Direct3D Windows Media Player WinForms + GDI PDF WinForms
  • 5. The Application Class Additional application-scoped services, including Creating and managing common application infrastructure. Tracking and interacting with application lifetime. Startup Activated Deactivated ShutdownMode (OnLastWindowClose,OnMainWindowClose, OnExplicitShutdown) SessionEnding (Logging off,Shutting down,Restarting,Hibernating) Exit Retrieving and processing command-line parameters. Example Sharing application-scope properties and resources. Examples in Code Detecting and responding to unhandled exceptions. Example in Code
  • 6. The Application Class Returning exit codes. Example in Code Managing windows in standalone applications Tracking and managing navigation using System.Windows.Navigation; 1. <Hyperlink Control <Hyperlink NavigateUri=&quot;UriOfPageToNavigateTo.xaml&quot;> Navigate to Another Page </Hyperlink> 2. Via NavigationService // Instantiate the page to navigate to PageWithNonDefaultConstructor page = new PageWithNonDefaultConstructor(&quot;Hello!&quot;); // Navigate to the page, using the NavigationService this .NavigationService.Navigate(page);
  • 7. The Application Class 3.Programmatic Navigation with a Pack URI // Create a pack URI Uri uri = new Uri(&quot;AnotherPage.xaml&quot;, UriKind.Relative); // Get the navigation service that was used to // navigate to this page, and navigate to // AnotherPage.xaml this .NavigationService.Navigate(uri); Configuring the Host Window's Title, Width, and Height Fragment Navigation Navigation to a content fragment PageURI # ElementName
  • 8. Navigation Lifetime Navigating . Occurs when a new navigation is requested. Can be used to cancel the navigation. NavigationProgress . Occurs periodically during a download to provide navigation progress information. Navigated . Occurs when the page has been located and downloaded. NavigationStopped . Occurs when the navigation is stopped (by calling StopLoading), or when a new navigation is requested while a current navigation is in progress. NavigationFailed . Occurs when an error is raised while navigating to the requested content. LoadCompleted . Occurs when content that was navigated to is loaded and parsed, and has begun rendering. FragmentNavigation Occurs when navigation to a content fragment begins, which happens: Immediately, if the desired fragment is in the current content. After the source content has been loaded, if the desired fragment is in different content.
  • 10. Navigation Lifetime Journal / journal entry( JournalEntry class ) The back stack, the forward stack 1. Declarative mechanisms provided by WPF <Hyperlink Members of the NavigationService classCommand=&quot;NavigationCommands.BrowseBack&quot;>Back</Hyperlink> 2. Programmatic mechanisms provided by WPF GoBack GoForward CanGoBack CanGoForward Retaining Content State with Navigation History New Page, so data is destroyed, But there is a mechanism to restore state via Journal like navigation history. Custom implementation is also provided System.Windows.Navigation.CustomContentState
  • 11. Navigation Lifetime Structured Navigation Overview Structured Navigation with PageFunction Other Types of Structured Navigation NavigationWindow Class browser-style navigation into your standalone applications Navigation Hosts Configuring the Application Definition for MSBuild In MSBuild project <ApplicationDefinition Include=&quot;App.xaml&quot; /> Getting the Current Application // Get strongly-typed current application App app = (App)App.Current; Two way to Start Window or Page 1. ByCode void App_Startup(object sender, StartupEventArgs e) { ((NavigationWindow)this.MainWindow).Navigate(new Uri(&quot;HomePage.xaml&quot;, UriKind.Relative)); } 2. StartupUri=&quot;MainWindow.xaml&quot;
  • 13. WPF Architecture More declarative, &quot;property centric&quot; model of programming System.Threading.DispatcherObject Support for concurrency and threading. messaging system implemented by the dispatcher. Create a CLR object that has STA behavior. Thread affinity: A component uses the identity of the executing thread to store some type of state. OLE 2.0, the clipboard, and Internet Explorer all require single thread affinity (STA) execution. The dispatcher: Basic message dispatching system, with multiple prioritized queues Examples of messages include: Raw input notifications (mouse moved) Framework functions (layout) User commands (execute this method).
  • 14. WPF Architecture System.Windows.DependencyObject Dependency Properties: To compute the value of a property based on the value of other inputs System properties such as themes and user preference Just-in-time property determination mechanisms such as data binding and animations/storyboards Multiple-use templates such as resources and styles Values known through parent-child relationships with other elements in the element tree Also For: Self-contained validation Default values Callbacks that monitor changes to other properties A system that can coerce property values based on potentially runtime information.
  • 15. WPF Architecture System.Windows.Media.Visual Building a tree of visual objects Drawing instructions and metadata about how to render those instructions (clipping, transformation, etc.). Point of connection between these two subsystems, the managed API and the unmanaged milcore.
  • 16. WPF Architecture Composition: In User32 and GDI: (Immediate mode clipping system) a clipping bounds outside of which the component isn’t allowed to touch the pixels, and then the component is asked to paint pixels in that box. Good for memory constrained environment. In WPF: &quot;Painter's algorithm&quot; painting model. To render from the back to the front of the display. Each component to paint over the previous component's display. Complex, partially transparent shapes. Better for new type of graphics object.
  • 17. WPF Architecture System.Windows.UIElement Core subsystems including Layout, Input, and Events. Layout: 1. A fixed set of layout models (HTML supports three models for layout; flow, absolute, and tables) 2. No model for layout (User32 really only supports absolute positioning) A flexible, extensible layout model, which could be driven by property values rather than imperative logic. A two phase model with Measure and Arrange passes. Measure Phase: To determine how much size it would like to take. A parent element will ask a child to measure several times to determine its optimal position and size. Rule: Size to content. Arrange phase: To allows a parent to position and determine the final size of each child. Input: On a kernel mode device driver. Gets routed to the correct process and thread by involving the Windows kernel and User32. Routed to WPF. WPF raw input message and sent to the dispatcher. Raw input events to be converted to multiple actual events.
  • 18. WPF Architecture Routing through the element tree. Events are said to &quot;bubble&quot; if they traverse from a target up the tree to the root. Events are said to &quot;tunnel&quot; if that start at the root and traverse down to a target. In the dispatcher for your application you would call TranslateAccelerator which would sniff the input messages in User32 and determine if any matched a registered accelerator. CommandBindings. To define functionality in terms of a command end point – something that implements ICommand. Enable an element to define a mapping between an input gesture (Ctrl+N) and a command (New).
  • 19. WPF Architecture System.Windows.FrameworkElement A set of policies and customizations on the subsystems introduced in lower layers of WPF. A set of new subsystems Policies: Application layout Direct access to animation through the BeginStoryboard method The data binding subsystem: one or more properties from a given element to be bound to a piece of data Styling Subsystem: Bind a set of properties from a shared definition to one or more instances of an element. System.Windows.Controls.Control Templating allows a control to describe it’s rendering in a parameterized, declarative manner. The implementation of a control provides a data model and interaction model This split between the data model (properties), interaction model (commands and events), and display model (templates) enables complete customization of a control’s look and behavior.
  • 20. WPF property system A set of services that can be used to extend the functionality of a common language runtime (CLR) property. Dependency property: A property that is backed by the WPF property system. What For? 1. A way to compute the value of a property based on the value of other inputs System properties such as themes and user preference Just-in-time property determination mechanisms such as data binding and animations/storyboards Multiple-use templates such as resources and styles Values known through parent-child relationships with other elements in the element tree. 2. To provide self-contained validation, default values, callbacks that monitor changes to other properties 3. A system that can coerce property values based on potentially runtime information. 4. Derived classes can also change some specific characteristics of an existing property by overriding dependency property metadata, rather than overriding the actual implementation of existing properties or creating new properties.
  • 21. Common Terms DependencyProperty: Extend property functionality by providing a type that backs a property DependencyObject: The base class that can register and own a dependency property Dependency property identifier: A DependencyProperty instance, which is obtained as a return value when registering a dependency property, and then stored as a member of a class. CLR &quot;wrapper&quot;: The actual get and set implementations for the property public static readonly DependencyProperty IsSpinningProperty = DependencyProperty.Register( ... ); public bool IsSpinning { get { return (bool)GetValue(IsSpinningProperty); } set { SetValue(IsSpinningProperty, value); } }
  • 22. Setting Property Values 1. XAML attribute <Button Background=&quot;Red&quot; Content=&quot;Button!&quot;/> 2. Property element syntax. <Button Content=&quot;Button!&quot;> <Button.Background> <ImageBrush ImageSource=&quot;wavy.jpg&quot;/> </Button.Background> </Button> 3. Setting Properties in Code Button myButton = new Button(); myButton.Width = 200.0;
  • 23. Routed events A type of event that can invoke handlers on multiple listeners in an element tree, rather than just on the object that raised the event. CLR event that is backed by an instance of the RoutedEvent class and is processed by the Windows Presentation Foundation (WPF) event system. Routed events are events who navigate up or down the visual tree acording to their RoutingStrategy. Top-level Scenarios for Routed Events Control composition and encapsulation: Eg: Rich content model. Like an image inside of a Button. Singular handler attachment points: To attach the same handler multiple times to process events that could be raised from multiple elements. Example Code Class handling: Permit a static handler that is defined by the class. (the opportunity to handle an event before any attached instance handlers can. Referencing an event without reflection: Creates a RoutedEvent field as an identifier, which provides a robust event identification technique that does not require static or run-time reflection.
  • 24. How Routed Events Are Implemented // Register the routed event public static readonly RoutedEvent SelectedEvent = EventManager.RegisterRoutedEvent( &quot;Selected&quot;, RoutingStrategy.Bubble, typeof (RoutedEventHandler), typeof (MyCustomControl));  // .NET wrapper public event RoutedEventHandler Selected{ add { AddHandler(SelectedEvent, value); } remove { RemoveHandler(SelectedEvent, value); }}  // Raise the routed event &quot;selected“ RaiseEvent( new RoutedEventArgs(MyCustomControl.SelectedEvent));
  • 25. Routing Strategies: Bubbling: Event handlers on the event source are invoked. Then routes to successive parent elements until reaching the element tree root. To report input or state changes from distinct controls or other UI elements. Direct: Only the source element itself is given the opportunity to invoke handlers in response. Analogous to the &quot;routing&quot; that Windows Forms uses for events. unlike a standard CLR event, direct routed events support class handling. Tunneling: Event handlers at the element tree root are invoked. Then The routed event then travels a route through successive child elements along the route, towards the node element that is the routed event source. Compositing for a control, such that events from composite parts can be deliberately suppressed or replaced by events that are specific to the complete control. Input events provided in WPF often come implemented as a tunneling/bubbling pair. Tunneling events are also sometimes referred to as Preview events, because of a naming convention that is used for the pairs.
  • 26. Resource StaticResource: A simple way to reuse commonly defined objects and values. Provides a value for a XAML property by substituting the value of an already defined resource. Static resource lookup behavior For the requested key within the resource dictionary defined by the element that sets the property. Traverses the logical tree upward, to the parent element and its resource dictionary. Application resources When: No intention of changing the value of the resource after it is referenced the first time. Not reevaluated based on runtime behaviors such as reloading a page. So some performance benefit. For Value of property that is not on a DependencyObject or a Freezable. Compiled into a DLL, and packaged as part of the application or shared between applications Creating a theme for a custom control, and are defining resources that are used within the themes.
  • 27. DynamicResource Provides a value for a XAML property by deferring that value to be a run-time reference to a resource. When: The value of the resource depends on conditions that are not known until runtime. Like SystemColors, SystemFonts, or SystemParameters Creating or referencing theme styles for a custom control. To adjust the contents of a ResourceDictionary during an application lifetime. A forward reference may be required The resource might not be used immediately when the page loads. (Static resource references always load from XAML when the page loads; however, a dynamic resource reference does not load until it is actually used.) Applying resources to elements that might be reparented in the logical tree during application lifetime.
  • 28. Dynamic resource Dynamic resource lookup behavior Within the resource dictionary defined by the element that sets the property. If the element defines a Style property, the Resources dictionary within the Style is checked. If the element defines a Template property, the Resources dictionary within the FrameworkTemplate is checked. Traverses the logical tree upward, to the parent element and its resource dictionary. Application resources Theme resource dictionary System resources Merged Resource Dictionary A way to define the resources portion of a WPF application outside of the compiled XAML application. (Resources can then be shared across applications)
  • 29. Data Binding Overview The process that establishes a connection between the application UI and business logic. Elements can be bound to data from a variety of data sources in the form of common language runtime (CLR) objects and XML. Features: ContentControls such as Button and ItemsControls such as ListBox and ListView have built-in functionality to enable flexible styling of single data items or collections of data items. Sort, filter, and group views can be generated on top of the data. Basic Data Binding Concepts
  • 30. Data Binding Overview Direction of the Data Flow What Triggers Source Updates
  • 31. Animation Overview Animation is an illusion that is created by quickly cycling through a series of images, each slightly different from the last. WPF includes an efficient timing system that is exposed through managed code and Extensible Application Markup Language (XAML) and that is deeply integrated into the WPF framework. For a property to have animation capabilities, it must meet the following three requirements: It must be a dependency property. It must belong to a class that inherits from DependencyObject and implements the IAnimatable interface. There must be a compatible animation type available. Controls such as Button and TabControl, and also Panel and Shape objects inherit from DependencyObject.
  • 32. Storyboards Overview A Storyboard is a type of container timeline that provides targeting information for the timelines it contains. A Storyboard can contain any type of Timeline, including other container timelines and animations. Storyboard objects enable you to combine timelines that affect a variety of objects and properties into a single timeline tree, making it easy to organize and control complex timing behaviors. How to Apply Animations with a Storyboard To use a Storyboard to organize and apply animations, you add the animations as child timelines of the Storyboard. The Storyboard class provides the Storyboard.TargetName and Storyboard.TargetProperty attached properties. You set these properties on an animation to specify its target object and property. Sample Code
  • 33. Triggers Overview Represents a trigger that applies property values or performs actions conditionally. Example: WPF defines properties that correspond to end-user actions, such as the IsMouseOver property that is set to true when the user hovers the cursor over a UIElement or the corresponding IsMouseOver property of a ContentElement. Representing end-user actions in property values, along with the Trigger element, allows WPF styles to change property values based on those end-user actions, all from within markup. Sample Code
  • 34. Styles and Templates Overview Styling and templating refer to a suite of features (styles, templates, triggers, and storyboards) that allow an application, document, or user interface (UI) designer to create visually compelling applications and to standardize on a particular look for their product.
  • 35. Trees in WPF The Logical Tree: Why: Content models can readily iterate over their possible child elements, and so that content models can be extensible. A framework for certain notifications, such as when all elements in the logical tree are loaded. Resource references are resolved by looking upwards through the logical tree for Resources collections on the initial requesting element and then parent elements.
  • 36. Trees in WPF The Visual Tree The structure of visuals represented by the Visual base class. When you write a template for a control, you are defining or redefining the visual tree that applies for that control. That event routes for a routed event mostly travel along the visual tree, not the logical tree. For Lower-level control over drawing for performance and optimization reasons Sample Code
  • 37. Attached Events A handler for a particular event to an arbitrary element rather than to an element that actually defines or inherits the event. Sample Code:
  • 38. Input System Subsystem provides a powerful API for obtaining input from a variety of devices, including the mouse, keyboard, and stylus. Where: UIElement, ContentElement, FrameworkElement, and FrameworkContentElement Plus the Keyboard class and Mouse classes For example: The key down event is associated with the KeyDown and PreviewKeyDown events. Preview events tunneling down the element tree from the root element to the target element. Bubbling events bubbling up from the target element to the root element.
  • 39. Commanding Overview Different from a simple event handler attached to a button or a timer that Commands separate the semantics and the originator of an action from its logic. The semantics of the command are consistent across applications and classes, but the logic of the action is specific to the particular object acted upon. Implement the ICommand. Example Code Four Main Concepts in WPF Commanding The command : The action to be executed. The command source: T he object which invokes the command. The command target: The object that the command is being executed on. The command binding: The object which maps the command logic to the command. The Paste command is the command, the MenuItem is the command source, the TextBox is the command target, and the command binding is supplied by the TextBox control. Commands By implementing the ICommand interface. ICommand exposes two methods, Execute, and CanExecute, and an event, CanExecuteChanged. Similar to Routedevents, there are RoutedCommand 
  • 40. Commanding Overview Command Sources: The object which invokes the command Examples: MenuItem, Button, and KeyGesture. Implement the ICommandSource interface. ICommandSource exposes three properties: Command, CommandTarget, and CommandParameter. CommandBinding: Associates a command with the event handlers that implement the command. The CommandBinding class contains a Command property, and PreviewExecuted, Executed, PreviewCanExecute, and CanExecute events. Example Code Command Library ApplicationCommands, NavigationCommands, MediaCommands, EditingCommands, and the ComponentCommands. Creating Custom Commands Example Code
  • 41. References: http://msdn.microsoft.com http://windowsclient.net http://www.wpftutorial.net http://joshsmithonwpf.wordpress.com http://idealprogrammer.com http://www.msdev.com http://www.wpfdev.com http:// WPFpedia .com
  • 42. A soft copy will be available at: http://softarchitect.wordpress.com For Future discussion, join http://tech.groups.yahoo.com/group/SoftArchitect/
  • 43. If you want to master a technology, start teaching it to others.