SlideShare a Scribd company logo
XAML Concepts Dependency Properties, XAML Trees, Routing Doncho Minkov Telerik School Academy schoolacademy.telerik.com   Technical Trainer http://www.minkov.it
Table of Contents Dependency Objects Dependency Properties Attached Properties Trees in XAML Trees in WPF Trees in Silverlight VisualTreeHelper LogicalTreeHelper
Table of Contents (2) Routing Bubbling Tunneling Commanding in XAML Built-in commands ICommand The Relay Command
Dependency Object
Dependency Object The  DependencyObject Represents an object that participates in the dependency property system Enables  WPF  /  SL   property   system  services The property system's functions: Compute the values of properties Provide system notification about values that have changed DependencyObject  as a base class enables objects to use Dependency Properties
Dependency Object (2) DependencyObject  has the following Get ,  Set , and  Clear  methods for values of any dependency properties Metadata, coerce value support, property changed notification Override callbacks for dependency properties or attached properties DependencyObject  class facilitates the  per-owner property metadata for a dependency property
Dependency Properties Dependencies
Dependency Properties Silverlight and WPF provide a set of services that can be used to extend the functionality of a CLR property Collectively, these services are typically referred to as the Silverlight / WPF property system Dependency Property is  A property that is backed by the SL/WPF property system
Dependency Properties (2) Dependency properties are typically exposed as CLR properties At a basic level, you could interact with these properties directly  May never find out they are dependency properties Better to know if a property is Dependency or CLR Can use the advantages of the dependency properties
Dependency Properties (3) The purpose of dependency properties is to provide a way to compute the value of a property based on the value of other inputs Can be implemented to provide callbacks to propagate changes to other properties
Dependency Properties Live Demo
Attached Properties How to set properties from another place
Attached Properties An attached property is intended to be used as a type of global property that is settable on any object In WPF and Silverlight attached properties are defined as dependency properties  They don't have the wrapper property Examples of Attached Properties Grid.Row, Grid.Column, Grid.RowSpan Canvas.Top, Canvas.Left, Canvas.Bottom etc.
Attached Properties Live Demo
Custom Dependency Properties How to make our own Dependency Properties?
Custom Dependency Properties The first thing to do is to register the Dependency Property Need registration due to the Property System In most of the cases we need a dependency property on a  UserControl public static readonly  DependencyProperty ScrollValueProperty = DependencyProperty.Register( "ScrollValue",  typeof(double),  typeof(UserControl), null); Dependency Property's instance is always readonly The name of the Dependency Property Registration to the Property System
Dependency Property Registration Two Register Methods: Register(String, Type, Type) Registers a dependency property with the specified property name, property type, and owner type Register(String, Type, Type, PropertyMetadata) Add Property metadata Default value or Callback for Property changes
Dependency Property Wrapper After the registration of the  Dependency Property  it needs wrapper Used to make it look like plain old CLR Property DependencyObject  has two methods used for the wrapping of dependency properties SetValue(DependenyProperty, value) GetValue(DependenyProperty) public double ScrollValue { get { return (double)GetValue(ScrollValueProperty); } set { SetValue(ScrollValueProperty , value); } }
Custom Attached Properties How to make attached properties?
Custom Attached Properties The registration of attached properties is a little different private static void OnPropertyChanged(…) { … } public static Thickness GetMargin(DependencyObject obj) { return (Thickness)obj.GetValue(MarginProperty); } public static void SetMargin(DependencyObject obj, Thickness val) { obj.SetValue(MarginProperty, val); } public static readonly DependencyProperty MarginProperty = DependencyProperty.RegisterAttached("Margin", typeof(Thickness), typeof(ContentMargin),  new FrameworkPropertyMetadata(default(Thickness),  new PropertyChangedCallback(OnPropertyChanged)));
Custom Dependency and Attached Properties Live Demo
Trees in WPF Visual and Logical
Trees in WPF and Silverlight WPF and Silverlight use a hierarchical system that organizes the elements and components Developers can manipulate the nodes directly Affect the rendering or behavior of an application Two such trees exist in WPF  Logical tree and Visual tree One kind of tree in Silverlight Visual Tree
Trees in WPF and Silverlight Elements of a XAML are hierarchically related This relation is called the  LogicalTree The template of one element consists of multiple visual elements This tree is called the  VisualTree WPF differs between those two trees Some problems are solved only by the logical elements  For others you want all elements
Trees in WPF Visual and Logical
The Trees in WPF WPF supports two kinds of Trees for rendering Logical Tree Describes the structure of control elements Visual Tree Describes the structure of Visual elements Sometimes both trees are used the same way
Object Tree The Object Tree Window Border AdornedDecoration AdornedLayer ContentPresenter StackPanel Label Border ContentPresenter TextBlock Button Border ContentPresenter TextBlock
Logical Tree The Logical Tree Window Border AdornedDecoration AdornedLayer ContentPresenter StackPanel Label Border ContentPresenter TextBlock Button Border ContentPresenter TextBlock
Visual Tree The Visual Tree Window Border AdornedDecoration AdornedLayer ContentPresenter StackPanel Label Border ContentPresenter TextBlock Button Border ContentPresenter TextBlock
Why Two Kinds of Trees? A WPF control consists of multiple, more primitive controls A button consists of  A border, a rectangle and a content presenter. These controls are visual children of the button When WPF renders the button The element itself has no appearance It iterates through the visual tree and renders the visual children of it
Why Two Kinds of Trees? (2) Sometimes you are not interested in the borders and rectangles of a controls' template You want a more robust tree that only contains the "real" controls  Not all the template parts And that is the eligibility for the logical tree
The Logical Tree The logical tree describes the relations between elements of the user interface The logical tree is responsible for: Inherit  DependencyProperty  values Resolving  DynamicResources  references Looking up element names for bindings Forwarding  RoutedEvents
The Visual Tree Contains all logical elements Including all visual elements of the template of each element The visual tree is responsible for: Rendering visual elements Propagate element opacity Propagate  Layout-  and  RenderTransforms Propagate the  IsEnabled  property Do Hit-Testing RelativeSource (FindAncestor)
Traversing Through  Trees in WPF VisualTreeHelper and Logical Tree Helper
LogicalTreeHelper and VisualTreeHelper Help a lot when traversing the WPF Trees Key Functionality: GetParrent(Dependency Object) Gets the logical parent of the current element GetChildren(Dependency Object) GetOpacity(Dependency Object) Etc…
Traversing Through Trees in WPF Live Demo
Visual Tree in Silverlight Just the Visual
The Visual Tree in Silverlight The same as in WPF Works exactly as in WPF May be used to find the first ancestor of concrete type i.e. the first  Grid  or  StackPanel public static T FindUpVisualTree<T> (DependencyObject initial) where T : DependencyObject { DependencyObject current = initial; while (current != null &&  current.GetType() != typeof(T)) { current = VisualTreeHelper.GetParent(current); } return current as T;  }
Visual Tree in Silverlight Live Demo
Routed Events in WPF/Silverlight Bubbling and Tunneling
Routed Events What is a routed event? A type of event that can invoke handlers on multiple listeners in an element tree Rather than just on the object that raised it The event route can travel in one of two directions Depending on the event definition Generally the route travels from the source element and then &quot;bubbles&quot; upward through the element tree
Types of Routed Events Three types of routed events in WPF and SL Bubbling Event handlers on the event source are invoked Then routes to successive parent elements until reaching the element tree root Most routed events use bubbling routing strategy Direct Only the source element itself is given the opportunity to invoke handlers in response
Types of Routed Events (2) Three types of routed events in WPF and SL Tunneling Event handlers at the tree root are invoked first Then travels down the object tree to the node that is the source of the event The element that raised the routed event Not supported in Silverlight Available as Preview events PreviewClick
Routed Events Example Tunneling Window Grid StackPanel TextBlock PreviewMouseLeftButtonDown  Event is raised
Routed Events Example Window Grid StackPanel TextBlock Bubbling MouseLeftButtonDown  Event is raised
Routed Events in WPF/Silverlight Live Demo
Commands in .NET
WPF Commands Commanding is an input mechanism in WPF Provides input handling at a more semantic level than device input Examples of commands are the  Copy ,  Cut , and  Paste  operations
WPF Commands (2) Commands have several purposes Separate the semantics and the objects that invoke a command from the logic that executes the command Allows for multiple and disparate sources to invoke the same command logic Allows the command logic to be customized for different targets
WPF Commands Commands can be used to indicate whether an action is available Example: when trying to cut something, the user should first select something To indicate whether an action is possible  Implement the  CanExecute   method A button can subscribe to the  CanExecuteChanged  event Disabled if  CanExecute  returns false  Enabled if  CanExecute  returns true.
The Four Main Concepts in WPF Commanding The routed command model in WPF consists of four main concepts Command The action to be executed CommandSource The object that invokes the command CommandTarget The object that the command is executed on CommandBinding The object that maps command logic to command
Four Main Concepts in WPF Commanding Example <Menu> <MenuItem Command=&quot;Copy&quot; CommandTarget=&quot;{Binding ElementName=textBoxText}&quot; /> <MenuItem Command=&quot;Paste&quot; CommandTarget=&quot;{Binding ElementName=mainTextBox}&quot; /> </Menu> <TextBox Name=&quot;mainTextBox&quot;/> <TextBox Name=&quot;textBoxText&quot;> Some Text in a Text Box </TextBox>
Commands in .NET Live Demo
The ICommand Interface How to implement our own Commands
ICommand Interface The  ICommand  interface public bool CanExecute(object parameter); public event EventHandler CanExecuteChanged; public void Execute(object parameter); Determines whether the  command can be executed When changes of the CanExecute state occur Called to invoke the command
Implementation Command Example Lets implement a  Command  to show the selected text in a  TextBox class MessagePopCommand : ICommand { public bool CanExecute(object parameter) { if (parameter == null) { return false; } return !string.IsNullOrEmpty(parameter.ToString()); } public event EventHandler CanExecuteChanged; public void Execute(object parameter) { MessageBox.Show(parameter.ToString()); } }
Implementing Command Example We need to make an instance of the  Command  in the code behind The  XAML  file: <TextBox Name=&quot;TextBoxToShow&quot;>text</TextBox> <Button  Content=&quot;Click Me!&quot;  CommandParameter=&quot;{Binding ElementName=TextBoxToShow,  Path=Text}&quot; Command=&quot;{Binding MessageCommand}&quot;/> In the  Code   Behind  file: private ICommand messageCommand; public ICommand MessageCommand { get { return this.messageCommand; } }
How Does it Work? When binding the command of the button to a specific command instance, the  CanExecute  method is invoked If it returns  false  the button is  disabled If  true  is returned the button is  enabled A known problem The order of the  Command   and  CommandParameter   properties matters! The XAML parser works from left to right  The paramerters must be known before binding
The ICommand Interface Live Implementation
Better Commanding Even better than Custom Commands
Better Commanding Most of the times it is not necessary to implement  ICommand   class for every distinct command Since in most of the cases the  ConcreteCommand  has the same interface Can we implement a command and give different behavior then instantiating? Of course – use the so called  RelayCommand
The RelayCommand What is a relay command A command which is given an behavior during instantiating Both  CanExecute  and  Execute  methods ICommand someCommand; public MyWindow() { this.someCommand =  new RelayCommand(ExecuteMethod,CanExecuteMethod); } public void ExecuteMethod(object parameter) {…} public bool CanExecuteMethod(object parameter) {…}
Better Commanding Live Demo
What's the Point of Commands?! Why the hell we need Commands?
The Point of Commands The answer is simple: The Commands can execute without the knowledge of who wants to execute them Commands are: Easily implemented Easily extended Easily replaceable A way to change an object without knowledge of who wants to change it Fundamental part of the MVVM pattern
XAML Concepts
Exercises Extend the VideoPlayer Control from the example: Add a slider that slides with the video length Add a slider that changes the volume Add buttons for Play, Pause, Stop Add key events for volume UP/DOWN Add key events to jump 5 seconds forward/backward in the video

More Related Content

ODP
Elasticsearch for beginners
PDF
jQuery for beginners
PPTX
Object modeling
PPT
Form validation client side
PPT
CORBA Basic and Deployment of CORBA
PPTX
XML, DTD & XSD Overview
PDF
Lecture 01 introduction to compiler
PPTX
Ado.Net Tutorial
Elasticsearch for beginners
jQuery for beginners
Object modeling
Form validation client side
CORBA Basic and Deployment of CORBA
XML, DTD & XSD Overview
Lecture 01 introduction to compiler
Ado.Net Tutorial

What's hot (20)

PDF
阿里CDN技术揭秘
PDF
Bases de datos con PHP y Mysqli
PPT
Java Servlets
PDF
Responsive Web Design with HTML5 and CSS3
PPTX
Web technologies: HTTP
PPTX
Introduction to SASS
PDF
Fundamental JavaScript [UTC, March 2014]
PPT
Mvc architecture
PDF
PHPデプロイツールの世界
PPTX
PDF
P code
PPT
Servlet life cycle
PDF
Operating system Describe the actions taken by a kernel to context-s.pdf
PPTX
About Best friends - HTML, CSS and JS
PDF
Apache Solr Workshop
PDF
Creating modern java web applications based on struts2 and angularjs
PPTX
THE PACKAGES CONCEPT IN JAVA PROGRAMMING.pptx
PDF
The Factorization Machines algorithm for building recommendation system - Paw...
PPTX
Entity relationship modeling
PPTX
CS8651 Internet Programming - Basics of HTML, HTML5, CSS
阿里CDN技术揭秘
Bases de datos con PHP y Mysqli
Java Servlets
Responsive Web Design with HTML5 and CSS3
Web technologies: HTTP
Introduction to SASS
Fundamental JavaScript [UTC, March 2014]
Mvc architecture
PHPデプロイツールの世界
P code
Servlet life cycle
Operating system Describe the actions taken by a kernel to context-s.pdf
About Best friends - HTML, CSS and JS
Apache Solr Workshop
Creating modern java web applications based on struts2 and angularjs
THE PACKAGES CONCEPT IN JAVA PROGRAMMING.pptx
The Factorization Machines algorithm for building recommendation system - Paw...
Entity relationship modeling
CS8651 Internet Programming - Basics of HTML, HTML5, CSS
Ad

Viewers also liked (20)

PPT
An Introduction to WPF
PPT
Slice and Dice
PPT
WPF and Databases
PPT
PPT
Complex Data Binding
PDF
Data Access with ADO.Net
PPT
WPF Controls
PPT
CSS Presentation
PPT
WPF Templating and Styling
PPT
Model View ViewModel
PDF
Web Design Concepts
PPT
Web design Tools
PPTX
WPF For Beginners - Learn in 3 days
PPT
Simple Data Binding
PPT
Introduction to XAML and WPF
PPT
Ado.net
PPT
PPT
ASP.NET 09 - ADO.NET
PPT
For Beginers - ADO.Net
PPTX
ADO.NET -database connection
An Introduction to WPF
Slice and Dice
WPF and Databases
Complex Data Binding
Data Access with ADO.Net
WPF Controls
CSS Presentation
WPF Templating and Styling
Model View ViewModel
Web Design Concepts
Web design Tools
WPF For Beginners - Learn in 3 days
Simple Data Binding
Introduction to XAML and WPF
Ado.net
ASP.NET 09 - ADO.NET
For Beginers - ADO.Net
ADO.NET -database connection
Ad

Similar to WPF Concepts (20)

PPT
WPF Fundamentals
PPT
Presentation wpf
PDF
WPF Intro
PPTX
Windows presentation foundation (wpf) and infragistics
PPT
Presentation wpf
PPT
WPF Line of Business Control Templates Styles
PPT
Wpf from David Kossoglyad
PPTX
WPF Deep Dive
PPTX
Windows phone and azure
PPTX
WPF - Controls &amp; Data
PPT
2 Day - WPF Training by Adil Mughal
PDF
WPF L02-Graphics, Binding and Animation
PDF
Wpf Introduction
PPTX
Introduction to XAML and its features
PPT
An Introduction To Silverlight
PPTX
Silverlight Developer Introduction
PPTX
Wpf-Xaml And Layout Basics
PPT
A Tour of Windows Presentation Foundation (WPF)
PPTX
The Magic of WPF & MVVM
PPTX
Chpater1
WPF Fundamentals
Presentation wpf
WPF Intro
Windows presentation foundation (wpf) and infragistics
Presentation wpf
WPF Line of Business Control Templates Styles
Wpf from David Kossoglyad
WPF Deep Dive
Windows phone and azure
WPF - Controls &amp; Data
2 Day - WPF Training by Adil Mughal
WPF L02-Graphics, Binding and Animation
Wpf Introduction
Introduction to XAML and its features
An Introduction To Silverlight
Silverlight Developer Introduction
Wpf-Xaml And Layout Basics
A Tour of Windows Presentation Foundation (WPF)
The Magic of WPF & MVVM
Chpater1

More from Doncho Minkov (17)

PPT
HTML 5 Tables and Forms
PPT
CSS Overview
PPT
CSS Layout
PPT
Adobe Photoshop
PPT
WPF Layout Containers
PPT
WPF Graphics and Animations
PPT
Introduction to Cross-platform Mobile Development Course
PPT
HTML Fundamentals
PPT
Tables and Forms in HTML
PPT
PPT
CSS Part I
PPT
CSS Part II
PPT
PPT
Workshop Usability
PPT
JavaScript
PPT
JavaScript OOP
PPT
jQuery Fundamentals
HTML 5 Tables and Forms
CSS Overview
CSS Layout
Adobe Photoshop
WPF Layout Containers
WPF Graphics and Animations
Introduction to Cross-platform Mobile Development Course
HTML Fundamentals
Tables and Forms in HTML
CSS Part I
CSS Part II
Workshop Usability
JavaScript
JavaScript OOP
jQuery Fundamentals

Recently uploaded (20)

PDF
How to Get Funding for Your Trucking Business
PDF
pdfcoffee.com-opt-b1plus-sb-answers.pdfvi
PPTX
AI-assistance in Knowledge Collection and Curation supporting Safe and Sustai...
PPTX
5 Stages of group development guide.pptx
PDF
Nidhal Samdaie CV - International Business Consultant
PPTX
Amazon (Business Studies) management studies
PDF
How to Get Business Funding for Small Business Fast
PPTX
Probability Distribution, binomial distribution, poisson distribution
PPTX
New Microsoft PowerPoint Presentation - Copy.pptx
PDF
WRN_Investor_Presentation_August 2025.pdf
PDF
Roadmap Map-digital Banking feature MB,IB,AB
PDF
Types of control:Qualitative vs Quantitative
PDF
Business model innovation report 2022.pdf
PDF
20250805_A. Stotz All Weather Strategy - Performance review July 2025.pdf
PDF
SIMNET Inc – 2023’s Most Trusted IT Services & Solution Provider
PDF
Reconciliation AND MEMORANDUM RECONCILATION
PDF
DOC-20250806-WA0002._20250806_112011_0000.pdf
PDF
Outsourced Audit & Assurance in USA Why Globus Finanza is Your Trusted Choice
PDF
IFRS Notes in your pocket for study all the time
PPTX
The Marketing Journey - Tracey Phillips - Marketing Matters 7-2025.pptx
How to Get Funding for Your Trucking Business
pdfcoffee.com-opt-b1plus-sb-answers.pdfvi
AI-assistance in Knowledge Collection and Curation supporting Safe and Sustai...
5 Stages of group development guide.pptx
Nidhal Samdaie CV - International Business Consultant
Amazon (Business Studies) management studies
How to Get Business Funding for Small Business Fast
Probability Distribution, binomial distribution, poisson distribution
New Microsoft PowerPoint Presentation - Copy.pptx
WRN_Investor_Presentation_August 2025.pdf
Roadmap Map-digital Banking feature MB,IB,AB
Types of control:Qualitative vs Quantitative
Business model innovation report 2022.pdf
20250805_A. Stotz All Weather Strategy - Performance review July 2025.pdf
SIMNET Inc – 2023’s Most Trusted IT Services & Solution Provider
Reconciliation AND MEMORANDUM RECONCILATION
DOC-20250806-WA0002._20250806_112011_0000.pdf
Outsourced Audit & Assurance in USA Why Globus Finanza is Your Trusted Choice
IFRS Notes in your pocket for study all the time
The Marketing Journey - Tracey Phillips - Marketing Matters 7-2025.pptx

WPF Concepts

  • 1. XAML Concepts Dependency Properties, XAML Trees, Routing Doncho Minkov Telerik School Academy schoolacademy.telerik.com Technical Trainer http://www.minkov.it
  • 2. Table of Contents Dependency Objects Dependency Properties Attached Properties Trees in XAML Trees in WPF Trees in Silverlight VisualTreeHelper LogicalTreeHelper
  • 3. Table of Contents (2) Routing Bubbling Tunneling Commanding in XAML Built-in commands ICommand The Relay Command
  • 5. Dependency Object The DependencyObject Represents an object that participates in the dependency property system Enables WPF / SL property system services The property system's functions: Compute the values of properties Provide system notification about values that have changed DependencyObject as a base class enables objects to use Dependency Properties
  • 6. Dependency Object (2) DependencyObject has the following Get , Set , and Clear methods for values of any dependency properties Metadata, coerce value support, property changed notification Override callbacks for dependency properties or attached properties DependencyObject class facilitates the per-owner property metadata for a dependency property
  • 8. Dependency Properties Silverlight and WPF provide a set of services that can be used to extend the functionality of a CLR property Collectively, these services are typically referred to as the Silverlight / WPF property system Dependency Property is A property that is backed by the SL/WPF property system
  • 9. Dependency Properties (2) Dependency properties are typically exposed as CLR properties At a basic level, you could interact with these properties directly May never find out they are dependency properties Better to know if a property is Dependency or CLR Can use the advantages of the dependency properties
  • 10. Dependency Properties (3) The purpose of dependency properties is to provide a way to compute the value of a property based on the value of other inputs Can be implemented to provide callbacks to propagate changes to other properties
  • 12. Attached Properties How to set properties from another place
  • 13. Attached Properties An attached property is intended to be used as a type of global property that is settable on any object In WPF and Silverlight attached properties are defined as dependency properties They don't have the wrapper property Examples of Attached Properties Grid.Row, Grid.Column, Grid.RowSpan Canvas.Top, Canvas.Left, Canvas.Bottom etc.
  • 15. Custom Dependency Properties How to make our own Dependency Properties?
  • 16. Custom Dependency Properties The first thing to do is to register the Dependency Property Need registration due to the Property System In most of the cases we need a dependency property on a UserControl public static readonly DependencyProperty ScrollValueProperty = DependencyProperty.Register( &quot;ScrollValue&quot;, typeof(double), typeof(UserControl), null); Dependency Property's instance is always readonly The name of the Dependency Property Registration to the Property System
  • 17. Dependency Property Registration Two Register Methods: Register(String, Type, Type) Registers a dependency property with the specified property name, property type, and owner type Register(String, Type, Type, PropertyMetadata) Add Property metadata Default value or Callback for Property changes
  • 18. Dependency Property Wrapper After the registration of the Dependency Property it needs wrapper Used to make it look like plain old CLR Property DependencyObject has two methods used for the wrapping of dependency properties SetValue(DependenyProperty, value) GetValue(DependenyProperty) public double ScrollValue { get { return (double)GetValue(ScrollValueProperty); } set { SetValue(ScrollValueProperty , value); } }
  • 19. Custom Attached Properties How to make attached properties?
  • 20. Custom Attached Properties The registration of attached properties is a little different private static void OnPropertyChanged(…) { … } public static Thickness GetMargin(DependencyObject obj) { return (Thickness)obj.GetValue(MarginProperty); } public static void SetMargin(DependencyObject obj, Thickness val) { obj.SetValue(MarginProperty, val); } public static readonly DependencyProperty MarginProperty = DependencyProperty.RegisterAttached(&quot;Margin&quot;, typeof(Thickness), typeof(ContentMargin), new FrameworkPropertyMetadata(default(Thickness), new PropertyChangedCallback(OnPropertyChanged)));
  • 21. Custom Dependency and Attached Properties Live Demo
  • 22. Trees in WPF Visual and Logical
  • 23. Trees in WPF and Silverlight WPF and Silverlight use a hierarchical system that organizes the elements and components Developers can manipulate the nodes directly Affect the rendering or behavior of an application Two such trees exist in WPF Logical tree and Visual tree One kind of tree in Silverlight Visual Tree
  • 24. Trees in WPF and Silverlight Elements of a XAML are hierarchically related This relation is called the LogicalTree The template of one element consists of multiple visual elements This tree is called the VisualTree WPF differs between those two trees Some problems are solved only by the logical elements For others you want all elements
  • 25. Trees in WPF Visual and Logical
  • 26. The Trees in WPF WPF supports two kinds of Trees for rendering Logical Tree Describes the structure of control elements Visual Tree Describes the structure of Visual elements Sometimes both trees are used the same way
  • 27. Object Tree The Object Tree Window Border AdornedDecoration AdornedLayer ContentPresenter StackPanel Label Border ContentPresenter TextBlock Button Border ContentPresenter TextBlock
  • 28. Logical Tree The Logical Tree Window Border AdornedDecoration AdornedLayer ContentPresenter StackPanel Label Border ContentPresenter TextBlock Button Border ContentPresenter TextBlock
  • 29. Visual Tree The Visual Tree Window Border AdornedDecoration AdornedLayer ContentPresenter StackPanel Label Border ContentPresenter TextBlock Button Border ContentPresenter TextBlock
  • 30. Why Two Kinds of Trees? A WPF control consists of multiple, more primitive controls A button consists of A border, a rectangle and a content presenter. These controls are visual children of the button When WPF renders the button The element itself has no appearance It iterates through the visual tree and renders the visual children of it
  • 31. Why Two Kinds of Trees? (2) Sometimes you are not interested in the borders and rectangles of a controls' template You want a more robust tree that only contains the &quot;real&quot; controls Not all the template parts And that is the eligibility for the logical tree
  • 32. The Logical Tree The logical tree describes the relations between elements of the user interface The logical tree is responsible for: Inherit DependencyProperty values Resolving DynamicResources references Looking up element names for bindings Forwarding RoutedEvents
  • 33. The Visual Tree Contains all logical elements Including all visual elements of the template of each element The visual tree is responsible for: Rendering visual elements Propagate element opacity Propagate Layout- and RenderTransforms Propagate the IsEnabled property Do Hit-Testing RelativeSource (FindAncestor)
  • 34. Traversing Through Trees in WPF VisualTreeHelper and Logical Tree Helper
  • 35. LogicalTreeHelper and VisualTreeHelper Help a lot when traversing the WPF Trees Key Functionality: GetParrent(Dependency Object) Gets the logical parent of the current element GetChildren(Dependency Object) GetOpacity(Dependency Object) Etc…
  • 36. Traversing Through Trees in WPF Live Demo
  • 37. Visual Tree in Silverlight Just the Visual
  • 38. The Visual Tree in Silverlight The same as in WPF Works exactly as in WPF May be used to find the first ancestor of concrete type i.e. the first Grid or StackPanel public static T FindUpVisualTree<T> (DependencyObject initial) where T : DependencyObject { DependencyObject current = initial; while (current != null && current.GetType() != typeof(T)) { current = VisualTreeHelper.GetParent(current); } return current as T; }
  • 39. Visual Tree in Silverlight Live Demo
  • 40. Routed Events in WPF/Silverlight Bubbling and Tunneling
  • 41. Routed Events What is a routed event? A type of event that can invoke handlers on multiple listeners in an element tree Rather than just on the object that raised it The event route can travel in one of two directions Depending on the event definition Generally the route travels from the source element and then &quot;bubbles&quot; upward through the element tree
  • 42. Types of Routed Events Three types of routed events in WPF and SL Bubbling Event handlers on the event source are invoked Then routes to successive parent elements until reaching the element tree root Most routed events use bubbling routing strategy Direct Only the source element itself is given the opportunity to invoke handlers in response
  • 43. Types of Routed Events (2) Three types of routed events in WPF and SL Tunneling Event handlers at the tree root are invoked first Then travels down the object tree to the node that is the source of the event The element that raised the routed event Not supported in Silverlight Available as Preview events PreviewClick
  • 44. Routed Events Example Tunneling Window Grid StackPanel TextBlock PreviewMouseLeftButtonDown Event is raised
  • 45. Routed Events Example Window Grid StackPanel TextBlock Bubbling MouseLeftButtonDown Event is raised
  • 46. Routed Events in WPF/Silverlight Live Demo
  • 48. WPF Commands Commanding is an input mechanism in WPF Provides input handling at a more semantic level than device input Examples of commands are the Copy , Cut , and Paste operations
  • 49. WPF Commands (2) Commands have several purposes Separate the semantics and the objects that invoke a command from the logic that executes the command Allows for multiple and disparate sources to invoke the same command logic Allows the command logic to be customized for different targets
  • 50. WPF Commands Commands can be used to indicate whether an action is available Example: when trying to cut something, the user should first select something To indicate whether an action is possible Implement the CanExecute method A button can subscribe to the CanExecuteChanged event Disabled if CanExecute returns false Enabled if CanExecute returns true.
  • 51. The Four Main Concepts in WPF Commanding The routed command model in WPF consists of four main concepts Command The action to be executed CommandSource The object that invokes the command CommandTarget The object that the command is executed on CommandBinding The object that maps command logic to command
  • 52. Four Main Concepts in WPF Commanding Example <Menu> <MenuItem Command=&quot;Copy&quot; CommandTarget=&quot;{Binding ElementName=textBoxText}&quot; /> <MenuItem Command=&quot;Paste&quot; CommandTarget=&quot;{Binding ElementName=mainTextBox}&quot; /> </Menu> <TextBox Name=&quot;mainTextBox&quot;/> <TextBox Name=&quot;textBoxText&quot;> Some Text in a Text Box </TextBox>
  • 53. Commands in .NET Live Demo
  • 54. The ICommand Interface How to implement our own Commands
  • 55. ICommand Interface The ICommand interface public bool CanExecute(object parameter); public event EventHandler CanExecuteChanged; public void Execute(object parameter); Determines whether the command can be executed When changes of the CanExecute state occur Called to invoke the command
  • 56. Implementation Command Example Lets implement a Command to show the selected text in a TextBox class MessagePopCommand : ICommand { public bool CanExecute(object parameter) { if (parameter == null) { return false; } return !string.IsNullOrEmpty(parameter.ToString()); } public event EventHandler CanExecuteChanged; public void Execute(object parameter) { MessageBox.Show(parameter.ToString()); } }
  • 57. Implementing Command Example We need to make an instance of the Command in the code behind The XAML file: <TextBox Name=&quot;TextBoxToShow&quot;>text</TextBox> <Button Content=&quot;Click Me!&quot; CommandParameter=&quot;{Binding ElementName=TextBoxToShow, Path=Text}&quot; Command=&quot;{Binding MessageCommand}&quot;/> In the Code Behind file: private ICommand messageCommand; public ICommand MessageCommand { get { return this.messageCommand; } }
  • 58. How Does it Work? When binding the command of the button to a specific command instance, the CanExecute method is invoked If it returns false the button is disabled If true is returned the button is enabled A known problem The order of the Command and CommandParameter properties matters! The XAML parser works from left to right The paramerters must be known before binding
  • 59. The ICommand Interface Live Implementation
  • 60. Better Commanding Even better than Custom Commands
  • 61. Better Commanding Most of the times it is not necessary to implement ICommand class for every distinct command Since in most of the cases the ConcreteCommand has the same interface Can we implement a command and give different behavior then instantiating? Of course – use the so called RelayCommand
  • 62. The RelayCommand What is a relay command A command which is given an behavior during instantiating Both CanExecute and Execute methods ICommand someCommand; public MyWindow() { this.someCommand = new RelayCommand(ExecuteMethod,CanExecuteMethod); } public void ExecuteMethod(object parameter) {…} public bool CanExecuteMethod(object parameter) {…}
  • 64. What's the Point of Commands?! Why the hell we need Commands?
  • 65. The Point of Commands The answer is simple: The Commands can execute without the knowledge of who wants to execute them Commands are: Easily implemented Easily extended Easily replaceable A way to change an object without knowledge of who wants to change it Fundamental part of the MVVM pattern
  • 67. Exercises Extend the VideoPlayer Control from the example: Add a slider that slides with the video length Add a slider that changes the volume Add buttons for Play, Pause, Stop Add key events for volume UP/DOWN Add key events to jump 5 seconds forward/backward in the video