8. XAML & WPF - WPF Concepts

  • View
    2.591

  • Download
    2

Embed Size (px)

DESCRIPTION

WPF ConceptsTelerik Software Academy: http://academy.telerik.com/school-academy/meetings/details/2012/02/02/desktop-applications-csharp-wpfThe website and all video materials are in Bulgarian.Dependency ObjectsDependency PropertiesAttached PropertiesTrees in WPFTrees in WPFTrees in SilverlightVisualTreeHelperLogicalTreeHelperRoutingBubblingTunnelingCommanding in XAMLBuilt-in commandsICommandThe Relay CommandMVVM Design Pattern

Text of 8. XAML & WPF - WPF Concepts

  • 1.WPF Concepts Dependency Properties, RoutingDoncho MinkovTechnical Trainerhttp://www.minkov.itTelerik Software Academyacademy.telerik.com

2. Table of Contents Dependency Objects Dependency Properties Attached Properties Trees in WPF 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 MVVM Design Pattern 4. Dependency Object 5. Dependency Object The DependencyObject Represents an object that participates in thedependency property system Enables WPF property system services The property systems functions: Compute the values of properties Provide system notification about values thathave 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 anydependency properties Metadata, coerce value support, propertychanged notification Override callbacks for dependency properties orattached properties DependencyObject class facilitates the per-owner property metadata for a dependency property 7. Dependency PropertiesDependencies 8. Dependency Properties WPF provides 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 WPF property system Dependency Property is A property that is backed by the WPF property system 9. Dependency Properties (2) Dependency properties are typically exposed as CLR properties At a basic level, you could interact with theseproperties directly May never find out they are dependencyproperties Better to know if a property is Dependency or plain CLR property Can use the advantages of the dependencyproperties 10. Dependency Properties (3) The purpose of dependency propertiesis 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 11. Dependency Properties Live Demo 12. Attached PropertiesHow 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 attached properties are defined as dependency properties They dont have the wrapper property Examples of Attached Properties Grid.Row, Grid.Column, Grid.RowSpan Canvas.Top, Canvas.Left, Canvas.Bottom etc. 14. Attached PropertiesLive Demo 15. Custom Dependency PropertiesHow to make our own Dependency Properties? 16. Custom Dependency Properties The first thing to do is to register theDependency Property Need registration due to the Property SystemDependency Propertys instance is always readonlypublic static readonlyDependencyProperty ScrollValueProperty =DependencyProperty.Register( Registration to the "ScrollValue", Property System typeof(double), typeof(UserControl), The name of the null); Dependency Property In most of the cases we need a dependency property on a UserControl 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 DependencyProperty it needs wrapper Used to make it look like plain CLR Property DependencyObject has two methods used forthe wrapping of dependency properties SetValue(DependenyProperty, value) GetValue(DependenyProperty)public double ScrollValue{ get { return (double)GetValue(ScrollValueProperty); } set { SetValue(ScrollValueProperty , value); }} 19. Custom Attached PropertiesHow to make attached properties? 20. Custom Attached Properties The registration of attached properties is alittle differentprivate 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))); 21. Custom Dependency andAttached Properties Live Demo 22. Trees in WPFObject, Visual and Logical 23. Trees in WPF WPF uses a hierarchical system to organize 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 Visual tree 24. Trees in WPF (2) 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 25. Object TreeWindow BorderAdornedDecorationStackPanel ContentPresenterAdornedLayer LabelButtonBorderBorder The Object TreeContentPresenterContentPresenter TextBlockTextBlock 26. Logical TreeWindow BorderAdornedDecorationStackPanel ContentPresenterAdornedLayer LabelButtonBorderBorder The Logical TreeContentPresenterContentPresenter TextBlockTextBlock 27. Visual TreeWindow BorderAdornedDecorationStackPanel ContentPresenterAdornedLayer LabelButtonBorderBorder The Visual TreeContentPresenterContentPresenter TextBlockTextBlock 28. 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 rendersthe visual children of it 29. 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 containsthe "real" controls Not all the template parts And that is the eligibility for the logical tree 30. 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 31. The Visual Tree Contains all logical elements Including all visual elements of the template ofeach 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) 32. Traversing ThroughTrees in WPFVisualTreeHelper and Logical Tree Helper 33. LogicalTreeHelper andVisualTreeHelper 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 34. Traversing Through Trees in WPFLive Demo 35. Routed Events in WPFBubbling and Tunneling 36. Routed Events What is a routed event? A type of event that can invoke handlers onmultiple 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 sourceelement and then "bubbles" upward throughthe element tree 37. Types of Routed Events Three types of routed events in WPF 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 38. 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 39. Routed Events ExampleWindow GridTunneling StackPanel TextBlockPreviewMouseLeftButtonDown Event is raised 40. Routed Events ExampleWindow Grid Bubbling StackPanel TextBlockMouseLeftButtonDownEvent is raised 41. Routed Events inWPF/Silverlight Live Demo 42. Commands in .NET 43. 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 44. WPF Commands (2) Commands have severalpurposes 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 45. 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. 46. 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 47. Four Main Concepts in WPFCommanding Example

Some Text in a Text Box 48. Commands in .NET Live Demo 49. The ICommand Interface How to implement our own Commands 50. ICommand Interface The ICommand interface Determines whether thecommand can be executedpublic bool CanExecute(object parameter);public event EventHandler CanExecuteChanged;public void Execute(object par