8. xaml & wpf - wpf concepts

82
Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer http://www.minkov.it rik.com/.../ desktop-applications- csharp - wpf WPF Concepts Dependency Properties, Routing

Upload: telerik-software-academy

Post on 06-May-2015

2.732 views

Category:

Technology


5 download

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

TRANSCRIPT

Page 2: 8. XAML & WPF - WPF Concepts

Table of Contents Dependency Objects Dependency Properties Attached Properties Trees in WPF

Trees in WPF Trees in Silverlight VisualTreeHelper LogicalTreeHelper

Page 3: 8. XAML & WPF - WPF Concepts

Table of Contents (2) Routing

Bubbling Tunneling

Commanding in XAML Built-in commands ICommand The Relay Command

MVVM Design Pattern

Page 4: 8. XAML & WPF - WPF Concepts

Dependency Object

Page 5: 8. XAML & WPF - WPF Concepts

Dependency Object The DependencyObject

Represents an object that participates in the dependency property system

Enables WPF 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

Page 6: 8. XAML & WPF - WPF Concepts

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

Page 7: 8. XAML & WPF - WPF Concepts

Dependency Properties

Dependencies

Page 8: 8. XAML & WPF - WPF Concepts

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

Page 9: 8. XAML & WPF - WPF Concepts

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 plain CLR property Can use the advantages of the

dependency properties

Page 10: 8. XAML & WPF - WPF Concepts

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

Page 11: 8. XAML & WPF - WPF Concepts

Dependency Properties

Live Demo

Page 12: 8. XAML & WPF - WPF Concepts

Attached PropertiesHow to set properties from another

place

Page 13: 8. XAML & WPF - WPF Concepts

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 don't have the wrapper

property

Examples of Attached Properties Grid.Row, Grid.Column,

Grid.RowSpan

Canvas.Top, Canvas.Left, Canvas.Bottom

etc.

Page 14: 8. XAML & WPF - WPF Concepts

Attached PropertiesLive Demo

Page 15: 8. XAML & WPF - WPF Concepts

Custom Dependency Properties

How to make our own Dependency Properties?

Page 16: 8. XAML & WPF - WPF Concepts

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

Page 17: 8. XAML & WPF - WPF Concepts

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

Page 18: 8. XAML & WPF - WPF Concepts

Dependency Property Wrapper

After the registration of the Dependency Property it needs wrapper Used to make it look like plain 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); }}

Page 19: 8. XAML & WPF - WPF Concepts

Custom Attached Properties

How to make attached properties?

Page 20: 8. XAML & WPF - WPF Concepts

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)));

Page 21: 8. XAML & WPF - WPF Concepts

Custom Dependency and Attached

PropertiesLive Demo

Page 22: 8. XAML & WPF - WPF Concepts

Trees in WPFObject, Visual and Logical

Page 23: 8. XAML & WPF - WPF Concepts

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

Page 24: 8. XAML & WPF - WPF Concepts

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

Page 25: 8. XAML & WPF - WPF Concepts

Object Tree

Window Border AdornedDecoration

AdornedLayerContentPresenter

StackPanel

Label

Border

ContentPresenter

TextBlock

Button

Border

ContentPresenter

TextBlock

The Object Tree

Page 26: 8. XAML & WPF - WPF Concepts

Logical Tree

Window Border AdornedDecoration

AdornedLayerContentPresenter

StackPanel

Label

Border

ContentPresenter

TextBlock

Button

Border

ContentPresenter

TextBlock

The Logical Tree

Page 27: 8. XAML & WPF - WPF Concepts

Visual Tree

Window Border AdornedDecoration

AdornedLayerContentPresenter

StackPanel

Label

Border

ContentPresenter

TextBlock

Button

Border

ContentPresenter

TextBlock

The Visual Tree

Page 28: 8. XAML & WPF - WPF Concepts

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

Page 29: 8. XAML & WPF - WPF Concepts

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

Page 30: 8. XAML & WPF - WPF Concepts

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

Page 31: 8. XAML & WPF - WPF Concepts

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)

Page 32: 8. XAML & WPF - WPF Concepts

Traversing Through Trees in WPF

VisualTreeHelper and Logical Tree Helper

Page 33: 8. XAML & WPF - WPF Concepts

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…

Page 34: 8. XAML & WPF - WPF Concepts

Traversing Through Trees in WPF

Live Demo

Page 35: 8. XAML & WPF - WPF Concepts

Routed Events in WPF

Bubbling and Tunneling

Page 36: 8. XAML & WPF - WPF Concepts

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 "bubbles" upward through the element tree

Page 37: 8. XAML & WPF - WPF Concepts

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

Page 38: 8. XAML & WPF - WPF Concepts

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

Page 39: 8. XAML & WPF - WPF Concepts

Routed Events Example

Tunneling

Window

Grid

StackPanel

TextBlockPreviewMouseLeftButtonDown Event is

raised

Page 40: 8. XAML & WPF - WPF Concepts

Routed Events Example

Window

Grid

StackPanel

TextBlock

Bubbling

MouseLeftButtonDown Event is raised

Page 41: 8. XAML & WPF - WPF Concepts

Routed Events in

WPF/SilverlightLive Demo

Page 42: 8. XAML & WPF - WPF Concepts

Commands in .NET

Page 43: 8. XAML & WPF - WPF Concepts

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

Page 44: 8. XAML & WPF - WPF Concepts

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

Page 45: 8. XAML & WPF - WPF Concepts

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.

Page 46: 8. XAML & WPF - WPF Concepts

The Four Main Concepts in WPF Commanding

The routed command model in WPF consists of four main concepts Command

The action to be executed

CommandSourceThe object that invokes the command

CommandTargetThe object that the command is executed on

CommandBindingThe object that maps command logic to command

Page 47: 8. XAML & WPF - WPF Concepts

Four Main Concepts in WPF Commanding

Example

<Menu> <MenuItem Command="Copy" CommandTarget="{Binding ElementName=textBoxText}" /> <MenuItem Command="Paste" CommandTarget="{Binding ElementName=mainTextBox}" /></Menu><TextBox Name="mainTextBox"/><TextBox Name="textBoxText"> Some Text in a Text Box</TextBox>

Page 48: 8. XAML & WPF - WPF Concepts

Commands in .NETLive Demo

Page 49: 8. XAML & WPF - WPF Concepts

The ICommand Interface

How to implement our own Commands

Page 50: 8. XAML & WPF - WPF Concepts

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

Page 51: 8. XAML & WPF - WPF Concepts

Implementation Command Example

Lets implement a Command to show the selected text in a TextBoxclass 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()); }}

Page 52: 8. XAML & WPF - WPF Concepts

Implementing Command Example

We need to make an instance of the Command in the code behind

The XAML file:<TextBox Name="TextBoxToShow">text</TextBox><Button Content="Click Me!" CommandParameter="{Binding ElementName=TextBoxToShow, Path=Text}" Command="{Binding MessageCommand}"/> In the Code Behind file:private ICommand messageCommand;public ICommand MessageCommand{ get { return this.messageCommand; }}

Page 53: 8. XAML & WPF - WPF Concepts

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

Page 54: 8. XAML & WPF - WPF Concepts

The ICommand Interface

Live Implementation

Page 55: 8. XAML & WPF - WPF Concepts

Better CommandingEven better than Custom Commands

Page 56: 8. XAML & WPF - WPF Concepts

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

Page 57: 8. XAML & WPF - WPF Concepts

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) {…}

Page 58: 8. XAML & WPF - WPF Concepts

Better CommandingLive Demo

Page 59: 8. XAML & WPF - WPF Concepts

What's the Point of Commands?!

Why the hell we need Commands?

Page 60: 8. XAML & WPF - WPF Concepts

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

Page 61: 8. XAML & WPF - WPF Concepts

Model – View – ViewModel

Design PatternWhat is MVVM?

Page 62: 8. XAML & WPF - WPF Concepts

Multilayer architectural pattern Introduced by Microsoft for usage in

WPF/Silverlight Wide usage of MVVM nowadays

Even in JavaScript and web development

Used for separation of concerns i.e. separate presentation from

program logic

What is Model View ViewModel?

Page 63: 8. XAML & WPF - WPF Concepts

What is Model View ViewModel? (2)

With MVVM the project becomes More easily extendable Easier for the back-end and front-

end developers to co-work on the same project

Change the presentation layer at any point

Easily testable

Page 64: 8. XAML & WPF - WPF Concepts

MVVM ArchitectureThe View, the Model, the ViewModel

Page 65: 8. XAML & WPF - WPF Concepts

MVVM Architecture MVVM consists of three layers

View is the Presentation Layer Only GUI elements

No business logic

Model refers to DataLayer Represents the real state content

Data access layer that represents that content

Page 66: 8. XAML & WPF - WPF Concepts

MVVM Architecture (2) ViewModel is a "Model of the View"

Abstraction of the View Serves in data binding between the

View and the Model Acts as a data binder/converter Changes Model information into

View information Passes commands from the View

into the Model Exposes public properties,

commands and abstractions

Page 67: 8. XAML & WPF - WPF Concepts

MVVM Layers Connections

The main idea of MVVM is that each pair of layers is coupled as loosely as possible The View only knows about the

ViewModel The View has no idea of the Model

The ViewModel only knows about the Model The ViewModel has no idea of the

View

The Model knows nothing about the other layers

View ViewModel

Model

Page 68: 8. XAML & WPF - WPF Concepts

MVVM Execution What happens when an user clicks a Button?

1. The View fires event that a button was clicked

2. The View calls a Method in the ViewModel

3. The ViewModel gets/sets some data from/in the ModelView ViewMode

lModel

User Fires an Event

The ViewModel requests data

The ViewModel receives data

The View Shows the new

data

Page 69: 8. XAML & WPF - WPF Concepts

Simple MVVM Implementation

Page 70: 8. XAML & WPF - WPF Concepts

Simple MVVM Implementation

An application that keeps a set of names The user can add or delete a name

at any time The user can see all the names

Application architecture Model

Keeps the names

ViewModel Gets/deletes/adds the names

View Gives a UI for these operations

Data and data logic

Business Logic

User Interface

Page 71: 8. XAML & WPF - WPF Concepts

Live Demo

Simple MVVM Implementation

Page 72: 8. XAML & WPF - WPF Concepts

Implementing the ViewModel

INotifyProperyChanged

Page 73: 8. XAML & WPF - WPF Concepts

ViewModel Implementation

A question pops out How does the View know about

changes in the ViewModel? How the ViewModel knows about

changes in the Model? There is no reversed connection,

right? The answer is simple

The INotifyPropertyChanged interface Gives an event to notify about

changes

Page 74: 8. XAML & WPF - WPF Concepts

INotifyProperyChanged The INotifyPropertyChanged

interface contains only one eventPropertyChanged(object sender, PropertyChangedEventArgs e) The point of this event is to be

called when the data is changed Both Model and ViewModel should

implement this interface In small project only the

ViewModel can implement it

Page 75: 8. XAML & WPF - WPF Concepts

Implementing INotifyPropertyChanged

The Property System automatically notifies the View about a change with PropertyChanged

public class ViewModel:INotifyPropertyChanged{ PropertyChanged(object sender,PropertyChangedEventArgs e)

OnPropertyChanged(string propertyName) { if(this.PropertyChanged!=null) { var args=new PropertyChangedEventArgs(propertyName); PropertyChanged(this,args); } }}

Page 76: 8. XAML & WPF - WPF Concepts

MVVM Real Life Implementation

Lets Get Practical

Page 77: 8. XAML & WPF - WPF Concepts

Implementing ImageViewer

We will implement an Image Viewer application using WPF and MVVM The user should be able to see all

the images in a given folder

The user should be able to add/delete images

The user should be able to select an image to enlarge it

Next and Previous buttons should be available

Page 78: 8. XAML & WPF - WPF Concepts

MVVM Real Life Implementation

Live Demo

Page 79: 8. XAML & WPF - WPF Concepts

Questions?

XAML Concepts

Page 80: 8. XAML & WPF - WPF Concepts

форум програмиране, форум уеб дизайнкурсове и уроци по програмиране, уеб дизайн – безплатно

програмиране за деца – безплатни курсове и уроцибезплатен SEO курс - оптимизация за търсачки

уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop

уроци по програмиране и уеб дизайн за ученициASP.NET MVC курс – HTML, SQL, C#, .NET, ASP.NET MVC

безплатен курс "Разработка на софтуер в cloud среда"

BG Coder - онлайн състезателна система - online judge

курсове и уроци по програмиране, книги – безплатно от Наков

безплатен курс "Качествен програмен код"

алго академия – състезателно програмиране, състезания

ASP.NET курс - уеб програмиране, бази данни, C#, .NET, ASP.NETкурсове и уроци по програмиране – Телерик академия

курс мобилни приложения с iPhone, Android, WP7, PhoneGap

free C# book, безплатна книга C#, книга Java, книга C#Дончо Минков - сайт за програмиранеНиколай Костов - блог за програмиранеC# курс, програмиране, безплатно

?

? ? ??

?? ?

?

?

?

??

?

?

? ?

Questions?

?http://academy.telerik.com

XAML Concepts

Page 81: 8. XAML & WPF - WPF 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