Transcript
Page 1: NET Database Technologies: Introduction to WPF and Entity Framework DataBinding

.NET Database Technologies: Introduction to WPF and Entity

Framework DataBinding

Page 2: NET Database Technologies: Introduction to WPF and Entity Framework DataBinding

WPF rationale

• UI layout and design separated from functionality

• XML-based Markup language (XAML) for design, programming language (C#, VB, etc) for functionality

• Designers and developers can use separate specialised tools to work on the same project:

• Expression Blend for designers

• Visual Studio for developers

Page 3: NET Database Technologies: Introduction to WPF and Entity Framework DataBinding

WPF rationale

• Similar technology, based on XAML and C#/VB, can be used for different interface types:

Windows (WPF)

Web (Silverlight)

Phone (Silverlight)

• Basic idea of building interface using markup and code is similar to other web development technologies, e.g.

HTML & JavaScript

ASP.NET & C#

Page 4: NET Database Technologies: Introduction to WPF and Entity Framework DataBinding

XAML controls

• Layout controls

containers for other controls to position them in the interface

<Frame>, <Grid>, <StackPanel>, etc.

• Interactive controls

<Button>, <ComboBox>,<Slider>, etc.

• Display controls

<Label>,<ListBox>, <Image>, etc

• Data controls

<DataGrid>, <ListView>, etc.

• Application controls

<Menu>, <ToolBar>, etc.

Page 5: NET Database Technologies: Introduction to WPF and Entity Framework DataBinding

A simple WPF example

text box – user can type a question heretext box – user can type a question here

button – user clicks this to get advicebutton – user clicks this to get advice

text box – answer is shown heretext box – answer is shown here

Page 6: NET Database Technologies: Introduction to WPF and Entity Framework DataBinding

XAML window

• Window defined in a XAML file

•Grid control as a container

other controls are defined here, inside <Grid> controlother controls are defined here, inside <Grid> control

Grid has 3 rows, middle row sized to fit contents, others expand to fill available space

Grid has 3 rows, middle row sized to fit contents, others expand to fill available space

Page 7: NET Database Technologies: Introduction to WPF and Entity Framework DataBinding

Adding controls to a window

• Controls defined inside <Grid> element

Attributes control appearance of controls (fonts, margins, etc)Attributes control appearance of controls (fonts, margins, etc)

Grid.Row attribute specifies which row of grid the control is displayed in

Grid.Row attribute specifies which row of grid the control is displayed in

name of method to handle click eventname of method to handle click event

Page 8: NET Database Technologies: Introduction to WPF and Entity Framework DataBinding

Code-behind file

• Contains a C# class which is derived from Window library class

event handler methodevent handler method

constructorconstructor

event handler method uses a model class AdviceGenerator and sets Text property of the text box named txtAnswer

event handler method uses a model class AdviceGenerator and sets Text property of the text box named txtAnswer

Page 9: NET Database Technologies: Introduction to WPF and Entity Framework DataBinding

Applications and windows

• App.xaml is the startup file for a WPF project

• Code-behind contains an empty constructor by default

• So where is the Main method?

In autogenerated code in file App.g.cs in obj folder

• Additional windows defined as separate XAML files

Can create an instance of code-behind class and call its Show method to open a new window

• Can also design applications using a page-based model

window to open at startupwindow to open at startup

Page 10: NET Database Technologies: Introduction to WPF and Entity Framework DataBinding

Code and visual designers

• WPF windows can be designed using visual design tools in Visual Studio and Expression Blend

• Important to understand XAML code to get fine control over design

• Plan out layout using capabilities of layout controls rather than dragging controls from designer toolbox and positioning visually

Makes it easy to provide layouts which adjust elegantly when window is resized

Page 11: NET Database Technologies: Introduction to WPF and Entity Framework DataBinding

Layout controls

•Grid

arranges its child controls in a tabular structure

•Stack Panel, Wrap Panel

stacks child elements below or beside each other, Wrap Panel wraps to new line if no space

•Dock Panel

docks elements to left, right, top, bottom or centre

•Canvas

Elements positioned by coordinates, mainly used for 2D drawing

Page 12: NET Database Technologies: Introduction to WPF and Entity Framework DataBinding

Alignment

Button Button Button Button

Button Button Button Button

Button Button Button Button

Button Button Button Button

Left Center Right Stretch

Top

Center

Bottom

Stretch

Horizontal Alignment

Ver

tica

l Alig

nm

ent

Page 13: NET Database Technologies: Introduction to WPF and Entity Framework DataBinding

Margin and padding

• The Margin is the extra space around the control

• The Padding is extra space inside the control

• The Padding of an outer control is the Margin of an inner control

OKOK OKCancel

Padding

Margin

Page 14: NET Database Technologies: Introduction to WPF and Entity Framework DataBinding

Laying out a grid

• Row and column definitions

• Sizes:

Fixed: Fixed size)

Auto: Takes as much space as needed by the contained control

Star (*): Takes as much space as available

• Position each control in grid with properties Grid.Column and Grid.Row

• Merge grid cells with Grid.ColumnSpan and Grid.RowSpan

• These are WPF attached properties

Page 15: NET Database Technologies: Introduction to WPF and Entity Framework DataBinding

WPF properties

• Normal .NET properties

Value read directly from member field in class

• Dependency properties

Resolved dynamically, e.g. by binding, allowing:

• Change notification

• Inheritance from parent elements

• Reduced memory footprint – only store non-default values

Many XAML control properties are dependency properties

• Attached properties

Allow you to attach a value to an object that does not know anything about this value

A child element can store a value associated with a property defined on an parent element 

Page 16: NET Database Technologies: Introduction to WPF and Entity Framework DataBinding

Layout example

Page 17: NET Database Technologies: Introduction to WPF and Entity Framework DataBinding

Layout example - Grid

4 rows, 3 columns4 rows, 3 columns

Page 18: NET Database Technologies: Introduction to WPF and Entity Framework DataBinding

Layout example - controls

can miss out Column=“0”can miss out Column=“0”

Page 19: NET Database Technologies: Introduction to WPF and Entity Framework DataBinding

XAML routed events

• A typical WPF application contains many elements.

• Elements exist in an element tree relationship to each other

• A routed event is a type of event that can invoke handlers on multiple listeners in an element tree, rather than just on the object that raised the event

• The event route generally travels from the source element and then "bubbles" upward through the element tree until it reaches the element tree root (typically a page or a window)

• Control composition and encapsulation

• Singular handler attachment points

Page 20: NET Database Technologies: Introduction to WPF and Entity Framework DataBinding

XAML routed events

• This example has Button click handlers attached at different levels in the tree

Page 21: NET Database Technologies: Introduction to WPF and Entity Framework DataBinding

Handling routed events

handles Cancel button and sets Handled to true so that event does not bubble up

handles Cancel button and sets Handled to true so that event does not bubble up

other button events bubble up to Grid and are handled here

other button events bubble up to Grid and are handled here

this will not happen as Cancel button event already handled

this will not happen as Cancel button event already handled

Page 22: NET Database Technologies: Introduction to WPF and Entity Framework DataBinding

Types of event

• Actually, it’s a bit more complicated than that...

• There are three types of routed event:

•Direct events

Like ordinary .NET events, originate in one element and do not pass to any other

•Bubbling events

Travel up the containment hierarchy

•Tunnelling events

Travel down the containment hierarchy

Give you the chance to preview and possibly stop an event before it reaches the appropriate control

Usually named as Preview...

Page 23: NET Database Technologies: Introduction to WPF and Entity Framework DataBinding

Event tunnelling

• When an event (e.g. MouseDown) occurs in an element, a Preview event (PreviewMouseDown) starts at the root element and tunnels down to source

• If it is not marked as handled, then the actual event starts at the source and bubbles up towards the root in search of a handler

• See http://msdn.microsoft.com/en-gb/magazine/cc785480.aspx#id0190003

using Snoop (http://snoopwpf.codeplex.com/) using Snoop (http://snoopwpf.codeplex.com/)

in this case Button handles MouseDown event and raises its own Click event, which then bubbles up to element with handler attached

in this case Button handles MouseDown event and raises its own Click event, which then bubbles up to element with handler attached

Page 24: NET Database Technologies: Introduction to WPF and Entity Framework DataBinding

WPF command model

• May want the same action to be triggered in several different ways

e.g. Print menu item, Print button, Ctrl+P

• Need to add event handlers wherever they are needed

• What if we need to disable printing at some point

Need to disable controls and ignore shortcut at the right time

Can be difficult to manage and debug

• WPF command model makes this easier to manage

Delegates events to appropriate commands

Can attach the same command to multiple controls

Keeps enabled state of controls synchronised to command state

Page 25: NET Database Technologies: Introduction to WPF and Entity Framework DataBinding

Command model concepts

• Command - implements ICommand

Execute and CanExecute properties, CanExecuteChanged event

Represents a command, but does not contain code that performs the task

The Command Library is a basic library of common commands, like New, Save, Print, Copy, Paste

Can create custom commands

•Command Source – implements ICommandSource

Command, CommandTarget and CommandParameter properties

Button, MenuItem, etc are command sources

Page 26: NET Database Technologies: Introduction to WPF and Entity Framework DataBinding

Command model concepts

• CommandBinding

Command property, Executed and CanExecute events

Links a command to the related application logic (event handler)

• Command target

Element on which the command is being performed

e.g. a Paste command might insert text in a TextBox

The command source can explicitly set the command target

If the command target is not defined, the element with keyboard focus will be used as the command target

Some controls can handle command events on their own

• e.g. TextBox handles Cut, Paste and Copy

• Don’t need to write event handlers explicitly for these

Page 27: NET Database Technologies: Introduction to WPF and Entity Framework DataBinding

Command example

• Setting Command property of command sources, using library commands

TextBox will be command target when it has focusTextBox will be command target when it has focus

Page 28: NET Database Technologies: Introduction to WPF and Entity Framework DataBinding

Command example

• Setting command bindings in XAML

• Don’t need to set bindings for Cut, Paste, Copy as TextBox has event handlers for these built in

• Cut and Copy will be enabled when text is highlighted

Page 29: NET Database Technologies: Introduction to WPF and Entity Framework DataBinding

Command example

• Event handlers for commands

TextChanged event on target (Text Box) will cause CanExecute event on command binding to be fired, which is used here to update CanExecute property of Command

TextChanged event on target (Text Box) will cause CanExecute event on command binding to be fired, which is used here to update CanExecute property of Command

flag to indicate whether text box contains unsaved textflag to indicate whether text box contains unsaved text

Page 30: NET Database Technologies: Introduction to WPF and Entity Framework DataBinding

Binding

• Properties of controls can be automatically updated by properties of other controls or model objects

• Updates can be one-way or two way

Source object Target object

.NET property dependency property

INotifyPropertyChanged

binding

Page 31: NET Database Technologies: Introduction to WPF and Entity Framework DataBinding

Binding controls

Content property of Label (target) bound to Text property of TextBox (source)

Content property of Label (target) bound to Text property of TextBox (source)

Text property of TextBox (target) bound to Value property of Slider (source)

Text property of TextBox (target) bound to Value property of Slider (source)

Binding mode – changes cause updates both ways

Binding mode – changes cause updates both ways

Page 32: NET Database Technologies: Introduction to WPF and Entity Framework DataBinding

Binding modes

• One time

Source property updates target property once and only once

• One way

Source property always updates target property

• Two way

Source and target properties update each other – change one and the other changes

• One way to source

• Target property always updates source property

Page 33: NET Database Technologies: Introduction to WPF and Entity Framework DataBinding

Binding to an object

• Model class – simple Employee class

extra code to notify changes in property values for binding (details not shown)

extra code to notify changes in property values for binding (details not shown)

Page 34: NET Database Technologies: Introduction to WPF and Entity Framework DataBinding

Binding to an object

• XAML – TextBox is bound to Name property, as specified by binding Path

• Don’t specify source here – it will be the data context of the window

• Code-behind – create model object and set it as data context for window

Page 35: NET Database Technologies: Introduction to WPF and Entity Framework DataBinding

Binding to an object

• For two-way binding of objects to UI control, objects must implement INotifyPropertyChanged

• Properties must raise PropertyChanged event

• Collections should be of type ObservableCollection, which implements INotifyPropertyChanged and INotifyCollectionChanged

• This can introduce UI concerns into classes...

Page 36: NET Database Technologies: Introduction to WPF and Entity Framework DataBinding

Binding to data sources

• Source object for binding can be a data source, e.g:

Objects

Entity data

XML

• There are several ways of specifying binding source for an element:

Using the DataContext property on a parent element

• Useful when you are binding multiple properties to the same source

Specify the binding Source property on individual binding declarations

Specify the binding ElementName property to bind to another control

Page 37: NET Database Technologies: Introduction to WPF and Entity Framework DataBinding

Visual Studio and EF data sources

• Visual Studio allows you to drag-and-drop object data sources or EF entity sets onto the WPF designer

• Sets up Resources element to define data sources in XAML

• Generates code-behind to retrieve data from underlying data source

• Elements can bind to source as a StaticResource

• EF generated classes support WPF binding

Page 38: NET Database Technologies: Introduction to WPF and Entity Framework DataBinding

MVVM pattern

•Model-View-ViewModel

• WPF/Silverlight equivalent to the MVC (Model-View-Controller) and MVP (Model-View-Presenter) patterns used in ASP.NET

• Suitable for separation of concerns in rich, highly interactive user interfaces

• Fits well with WPF binding, command and templating infrastructure

Page 39: NET Database Technologies: Introduction to WPF and Entity Framework DataBinding

MVVM pattern

• Model

Domain class(es)

• View

XAML which contains elements to display data and/or react to user input

• ViewModel

Class which contains:

• Properties which correspond to the content or state required for UI elements

• Commands which correspond to the actions required to handle user input from UI elements

• Commands will typically use domain objects to perform business logic and update UI content or state

Page 40: NET Database Technologies: Introduction to WPF and Entity Framework DataBinding

MVVM binding

• MVVM works particularly well in WPF/Silverlight because of its powerful binding mechanism

• View elements bind to properties and/or commands defined in ViewModel

• ViewModel does not need to know explicitly about the corresponding View

• ViewModel defines UI state/behaviour, but does not have any dependency on a specific UI

• UI logic in ViewModel can be unit tested

• WPF templating allows detailed control over how the View displays the properties of the ViewModel

Page 41: NET Database Technologies: Introduction to WPF and Entity Framework DataBinding

MVVM binding

• ViewModel class is set as DataContext for View

ItemTemplate defines how properties of each item, of type Person, in ListBox should be displayed – here FirstName and LastName properties are displayed as text blocks in a stack panel

ItemTemplate defines how properties of each item, of type Person, in ListBox should be displayed – here FirstName and LastName properties are displayed as text blocks in a stack panel

ItemSource is bound to the Persons property of ViewModel, which is a collection of Person domain objects

ItemSource is bound to the Persons property of ViewModel, which is a collection of Person domain objects

Page 42: NET Database Technologies: Introduction to WPF and Entity Framework DataBinding

Further reading

•Drag & Drop Databinding with the Entity Framework and WPF

Julie Lerman

http://msdn.microsoft.com/en-us/data/gg610409

•Chapter 9: Programming Entity Framework

Julie Lerman (again!)

•Pro WPF in C# 2010

Matthew MacDonald

Apress


Top Related