WPF and Entity Framework DataBinding

advertisement
.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
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#
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.
A simple WPF example
text box – user can
type a question here
button – user clicks
this to get advice
text box – answer is
shown here
XAML window
• Window defined in a XAML file
• Grid control as a container
Grid has 3 rows, middle row
sized to fit contents, others
expand to fill available space
other controls are defined here, inside <Grid> control
Adding controls to a window
• Controls defined inside <Grid> element
name of method to handle click event
Grid.Row attribute
specifies which row of
grid the control is
displayed in
Attributes control appearance of controls (fonts, margins, etc)
Code-behind file
• Contains a C# class which is derived from Window library
class
constructor
event handler method
event handler method uses a model class
AdviceGenerator and sets Text property of the text box
named txtAnswer
Applications and windows
• App.xaml is the startup file for a WPF project
window to open at startup
• 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
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
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
Alignment
Horizontal Alignment
Vertical Alignment
Left
Center
Right
Stretch
Button
Button
Button
Button
Button
Button
Button
Button
Button
Button
Button
Button
Button
Button
Button
Button
Top
Center
Bottom
Stretch
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
Padding
OK
OK
Cancel
OK
Margin
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
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
Layout example
Layout example - Grid
4 rows, 3 columns
Layout example - controls
can miss out Column=“0”
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
XAML routed events
• This example has Button click handlers attached at
different levels in the tree
Handling routed events
other button events
bubble up to Grid and
are handled here
this will not happen as
Cancel button event
already handled
handles Cancel button
and sets Handled to true
so that event does not
bubble up
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...
Event tunnelling
using Snoop (http://snoopwpf.codeplex.com/)
• 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
in this case Button handles MouseDown event
and raises its own Click event, which then
bubbles up to element with handler attached
• See http://msdn.microsoft.com/en-
gb/magazine/cc785480.aspx#id0190
003
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
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
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
Command example
• Setting Command property of command sources, using
library commands
TextBox will be command
target when it has focus
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
Command example
• Event handlers for commands
flag to indicate whether text box contains
unsaved text
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
Binding
• Properties of controls can be automatically updated by
properties of other controls or model objects
• Updates can be one-way or two way
INotifyPropertyChanged
Source object
.NET property
Target object
binding
dependency property
Binding controls
Content property of
Label (target) bound to
Text property of
TextBox (source)
Binding mode –
changes cause updates
both ways
Text property of
TextBox (target) bound
to Value property of
Slider (source)
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
Binding to an object
• Model class – simple Employee class
extra code to notify
changes in property
values for binding
(details not shown)
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
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...
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
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
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
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
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
MVVM binding
• ViewModel class is set as DataContext for View
ItemSource is bound to the
Persons property of ViewModel,
which is a collection of Person
domain objects
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
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
Download