wpf concepts
TRANSCRIPT
XAML ConceptsXAML ConceptsDependency Properties, XAML Trees, Dependency Properties, XAML Trees,
RoutingRouting
Doncho MinkovDoncho Minkov
Telerik School Telerik School AcademyAcademyschoolacademy.telerik.com
Technical TrainerTechnical Trainerhttp://www.minkov.it
Table of ContentsTable of Contents Dependency ObjectsDependency Objects Dependency PropertiesDependency Properties Attached PropertiesAttached Properties Trees in XAMLTrees in XAML
Trees in WPFTrees in WPF Trees in SilverlightTrees in Silverlight VisualTreeHelperVisualTreeHelper LogicalTreeHelperLogicalTreeHelper
Table of Contents (2)Table of Contents (2) RoutingRouting
BubblingBubbling TunnelingTunneling
Commanding in XAMLCommanding in XAML Built-in commandsBuilt-in commands ICommandICommand The Relay CommandThe Relay Command
Dependency ObjectDependency Object
Dependency ObjectDependency Object The The DependencyObjectDependencyObject
Represents an object that participates in Represents an object that participates in the dependency property systemthe dependency property system
Enables Enables WPFWPF / / SLSL propertyproperty systemsystem servicesservices
The property system's functions:The property system's functions: Compute the values of propertiesCompute the values of properties Provide system notification about values Provide system notification about values
that have changedthat have changed DependencyObjectDependencyObject as a base class enables as a base class enables
objects to use Dependency Propertiesobjects to use Dependency Properties
Dependency Object (2)Dependency Object (2) DependencyObjectDependencyObject has the following has the following
GetGet, , SetSet, and , and ClearClear methods for methods for values of any dependency propertiesvalues of any dependency properties
Metadata, coerce value support, Metadata, coerce value support, property changed notificationproperty changed notification
Override callbacks for dependency Override callbacks for dependency properties or attached propertiesproperties or attached properties
DependencyObjectDependencyObject class facilitates class facilitates the the per-owner property metadata for a per-owner property metadata for a dependency propertydependency property
Dependency Dependency PropertiesProperties
DependenciesDependencies
Dependency PropertiesDependency Properties Silverlight and WPF provide a set Silverlight and WPF provide a set
of services that can be used to of services that can be used to extend the functionality of a CLR extend the functionality of a CLR propertyproperty Collectively, these services are Collectively, these services are
typically referred to as the typically referred to as the Silverlight / WPF property systemSilverlight / WPF property system
Dependency Property is Dependency Property is A property that is backed by the A property that is backed by the
SL/WPF property systemSL/WPF property system
Dependency Properties Dependency Properties (2)(2)
Dependency properties are Dependency properties are typically exposed as CLR propertiestypically exposed as CLR properties At a basic level, you could interact At a basic level, you could interact
with these properties directly with these properties directly
May never find out they are May never find out they are dependency propertiesdependency properties
Better to know if a property is Better to know if a property is Dependency or CLRDependency or CLR Can use the advantages of the Can use the advantages of the
dependency propertiesdependency properties
Dependency Properties Dependency Properties (3)(3)
The purpose of dependency The purpose of dependency properties is to provide a way to properties is to provide a way to compute the value of a property compute the value of a property based on the value of other inputsbased on the value of other inputs Can be implemented to provide Can be implemented to provide
callbacks to propagate changes to callbacks to propagate changes to other propertiesother properties
Dependency Dependency PropertiesProperties
Live DemoLive Demo
Attached PropertiesAttached PropertiesHow to set properties from another How to set properties from another
placeplace
Attached PropertiesAttached Properties An attached property is intended to be An attached property is intended to be
used as a type of global property that used as a type of global property that is settable on any objectis settable on any object
In WPF and Silverlight attached In WPF and Silverlight attached properties are defined as dependency properties are defined as dependency properties properties They don't have the wrapper propertyThey don't have the wrapper property
Examples of Attached PropertiesExamples of Attached Properties Grid.Row, Grid.Column, Grid.RowSpanGrid.Row, Grid.Column, Grid.RowSpan
Canvas.Top, Canvas.Left, Canvas.BottomCanvas.Top, Canvas.Left, Canvas.Bottom
etc.etc.
Attached PropertiesAttached PropertiesLive DemoLive Demo
Custom Dependency Custom Dependency PropertiesProperties
How to make our own Dependency How to make our own Dependency Properties?Properties?
Custom Dependency Custom Dependency PropertiesProperties
The first thing to do is to register The first thing to do is to register the Dependency Propertythe Dependency Property Need registration due to the Need registration due to the
Property SystemProperty System
In most of the cases we need a In most of the cases we need a dependency property on a dependency property on a UserControlUserControl
public static readonly public static readonly DependencyProperty ScrollValueProperty =DependencyProperty ScrollValueProperty = DependencyProperty.Register(DependencyProperty.Register( "ScrollValue", "ScrollValue", typeof(double), typeof(double), typeof(UserControl),typeof(UserControl), null);null);
Dependency Property's Dependency Property's instance is always instance is always
readonlyreadonly
The name of the The name of the Dependency Dependency
PropertyProperty
Registration to Registration to the Property the Property
SystemSystem
Dependency Property Dependency Property RegistrationRegistration
Two Register Methods:Two Register Methods: Register(String, Type, Type)Register(String, Type, Type)
Registers a dependency property Registers a dependency property with the specified property name, with the specified property name, property type, and owner typeproperty type, and owner type
Register(String, Type, Type, Register(String, Type, Type, PropertyMetadata)PropertyMetadata)
Add Property metadataAdd Property metadata
Default value or Callback for Default value or Callback for Property changesProperty changes
Dependency Property Dependency Property WrapperWrapper
After the registration of the After the registration of the Dependency PropertyDependency Property it needs it needs wrapperwrapper Used to make it look like plain old Used to make it look like plain old
CLR PropertyCLR Property DependencyObjectDependencyObject has two methods has two methods
used for the wrapping of dependency used for the wrapping of dependency propertiesproperties SetValue(DependenyProperty, value)SetValue(DependenyProperty, value) GetValue(DependenyProperty)GetValue(DependenyProperty)
public double ScrollValuepublic double ScrollValue{{ get { return get { return (double)GetValue(ScrollValueProperty); }(double)GetValue(ScrollValueProperty); } set { SetValue(ScrollValueProperty , value); }set { SetValue(ScrollValueProperty , value); }}}
Custom Attached Custom Attached PropertiesProperties
How to make attached properties?How to make attached properties?
Custom Attached Custom Attached PropertiesProperties
The registration of attached The registration of attached properties is a little differentproperties is a little different
private static void OnPropertyChanged(…) { … }private static void OnPropertyChanged(…) { … }
public static Thickness GetMargin(DependencyObject obj)public static Thickness GetMargin(DependencyObject obj){{ return (Thickness)obj.GetValue(MarginProperty);return (Thickness)obj.GetValue(MarginProperty);}}
public static void SetMargin(DependencyObject obj, Thickness public static void SetMargin(DependencyObject obj, Thickness val)val){{ obj.SetValue(MarginProperty, val);obj.SetValue(MarginProperty, val);}}
public static readonly DependencyProperty MarginProperty =public static readonly DependencyProperty MarginProperty = DependencyProperty.RegisterAttached("Margin",DependencyProperty.RegisterAttached("Margin", typeof(Thickness), typeof(ContentMargin), typeof(Thickness), typeof(ContentMargin), new FrameworkPropertyMetadata(default(Thickness), new FrameworkPropertyMetadata(default(Thickness), new new PropertyChangedCallback(OnPropertyChanged)));PropertyChangedCallback(OnPropertyChanged)));
Custom Dependency Custom Dependency and Attached and Attached
PropertiesPropertiesLive DemoLive Demo
Trees in WPFTrees in WPFVisual and LogicalVisual and Logical
Trees in WPF and Trees in WPF and SilverlightSilverlight
WPF and Silverlight use a hierarchical WPF and Silverlight use a hierarchical system that organizes the elements system that organizes the elements and componentsand components Developers can manipulate the nodes Developers can manipulate the nodes
directlydirectly Affect the rendering or behavior of an Affect the rendering or behavior of an
applicationapplication
Two such trees exist in WPF Two such trees exist in WPF Logical tree and Visual treeLogical tree and Visual tree
One kind of tree in SilverlightOne kind of tree in Silverlight Visual TreeVisual Tree
Trees in WPF and Trees in WPF and SilverlightSilverlight
Elements of a XAML are Elements of a XAML are hierarchically relatedhierarchically related This relation is called the This relation is called the LogicalTreeLogicalTree
The template of one element The template of one element consists of multiple visual elementsconsists of multiple visual elements This tree is called the This tree is called the VisualTreeVisualTree
WPF differs between those two treesWPF differs between those two trees Some problems are solved only by Some problems are solved only by
the logical elements the logical elements For others you want all elementsFor others you want all elements
Trees in WPFTrees in WPFVisual and LogicalVisual and Logical
The Trees in WPFThe Trees in WPF WPF supports two kinds of Trees WPF supports two kinds of Trees
for renderingfor rendering Logical TreeLogical Tree
Describes the structure of control Describes the structure of control elementselements
Visual TreeVisual Tree
Describes the structure of Visual Describes the structure of Visual elementselements
Sometimes both trees are used the Sometimes both trees are used the same waysame way
Object TreeObject Tree
The Object TreeThe Object Tree
WindowWindow BorderBorder AdornedDecorationAdornedDecoration
AdornedLayerAdornedLayerContentPresentContentPresenterer
StackPanelStackPanel
LabelLabel
BorderBorder
ContentPresenterContentPresenter
TextBlockTextBlock
ButtonButton
BorderBorder
ContentPresenterContentPresenter
TextBlockTextBlock
Logical TreeLogical Tree
The Logical TreeThe Logical Tree
WindowWindow BorderBorder AdornedDecorationAdornedDecoration
AdornedLayerAdornedLayerContentPresentContentPresenterer
StackPanelStackPanel
LabelLabel
BorderBorder
ContentPresenterContentPresenter
TextBlockTextBlock
ButtonButton
BorderBorder
ContentPresenterContentPresenter
TextBlockTextBlock
Visual TreeVisual Tree
The Visual TreeThe Visual Tree
WindowWindow BorderBorder AdornedDecorationAdornedDecoration
AdornedLayerAdornedLayerContentPresentContentPresenterer
StackPanelStackPanel
LabelLabel
BorderBorder
ContentPresenterContentPresenter
TextBlockTextBlock
ButtonButton
BorderBorder
ContentPresenterContentPresenter
TextBlockTextBlock
Why Two Kinds of Why Two Kinds of Trees?Trees?
A WPF control consists of multiple, A WPF control consists of multiple, more primitive controlsmore primitive controls A button consists of A button consists of
A border, a rectangle and a content A border, a rectangle and a content presenter.presenter.
These controls are visual children of the These controls are visual children of the buttonbutton
When WPF renders the buttonWhen WPF renders the button The element itself has no appearanceThe element itself has no appearance It iterates through the visual tree and It iterates through the visual tree and
renders the visual children of itrenders the visual children of it
Why Two Kinds of Why Two Kinds of Trees? (2)Trees? (2)
Sometimes you are not interested Sometimes you are not interested in the borders and rectangles of a in the borders and rectangles of a controls' templatecontrols' template You want a more robust tree that You want a more robust tree that
only contains the "real" controls only contains the "real" controls
Not all the template partsNot all the template parts
And that is the eligibility for the And that is the eligibility for the logical treelogical tree
The Logical TreeThe Logical Tree The logical tree describes the The logical tree describes the
relations between elements of the relations between elements of the user interfaceuser interface
The logical tree is responsible for:The logical tree is responsible for: Inherit Inherit DependencyPropertyDependencyProperty values values
Resolving Resolving DynamicResources DynamicResources referencesreferences
Looking up element names for Looking up element names for bindingsbindings
Forwarding Forwarding RoutedEventsRoutedEvents
The Visual TreeThe Visual Tree Contains all logical elementsContains all logical elements
Including all visual elements of the Including all visual elements of the template of each elementtemplate of each element
The visual tree is responsible for:The visual tree is responsible for: Rendering visual elementsRendering visual elements Propagate element opacityPropagate element opacity Propagate Propagate Layout-Layout- and and
RenderTransformsRenderTransforms Propagate the Propagate the IsEnabled IsEnabled propertyproperty Do Hit-TestingDo Hit-Testing RelativeSource (FindAncestor)RelativeSource (FindAncestor)
Traversing Through Traversing Through Trees in WPFTrees in WPF
VisualTreeHelper and Logical Tree VisualTreeHelper and Logical Tree HelperHelper
LogicalTreeHelper and LogicalTreeHelper and VisualTreeHelperVisualTreeHelper
Help a lot when traversing the WPF Help a lot when traversing the WPF TreesTrees
Key Functionality:Key Functionality: GetParrent(Dependency Object)GetParrent(Dependency Object)
Gets the logical parent of the current Gets the logical parent of the current elementelement
GetChildren(Dependency Object)GetChildren(Dependency Object) GetOpacity(Dependency Object)GetOpacity(Dependency Object)
Etc…Etc…
Traversing Through Traversing Through Trees in WPFTrees in WPF
Live DemoLive Demo
Visual Tree in Visual Tree in SilverlightSilverlight
Just the VisualJust the Visual
The Visual Tree in The Visual Tree in SilverlightSilverlight
The same as in WPFThe same as in WPF Works exactly as in WPFWorks exactly as in WPF
May be used to find the first May be used to find the first ancestor of concrete typeancestor of concrete type
i.e. the first i.e. the first GridGrid or or StackPanelStackPanelpublic static T FindUpVisualTree<T>public static T FindUpVisualTree<T> (DependencyObject initial) where T : (DependencyObject initial) where T : DependencyObjectDependencyObject{{ DependencyObject current = initial;DependencyObject current = initial; while (current != null && while (current != null && current.GetType() != typeof(T))current.GetType() != typeof(T)) { current = { current = VisualTreeHelper.GetParent(current); }VisualTreeHelper.GetParent(current); } return current as T; return current as T; }}
Visual Tree in Visual Tree in SilverlightSilverlight
Live DemoLive Demo
Routed Events in Routed Events in WPF/SilverlightWPF/Silverlight
Bubbling and TunnelingBubbling and Tunneling
Routed EventsRouted Events What is a routed event?What is a routed event?
A type of event that can invoke A type of event that can invoke handlers on multiple listeners in an handlers on multiple listeners in an element treeelement tree Rather than just on the object that raised Rather than just on the object that raised
itit
The event route can travel in one of The event route can travel in one of two directionstwo directions Depending on the event definitionDepending on the event definition Generally the route travels from the Generally the route travels from the
source element and then "bubbles" source element and then "bubbles" upward through the element treeupward through the element tree
Types of Routed EventsTypes of Routed Events Three types of routed events in WPF Three types of routed events in WPF
and SLand SL BubblingBubbling
Event handlers on the event source are Event handlers on the event source are invokedinvoked
Then routes to successive parent elements Then routes to successive parent elements until reaching the element tree rootuntil reaching the element tree root
Most routed events use bubbling routing Most routed events use bubbling routing strategystrategy
DirectDirect Only the source element itself is given the Only the source element itself is given the
opportunity to invoke handlers in responseopportunity to invoke handlers in response
Types of Routed Events Types of Routed Events (2)(2) Three types of routed events in WPF Three types of routed events in WPF
and SLand SL TunnelingTunneling
Event handlers at the tree root are Event handlers at the tree root are invoked firstinvoked first
Then travels down the object tree to the Then travels down the object tree to the node that is the source of the eventnode that is the source of the event The element that raised the routed eventThe element that raised the routed event
Not supported in SilverlightNot supported in Silverlight
Available as Preview eventsAvailable as Preview events PreviewClickPreviewClick
Routed Events ExampleRouted Events Example
TunnelingTunneling
WindowWindow
GridGrid
StackPanelStackPanel
TextBlockTextBlockPreviewMouseLeftBPreviewMouseLeftButtonDownuttonDown Event is Event is
raisedraised
Routed Events ExampleRouted Events Example
WindowWindow
GridGrid
StackPanelStackPanel
TextBlockTextBlock
BubblingBubbling
MouseLeftButtonDoMouseLeftButtonDownwn Event is raised Event is raised
Routed Events Routed Events in in
WPF/SilverlightWPF/SilverlightLive DemoLive Demo
Commands in .NETCommands in .NET
WPF CommandsWPF Commands
Commanding is an input Commanding is an input mechanism in WPFmechanism in WPF Provides input handling at a more Provides input handling at a more
semantic level than device inputsemantic level than device input Examples of commands are the Examples of commands are the CopyCopy, , CutCut, and , and PastePaste operations operations
WPF Commands (2)WPF Commands (2)
Commands have several purposesCommands have several purposes Separate the semantics and the Separate the semantics and the
objects that invoke a command objects that invoke a command from the logic that executes the from the logic that executes the commandcommand Allows for multiple and disparate Allows for multiple and disparate
sources to invoke the same command sources to invoke the same command logiclogic
Allows the command logic to be Allows the command logic to be customized for different targetscustomized for different targets
WPF CommandsWPF Commands Commands can be used to indicate Commands can be used to indicate
whether an action is availablewhether an action is available Example: when trying to cut something, Example: when trying to cut something,
the user should first select somethingthe user should first select something To indicate whether an action is To indicate whether an action is
possible possible Implement the Implement the CanExecuteCanExecute methodmethod
A button can subscribe to the A button can subscribe to the CanExecuteChangedCanExecuteChanged event event Disabled if Disabled if CanExecuteCanExecute returns false returns false
Enabled if Enabled if CanExecuteCanExecute returns true. returns true.
The Four Main Concepts The Four Main Concepts in WPF Commandingin WPF Commanding
The routed command model in WPF The routed command model in WPF consists of four main conceptsconsists of four main concepts CommandCommand
The action to be executedThe action to be executed
CommandSourceCommandSourceThe object that invokes the commandThe object that invokes the command
CommandTargetCommandTargetThe object that the command is executed The object that the command is executed onon
CommandBindingCommandBindingThe object that maps command logic to The object that maps command logic to commandcommand
Four Main Concepts in Four Main Concepts in WPF Commanding WPF Commanding
ExampleExample
<Menu><Menu> <MenuItem Command="Copy"<MenuItem Command="Copy" CommandTarget="{Binding ElementName=textBoxText}" CommandTarget="{Binding ElementName=textBoxText}" />/> <MenuItem Command="Paste"<MenuItem Command="Paste" CommandTarget="{Binding ElementName=mainTextBox}" CommandTarget="{Binding ElementName=mainTextBox}" />/></Menu></Menu><TextBox Name="mainTextBox"/><TextBox Name="mainTextBox"/><TextBox Name="textBoxText"><TextBox Name="textBoxText"> Some Text in a Text BoxSome Text in a Text Box</TextBox></TextBox>
Commands in .NETCommands in .NETLive DemoLive Demo
The ICommand The ICommand InterfaceInterface
How to implement our own CommandsHow to implement our own Commands
ICommand InterfaceICommand Interface
The The ICommandICommand interface interface
public bool CanExecute(object parameter);public bool CanExecute(object parameter);
public event EventHandler CanExecuteChanged;public event EventHandler CanExecuteChanged;
public void Execute(object parameter);public void Execute(object parameter);
Determines Determines whether the whether the
command can be command can be executedexecuted
When changes of When changes of the CanExecute the CanExecute
state occurstate occur
Called to Called to invoke the invoke the commandcommand
Implementation Implementation Command ExampleCommand Example
Lets implement a Lets implement a CommandCommand to show to show the selected text in a the selected text in a TextBoxTextBoxclass MessagePopCommand : ICommandclass MessagePopCommand : ICommand{{ public bool CanExecute(object parameter)public bool CanExecute(object parameter) {{ if (parameter == null)if (parameter == null) {{ return false;return false; }} return !return !string.IsNullOrEmpty(parameter.ToString());string.IsNullOrEmpty(parameter.ToString()); }}
public event EventHandler CanExecuteChanged;public event EventHandler CanExecuteChanged;
public void Execute(object parameter)public void Execute(object parameter) {{ MessageBox.Show(parameter.ToString());MessageBox.Show(parameter.ToString()); }}}}
Implementing Implementing Command ExampleCommand Example
We need to make an instance of the We need to make an instance of the CommandCommand in the code behind in the code behind
The The XAMLXAML file: file:<TextBox Name="TextBoxToShow">text</TextBox><TextBox Name="TextBoxToShow">text</TextBox><Button Content="Click Me!" <Button Content="Click Me!" CommandParameter="{Binding CommandParameter="{Binding ElementName=TextBoxToShow, ElementName=TextBoxToShow, Path=Text}"Path=Text}" Command="{Binding MessageCommand}"/>Command="{Binding MessageCommand}"/> In the In the CodeCode BehindBehind file: file:private ICommand messageCommand;private ICommand messageCommand;public ICommand MessageCommandpublic ICommand MessageCommand{{ get { return this.messageCommand; }get { return this.messageCommand; }}}
How Does it Work?How Does it Work? When binding the command of the When binding the command of the
button to a specific command instance, button to a specific command instance, the the CanExecute CanExecute method is invokedmethod is invoked If it returns If it returns falsefalse the button is the button is disableddisabled If If truetrue is returned the button is is returned the button is enabledenabled
A known problemA known problem The order of the The order of the CommandCommand and and CommandParameterCommandParameter properties matters!properties matters! The XAML parser works from left to right The XAML parser works from left to right
The paramerters must be known before The paramerters must be known before bindingbinding
The ICommand The ICommand InterfaceInterface
Live ImplementationLive Implementation
Better CommandingBetter CommandingEven better than Custom CommandsEven better than Custom Commands
Better CommandingBetter Commanding
Most of the times it is not Most of the times it is not necessary to implement necessary to implement ICommandICommand class for every distinct commandclass for every distinct command Since in most of the cases the Since in most of the cases the ConcreteCommandConcreteCommand has the same has the same interfaceinterface
Can we implement a command and Can we implement a command and give different behavior then give different behavior then instantiating?instantiating? Of course – use the so called Of course – use the so called RelayCommandRelayCommand
The RelayCommandThe RelayCommand What is a relay commandWhat is a relay command
A command which is given an A command which is given an behavior during instantiatingbehavior during instantiating
Both Both CanExecuteCanExecute and and ExecuteExecute methodsmethods
ICommand someCommand;ICommand someCommand;public MyWindow()public MyWindow(){{ this.someCommand = this.someCommand = new new RelayCommand(ExecuteMethod,CanExecuteMethod);RelayCommand(ExecuteMethod,CanExecuteMethod);}}public void ExecuteMethod(object parameter) {…}public void ExecuteMethod(object parameter) {…}public bool CanExecuteMethod(object parameter) {…}public bool CanExecuteMethod(object parameter) {…}
Better CommandingBetter CommandingLive DemoLive Demo
What's the Point of What's the Point of Commands?!Commands?!
Why the hell we need Commands?Why the hell we need Commands?
The Point of CommandsThe Point of Commands The answer is simple:The answer is simple:
The Commands can execute without The Commands can execute without the knowledge of who wants to the knowledge of who wants to execute themexecute them
Commands are:Commands are: Easily implementedEasily implemented Easily extendedEasily extended Easily replaceableEasily replaceable A way to change an object without A way to change an object without
knowledge of who wants to change itknowledge of who wants to change it Fundamental part of the MVVM patternFundamental part of the MVVM pattern
QuestionsQuestions??
XAML ConceptsXAML Concepts
ExercisesExercises Extend the VideoPlayer Control from Extend the VideoPlayer Control from
the example:the example: Add a slider that slides with the video Add a slider that slides with the video
lengthlength
Add a slider that changes the volumeAdd a slider that changes the volume
Add buttons for Play, Pause, StopAdd buttons for Play, Pause, Stop
Add key events for volume UP/DOWNAdd key events for volume UP/DOWN
Add key events to jump 5 seconds Add key events to jump 5 seconds forward/backward in the videoforward/backward in the video