net database technologies: introduction to wpf and entity framework databinding

of 42 /42
.NET Database Technologies: Introduction to WPF and Entity Framework DataBinding

Author: julie-hunt

Post on 11-Jan-2016




2 download

Embed Size (px)


  • .NET Database Technologies: Introduction to WPF and Entity Framework DataBinding

  • WPF rationaleUI layout and design separated from functionalityXML-based Markup language (XAML) for design, programming language (C#, VB, etc) for functionalityDesigners and developers can use separate specialised tools to work on the same project:Expression Blend for designersVisual Studio for developers

  • WPF rationaleSimilar 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 & JavaScriptASP.NET & C#

  • XAML controlsLayout controlscontainers for other controls to position them in the interface, , , etc.Interactive controls, ,, etc.Display controls,, , etcData controls, , etc.Application controls, , etc.

  • A simple WPF exampletext box user can type a question herebutton user clicks this to get advicetext box answer is shown here

  • XAML windowWindow defined in a XAML fileGrid control as a container

    other controls are defined here, inside controlGrid has 3 rows, middle row sized to fit contents, others expand to fill available space

  • Adding controls to a windowControls defined inside element

    Attributes control appearance of controls (fonts, margins, etc)Grid.Row attribute specifies which row of grid the control is displayed inname of method to handle click event

  • Code-behind fileContains a C# class which is derived from Window library classevent handler methodconstructorevent handler method uses a model class AdviceGenerator and sets Text property of the text box named txtAnswer

  • Applications and windowsApp.xaml is the startup file for a WPF project

    Code-behind contains an empty constructor by defaultSo where is the Main method?In autogenerated code in file App.g.cs in obj folderAdditional windows defined as separate XAML filesCan create an instance of code-behind class and call its Show method to open a new windowCan also design applications using a page-based modelwindow to open at startup

  • Code and visual designersWPF windows can be designed using visual design tools in Visual Studio and Expression BlendImportant to understand XAML code to get fine control over designPlan out layout using capabilities of layout controls rather than dragging controls from designer toolbox and positioning visuallyMakes it easy to provide layouts which adjust elegantly when window is resized

  • Layout controlsGridarranges its child controls in a tabular structureStack Panel, Wrap Panelstacks child elements below or beside each other, Wrap Panel wraps to new line if no spaceDock Paneldocks elements to left, right, top, bottom or centreCanvasElements positioned by coordinates, mainly used for 2D drawing

  • Alignment

    Enter Text


  • Margin and paddingThe Margin is the extra space around the controlThe Padding is extra space inside the controlThe Padding of an outer control is the Margin of an inner control








  • Laying out a gridRow and column definitionsSizes:Fixed: Fixed size) Auto: Takes as much space as needed by the contained control Star (*): Takes as much space as availablePosition 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 propertiesNormal .NET propertiesValue read directly from member field in classDependency propertiesResolved dynamically, e.g. by binding, allowing:Change notificationInheritance from parent elementsReduced memory footprint only store non-default valuesMany XAML control properties are dependency propertiesAttached propertiesAllow you to attach a value to an object that does not know anything about this valueA child element can store a value associated with a property defined on an parent element

  • Layout example

  • Layout example - Grid4 rows, 3 columns

  • Layout example - controlscan miss out Column=0

  • XAML routed eventsA typical WPFapplication 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 eventThe 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 encapsulationSingular handler attachment points

  • XAML routed eventsThis example has Button click handlers attached at different levels in the tree

  • Handling routed eventshandles Cancel button and sets Handled to true so that event does not bubble upother button events bubble up to Grid and are handled herethis will not happen as Cancel button event already handled

  • Types of eventActually, its a bit more complicated than that...There are three types of routed event:Direct eventsLike ordinary .NET events, originate in one element and do not pass to any otherBubbling eventsTravel up the containment hierarchyTunnelling eventsTravel down the containment hierarchyGive you the chance to preview and possibly stop an event before it reaches the appropriate controlUsually named as Preview...

  • Event tunnellingWhen an event (e.g. MouseDown) occurs in an element, a Preview event (PreviewMouseDown) starts at the root element and tunnels down to sourceIf 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 using Snoop ( this case Button handles MouseDown event and raises its own Click event, which then bubbles up to element with handler attached

  • WPF command modelMay want the same action to be triggered in several different wayse.g. Print menu item, Print button, Ctrl+PNeed to add event handlers wherever they are neededWhat if we need to disable printing at some pointNeed to disable controls and ignore shortcut at the right timeCan be difficult to manage and debugWPF command model makes this easier to manageDelegates events to appropriate commandsCan attach the same command to multiple controlsKeeps enabled state of controls synchronised to command state

  • Command model conceptsCommand - implements ICommandExecute and CanExecute properties, CanExecuteChanged eventRepresents a command, but does not contain code that performs the taskThe Command Library is a basic library of common commands, like New, Save, Print, Copy, PasteCan create custom commandsCommand Source implements ICommandSourceCommand, CommandTarget and CommandParameter propertiesButton, MenuItem, etc are command sources

  • Command model conceptsCommandBindingCommand property, Executed and CanExecute eventsLinks a command to the related application logic (event handler)Command target Element on which the command is being performede.g. a Paste command might insert text in a TextBoxThe command source can explicitly set the command targetIf the command target is not defined, the element with keyboard focus will be used as the command targetSome controls can handle command events on their owne.g. TextBox handles Cut, Paste and CopyDont need to write event handlers explicitly for these

  • Command exampleSetting Command property of command sources, using library commandsTextBox will be command target when it has focus

  • Command exampleSetting command bindings in XAML

    Dont need to set bindings for Cut, Paste, Copy as TextBox has event handlers for these built inCut and Copy will be enabled when text is highlighted

  • Command exampleEvent 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 Commandflag to indicate whether text box contains unsaved text

  • BindingProperties of controls can be automatically updated by properties of other controls or model objectsUpdates can be one-way or two way

    Source object

    Target object

    .NET property

    dependency property



  • Binding controlsContent property of Label (target) bound to Text property of TextBox (source)Text property of TextBox (target) bound to Value property of Slider (source)Binding mode changes cause updates both ways

  • Binding modesOne timeSource property updates target property once and only onceOne waySource property always updates target property Two waySource and target properties update each other change one and the other changesOne way to sourceTarget property always updates source property

  • Binding to an objectModel class simple Employee classextra code to notify changes in property values for binding (details not shown)

  • Binding to an objectXAML TextBox is bound to Name property, as specified by binding Path

    Dont specify source here it will be the data context of the windowCode-behind create model object and set it as data context for window

  • Binding to an objectFor two-way binding of objects to UI control, objects must implement INotifyPropertyChangedProperties must raise PropertyChanged eventCollections should be of type ObservableCollection, which implements INotifyPropertyChanged and INotifyCollectionChanged This can introduce UI concerns into classes...

  • Binding to data sourcesSource object for binding can be a data source, e.g:ObjectsEntity dataXMLThere 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 sourceSpecify the binding Source property on individual binding declarationsSpecify the binding ElementName property to bind to another control

  • Visual Studio and EF data sourcesVisual Studio allows you to drag-and-drop object data sources or EF entity sets onto the WPF designerSets up Resources element to define data sources in XAMLGenerates code-behind to retrieve data from underlying data sourceElements can bind to source as a StaticResource

    EF generated classes support WPF binding

  • MVVM patternModel-View-ViewModel WPF/Silverlight equivalent to the MVC (Model-View-Controller) and MVP (Model-View-Presenter) patterns used in ASP.NETSuitable for separation of concerns in rich, highly interactive user interfacesFits well with WPF binding, command and templating infrastructure

  • MVVM patternModelDomain class(es)ViewXAML which contains elements to display data and/or react to user inputViewModelClass which contains:Properties which correspond to the content or state required for UI elementsCommands which correspond to the actions required to handle user input from UI elementsCommands will typically use domain objects to perform business logic and update UI content or state

  • MVVM bindingMVVM works particularly well in WPF/Silverlight because of its powerful binding mechanismView elements bind to properties and/or commands defined in ViewModelViewModel does not need to know explicitly about the corresponding ViewViewModel defines UI state/behaviour, but does not have any dependency on a specific UIUI logic in ViewModel can be unit testedWPF templating allows detailed control over how the View displays the properties of the ViewModel

  • MVVM bindingViewModel class is set as DataContext for ViewItemTemplate 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 panelItemSource is bound to the Persons property of ViewModel, which is a collection of Person domain objects

  • Further readingDrag & Drop Databinding with the Entity Framework and WPFJulie Lerman 9: Programming Entity FrameworkJulie Lerman (again!)Pro WPF in C# 2010Matthew MacDonaldApress