MVVM Overview Frank Shoemaker MindCrafted Systems

Slides:



Advertisements
Similar presentations
Module 1: Creating an Application by Using Windows Presentation Foundation Overview of WPF Creating a Simple WPF Application Handling Events and Commands.
Advertisements

Expression Blend 4 – deep dive
Dinko Jakovljević Microsoft Student Partner | BambooLab
Microsoft Focus & Expertise We have a world-class team of Microsoft experts that can make any other platform integrate better with an existing enterprise.
VB Classes ISYS 573. Object-Oriented Concepts Abstraction: –To create a model of an object, for the purpose of determining the characteristics (properties)
Real world Windows Phone development Igor
Building Silverlight Applications Using the MVVM pattern An Introduction by Peter Messenger Senior Developer – Qmastor
Linq-to-Entities, Data Persisters, Master Datail Doncho Minkov Telerik School Academy Technical Trainer
Visual Basic Fundamental Concepts. Integrated Development Enviroment Generates startup form for new project on which to place controls. Features toolbox.
Visual Basic 2008 Express Edition The IDE. Visual Basic 2008 Express The Start Page Recent Projects Open an existing project Create a New Project.
JavaScript & jQuery the missing manual Chapter 11
READING, WRITING, BINDING, VALIDATING AND VISUALISING YOUR DATA Business value with Silverlight.
Programming with Visual Basic.NET An Object-Oriented Approach  Chapter 8 Introduction to Database Processing.
.NET Database Technologies: Introduction to WPF and Entity Framework DataBinding.
Navigating database with windows forms.. Tiered applications  Provide a means to develop many presentations of the same app  Makes changes to the back.
© Minder Chen, ASP.NET 2.0: Introduction - 1 ASP.NET 2.0 Minder Chen, Ph.D. Framework Base Class Library ADO.NET: Data & XML.
LiveCycle Data Services Introduction Part 2. Part 2? This is the second in our series on LiveCycle Data Services. If you missed our first presentation,
Session 08: Architecture Controllers or Managers Graphical User Interface (GUI) FEN AK - IT Softwarekonstruktion.
Adam Calderon – C# MVP Application Development Practice Lead Interknowlogy.
V 1.0 Programming III. Automatic notifications (…Changed, INofityPropertyChanged, ObservableCollection ) Data formatters Data conversions Resources.
Module 3: Working with Components. Overview An Introduction to Key.NET Framework Development Technologies Creating a Simple.NET Framework Component Creating.
Sample Application Multi Layered Architecture (n-tier): –Graphical User Interface (GUI): Forms, components, controls The Visual Designer in Visual Studio.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Unit 3: Adding Code to a Microsoft ASP.NET Web Form.
Windows Phone MVVM and Unit Testing Step by Step Andy Wigley Windows Phone Development MVP, Mobile Software Consultant APPA Mundi Ltd WPH208.
1 CS 3870/CS 5870: Note 07 Lab 3 Lab 4 Test 1: Two Tables.
CIS 338: Classes and Modules Dr. Ralph D. Westfall May, 2011.
Object Oriented Software Development 10. Persistent Storage.
Windows Forms Navigating database with windows forms.
Copyright ©2004 Virtusa Corporation | CONFIDENTIAL Windows Workflow Foundation Ruwan Wijesinghe.
3.2 VB.NET Events An Event Procedure Properties and Event Procedures of the Form Tab Order of Controls Exercises.
Visual Basic.NET Programming March 3, Agenda Questions / Discussion Cookies Project Work (Ends Around 9:00 PM) Demo's (15 minutes per team)
Nikhil Kothari Software Architect Microsoft Corporation Session Code: WUX312.
Christopher M. Pascucci.NET Programming: WebForm Events.
1 Catching up on Rich Clients (round 1) Mike Ormond, Mike Taulty Developer & Platform Group Microsoft Ltd
Ajax and the GWT. Ajax  Asynchronous JavaScript And XML  Technology behind interactive web sites  Provide smoother experience than conventional web.
3 private void equalsButton_Click( object sender, RoutedEventArgs e) { calculateResult(); }
1 CS 3870/CS 5870: Note 16 Web User Controls. Prog 7 Copy Prog6 to Prog7 Modify all files for Prog7 Remove Web.config from sub-folders Make sure Prog7.
Slide 1. Agenda  Introduction to Windows Workflow What is it? What are activities? Hosting  Out of the box Activities  Custom Activities and Dependency.
Architecture Multi Layered Architecture (n-tier): Application: Model Controllers Database Access Graphical User Interface (GUI): Forms, components, controls.
04 |Sharing Code Between Windows 8 and Windows Phone 8 in Visual Studio Ben Riga
V 1.0 Programming III. Automatic notifications with data binding (…Changed, INofityPropertyChanged, ObservableCollection, DataTemplate) Data formatters.
Overview of Previous Lesson(s) Over View  ASP is a technology that enables scripts in web pages to be executed by an Internet server.  ASP.NET is a.
Java Beans - Basics CIS 421 Web-based Java Programming.
The Windows Forms DataGrid A Complex-Bound.NET GUI Control Mike FITZSIMON SYSTEMSARCHITECT F ITZSIMON IT C ONSULTING PTY LTD.
Model View ViewModel Architecture. MVVM Architecture components.
Module 9. Dealing with Generalization Course: Refactoring.
MVVM Pattern Mahender Senior Software Engineer United Health Group.
Windows 8 apps and the MVVM pattern SILVERLIGHTSHOW.NET WEBINARS SERIES GILL CLEEREN, October 16 th
Programming with MVVM Miguel A. Castro Architect -
Data Binding, Binding Properties Doncho Minkov Telerik School Academy Technical Trainer
Adam Schultz MVVM and WPF. MVVM Model, View, ViewModel A software architecture designed to separate out User Interface design, Business Logic, and Data.
Jim Fawcett CSE686 – Internet Programming Spring 2014
In Windows 8 Store Applications
Real world Windows Phone development
A variable is a name for a value stored in memory.
MVVM Made Simple with Prism
Jim Fawcett CSE681 – SW Modeling & Analysis Fall 2014
Jim Fawcett CSE686 – Internet Programming Spring 2012
Ben Riga 02 | Basics of View Models Ben Riga
Jim Fawcett CSE775 – Distributed Objects Spring 2011
Miguel A. Castro Architect IDesign
VB.NET Using Database.
Introduction to the MVVM Pattern
An introduction to MVVM using WPF NISCHAL S
Tech Ed North America /1/2018 4:27 PM Required Slide
Page Navigation and Data Binding in Windows Runtime Apps
What’s new for Windows 8 Devs Part 2
Tonga Institute of Higher Education
Tech Ed North America /6/2019 2:07 PM Required Slide
An Introduction to the Model-View-ViewModel Pattern
Presentation transcript:

MVVM Overview Frank Shoemaker MindCrafted Systems

Some background Some examples Overview of MVVM

MVVM stands for M odel V iew V iew- M odel MVVM

Simple Case

Typical class that covers a database Could be a WCF Service and its client reference Model

Provides data to and from the View Responds to both the View and the Model Informs the View of changes in the data Reusable (at least much more than code behind a form) ViewModel

Knows nothing about the View Does not push data into the view TextBox1.Text = object.Name() ViewModel

Uses Binding to subscribe to the ViewModel Interprets business data and state of ViewModel to the human Nothing but Presentation - XAML No or minimal code-behind View

WPF/Silverlight data binding is what makes things work ViewModel presents a published interface to the View Binding in the XAML instead of code More use of Declarative Programming More on the ViewModel in MVVM

Architecture

Existing Stuff Database Tables

Existing Stuff Library Class

WPF

Business data Properties Properties to return Select lists (AllSelect and StatusSelect) The usual CRUD routines Model Class

Encapsulates how it communications with the back-end Uses Events to signal I/O successfully completed or an error occurred In WPF its synchronous, but can be used as if its a asynchronous. In Silverlight its async. Model Class

Public Sub Read(ByVal id As Integer) Try myLibraryObj.MCFetch(id) RaiseEvent IOSuccessful("Read", New EventArgs()) Catch ex As Exception RaiseEvent IOErrorOccurred("Read", ex) End Try End Sub Model Class – I/O WPF - Synchronous

Public Sub Read(ByVal id As Integer) Try myService.FetchAsync(id, ServiceReference1.myContextPayloadType.Heavy) Catch ex As Exception RaiseEvent IOErrorOccurred("Read", ex) End Try End Sub Model Class – I/O Silverlight - Asynch

Private Sub Read_Completed(ByVal sender As System.Object, ByVal e As ServiceReference1.FetchCompletedEventArgs) Handles myService.FetchCompleted If IsNothing(e.Error) Then myData = e.Result RaiseEvent IOSuccessful("Read", New EventArgs()) Else RaiseEvent IOErrorOccurred("Read", e.Error) End If End Sub Model Class – I/O Silverlight - Asynch

Properties come in two flavors Data Properties Name, StatusID, CreateDate, AllSelect Form State properties IsEditing, IsNotEditing, IsOKToBeginEdit ViewModel Properties

Methods come in two flavors CRUD Methods Create, Read, Update, Delete Implements the IEditableObject interface BeginEdit, CancelEdit, EndEdit ViewModel Methods

Implements INotifyPropertyChanged interface Notify the View that a property has changed its value Allows the View to respond to reflect the change, if it wants to ViewModel Class Events

Present some properties in more than one way for the convenience of the View IsEditing True if the user is currently editing the business object IsNotEditing True if the user is NOT currently editing the business object. ViewModel Class Properties

DataContext Binding Gluing the Pieces Together

This example sets up the DataContext in code Create a new instance of the ViewModel Bind the View to the ViewModel Instance All Controls on the View then inherit the DataContext from the page. Setup the DataContext

Private Sub Page_Loaded (ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) myVM = New ViewModel.DepartmentVM() ' Set the DataContext for the ' entire page to the ViewModel Me.DataContext = myVM End Sub Set up the DataContext

Public Event PropertyChanged(ByVal sender As Object, ByVal e As PropertyChangedEventArgs) _ Implements INotifyPropertyChanged.PropertyChanged Data Binding - ViewModel INotifyPropertyChanged

Public Property CreatedBy() As String Get Return myModel.CreatedBy End Get Set(ByVal value As String) myModel.CreatedBy = value RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("CreatedBy")) End Set End Property Data Binding - ViewModel Deparment.CreatedBy

< TextBox Text="{Binding Path=CreateDate, Mode=OneWay }"... Path is within the DataContext Mode=OneWay means the control wont update the ViewModel Since its bound to CreateDate, when the PropertyChanged event is raised the control reloads from the CreateDate property in the ViewModel Controls dont need to be named Data Binding - View Deparment.CreatedBy

<TextBox Text="{Binding Path=Name, Mode=TwoWay, IsEnabled="{Binding Path=IsEditing}"... Binding to interpret the ViewModels state to the user. Binding For State

<Button Name="Edit" Content="Edit" IsEnabled="{Binding Path=IsOKToBeginEdit}" Click="Edit_Begin"... <Button Name="Save" Content="Save" IsEnabled="{Binding Path=IsEditing}" Click="Edit_Save"... <Button Name="Cancel" Content="Cancel" IsEnabled="{Binding Path=IsEditing}" Click="Edit_Cancel"... Binding for State

<TextBox Text="{Binding Path=Name, Mode=TwoWay,... Bi-directional binding. TwoWay Data Bindning

<TextBox Text="{Binding Path=Name, Mode=TwoWay, ValidatesOnExceptions=True}"... When the ViewModel throws the exception, the View changes Validating in the ViewModel

... <Setter Property="Validation.ErrorTemplate" Value="{StaticResource errorEyeCatcher}"/> <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}"/> Setting up Styles for Validation Binding

Setting up Styles for Validation Binding

<TextBox Text="{Binding Path=Name, Mode=TwoWay, UpdateSourceTrigger=LostFocus, ValidatesOnExceptions=True}" IsEnabled="{Binding Path=IsEditing}"... When to Validate?

<ComboBox ItemsSource="{Binding Path=StatusSelect}" DisplayMemberPath="Value" SelectedValuePath="Key" SelectedValue="{Binding Path=StatusID, Mode=TwoWay}"... ComboBox Binding

The state of Editing is maintained by the ViewModel ViewModel exposes properties to indicate state View interprets the ViewModels state to the user Data Binding ViewModel.FormStateMessage

<TextBlock Text="{Binding Path=FormStateMessage}"... Displaying the Status Message

<TextBlock Text="{Binding Path=FormStateMessage}" Foreground="{Binding Path=FormStateMessageType, Converter={StaticResource MessageForegroundColor}, ConverterParameter=FormStateMessageType}"... Use a converter routine to transform integer from the ViewModel into a color on theTextBox Binding to Change Color of the Message if its an Error

Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) _ As Object Implements System.Windows.Data.IValueConverter.Convert If CInt(value) = 1 Then ' Informational message Return "Black" Else ' Error message Return "Red" End If End Function Converter Routine

Setup the Converter Routine as a Resource in the XAML

Since ViewModels know nothing about the UI, they can be driven with a programmatic test case. Testing

Loose coupling between the Model, ViewModel, and View Bright lines between areas of concerns At least some chance of reusability of the ViewModel ViewModel is independently testable MVVM Wrap up

View can be worked on by designers without messing up the ViewModel Would benefit from a root ViewModel class for the state management. MVVM Wrap up