SlideShare ist ein Scribd-Unternehmen logo
1 von 34
or How I Learned to Stop Worrying and Love the Binding Bryan Anderson MVVM in the Real World
Vocabulary Presentation Model pattern MVVM Architecture Compare MVVM to MVC Religious Fights Common Issues & Solutions What am I going to talk about?
//Notifies clients that a property value has changed. publicinterfaceINotifyPropertyChanged {     //Occurs when a property value changes. eventPropertyChangedEventHandler PropertyChanged; } INotifyPropertyChanged
//Notifies listeners of dynamic changes, such as when items get //added and removedor the whole list is refreshed. publicinterfaceINotifyCollectionChanged {     //Occurs when the collection changes.     eventNotifyCollectionChangedEventHandler CollectionChanged; } //Describes the action that caused a CollectionChangedevent. publicenumNotifyCollectionChangedAction {     Add, Remove, Replace, Move, Reset } INotifyCollectionChanged
Keeps data in two properties “bound” together Allows data to flow in either or both directions Uses PropertyChanged & CollectionChanged to keep values updated Data Binding
Implements IValueConverter or IMultiValueConverter object Convert(object value, Type targetType, object parameter, CultureInfo culture) object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) Converts inputs from one value to another and back Used extensively in data binding Value Converter
Looks like a standard CLR property on the class’s interface Adds additional infrastructure features like Data Binding Change Notification Value Coercion Used extensively by WPF and Silverlight to create fast, reactive user interfaces Dependency Property
Groups a related set of controls Reduces repetition – DRYer Has its own code behind – allows new dependency properties User Control
An implementation of the Command Pattern In WPF & Silverlight the ICommand interface is used to define a class that represents a command bool CanExecute(object parameter) void Execute(object parameter) event EventHandler CanExecuteChanged Frequently implemented by creating a DelegateCommand class Commands
INotifyPropertyChanged INotifyCollectionChanged Data Binding Value Converter Dependency Property User Control Commands Questions?
Guide the separation of concerns Encapsulate what changes UI Web services Databases Anything else that interfaces with something outside the application The Purpose of Architecture Patterns
Separate presentation from functionality Testability Consistency Maintainability Allow a combined Blend/Visual Studio workflow Goals of the Presentation Model
Abstract Pattern that defines a family of platform/framework specific patterns MVVM – WPF, Silverlight MVC – Web MVP – Winforms Designed to pull the state and behavior out of the View into a more stable and testable layer Presentation Model View Presentation Model Model
Abstract Pattern that defines a family of platform/framework specific patterns MVVM – WPF, Silverlight MVC – Web MVP – Winforms Designed to pull the state and behavior out of the View into a more stable and testable layer Presentation Model View Presentation Model Model
MVVM Architecture – Model Responsible for business logic Interacts with persistent storage, e.g. database, web services, files, etc. Capable of being shared among related applications  View Unit Tests View Model Model File System Web Services Database
MVVM Architecture – View Model Should be thought of as an Abstract View Exposes properties and commands for use in a View Gets data from the Model and updates it according to property changes and command calls View Unit Tests View Model Model File System Web Services Database
MVVM Architecture - View Presents data to the user Handles input Interacts with the View Model by data binding to properties and commands Should contain no logic that isn’t entirely a view concern, e.g. which screen to show View Unit Tests View Model Model File System Web Services Database
MVVM Architecture - Tests Acts as another View Interacts with the Model and View Model to ensure correct behavior Provide an early warning that the architecture isn’t correct If testing is difficult, coupling is too high or concerns aren’t separated View Unit Tests View Model Model File System Web Services Database
The Model holds data and handles business logic The Controller receives input and makes changes to the View and Model accordingly The View renders the Model into a form suitable for interaction MVC Controller Model View
Religious Fights
Multiple, mutually exclusive options People form strong opinions and will argue the benefits of their choice for all eternity Each side has its own benefits and drawbacks A decision needs to be made before the “correct choice” can be determined In the end it comes down to a combination of reason and instinct Religious Fights
View Model Driven Allows more complete testing of logic to open new Views/View Models Tends to be DRYer as applications grow More difficult to use in Silverlight projects Religious Fights – Round 1 View Driven Easy to track which View Model is used by a View Much easier to use when sharing code between WPF and Silverlight Difficult or confusing for a single View to be used with multiple View Models
How much code should I actually have in the View’s code behind? Value converters are fine as long as they’re only converting values User Control code behind should only contain Dependency Property definitions and rare view-specific event handlers DataTemplateSelectors as long as their code is limited to choosing between DataTemplates Otherwise there should be no code-behind Religious Fights – Round 2
Should the View be allowed to use/display a Model class directly or should all interactions be through the View Model? The View should never edit a Model instance My rule of thumb – Only allow the view to display immutable Model objects, even then try to avoid it It should be considered technical debt if done, but it’s a relatively harmless area to take on debt Religious Fights – Round 3
Where should INotifyPropertyChanged and INotifyCollectionChanged be used? Definitely in the View Model Occasionally in the View - usually in Custom Controls and more rarely User Controls It’s becoming more accepted to them in the Model unless added to push updates to a View Religious Fights – Round 4
Notifying users from a View Model, i.e. How do I show a message box? How do I handle non-command events without code behind? Something should or should not be shown based on state. What goes in the View vs. View Model? Should I use an additional property or the command parameter to pass contextual data to a View Model’s command? View Models seem to copy all of my Model’s properties Common Issues & Solutions
Message boxes are annoying Notifying users from a View Model
Message boxes are annoying Messages to the user are useful Use a mediator – Allows you to aggregate messages from all of your VMs, log them, and display them. Also easy to test. If you only need it in one or two places an Error/Notification property or, more rarely, event works well. Implement the IDataErrorInfo interface for notifications related to property validation Notifying users from a View Model
Usually done using an attached behavior, search for “Attached Command Behavior” Can it be handled by binding?  If absolutely necessary and there’s no logic involved it can be put into code behind. Handling events without code behind
Code Behind & Gotos http://xkcd.com/292 Beware of Raptor Attacks
Is it a View-only concern? E.g. Master/Detail view Bind the detail view to the selected master item Is it a View Model concern? E.g. IsEditMode Use a DataTemplateSelector if available to switch Views Use Triggers, Visual State Manager, or another method to switch views based on the View Model properties Is it a combination? E.g. IsBusy Use the Visual State Manager if available Visibility based on state, what goes in the View vs. View Model?
Would the property be referenced anywhere outside of the command(s)? Does the property make sense in the context of the View Model’s interface?  Is the command used in multiple places that would need to set the property to different objects? Property or command parameter?
View Models are not just Façades or Adapters for Model classes View Models are not the code behind for a View View Models are an Abstract View or the Model for a View  View Models will present multiple Models and multiple View Models might use the same Model View Models just copy my Models
I love feedback! Bryan Anderson bryan.anderson@ilmservice.com @SolaAesir Questions?

Weitere Àhnliche Inhalte

Was ist angesagt?

Mvc pattern and implementation in java fair
Mvc   pattern   and implementation   in   java fairMvc   pattern   and implementation   in   java fair
Mvc pattern and implementation in java fair
Tech_MX
 
MVC
MVCMVC
MVC
akshin
 
Jsp with mvc
Jsp with mvcJsp with mvc
Jsp with mvc
vamsitricks
 

Was ist angesagt? (20)

MVC(Model View Controller),Web,Enterprise,Mobile
MVC(Model View Controller),Web,Enterprise,MobileMVC(Model View Controller),Web,Enterprise,Mobile
MVC(Model View Controller),Web,Enterprise,Mobile
 
Ppt of Basic MVC Structure
Ppt of Basic MVC StructurePpt of Basic MVC Structure
Ppt of Basic MVC Structure
 
MVC
MVCMVC
MVC
 
Mvc pattern and implementation in java fair
Mvc   pattern   and implementation   in   java fairMvc   pattern   and implementation   in   java fair
Mvc pattern and implementation in java fair
 
Just a View: An Introduction To Model-View-Controller Pattern
Just a View:  An Introduction To Model-View-Controller PatternJust a View:  An Introduction To Model-View-Controller Pattern
Just a View: An Introduction To Model-View-Controller Pattern
 
Web engineering - MVC
Web engineering - MVCWeb engineering - MVC
Web engineering - MVC
 
Design Patterns in ZK: Java MVVM as Model-View-Binder
Design Patterns in ZK: Java MVVM as Model-View-BinderDesign Patterns in ZK: Java MVVM as Model-View-Binder
Design Patterns in ZK: Java MVVM as Model-View-Binder
 
MVC
MVCMVC
MVC
 
Mvc, mvp & mvvm (erp)
Mvc, mvp & mvvm (erp)Mvc, mvp & mvvm (erp)
Mvc, mvp & mvvm (erp)
 
MVVM in iOS presentation
MVVM in iOS presentationMVVM in iOS presentation
MVVM in iOS presentation
 
Model view controller (mvc)
Model view controller (mvc)Model view controller (mvc)
Model view controller (mvc)
 
Model View Controller (MVC)
Model View Controller (MVC)Model View Controller (MVC)
Model View Controller (MVC)
 
Mvc fundamental
Mvc fundamentalMvc fundamental
Mvc fundamental
 
MVC Framework
MVC FrameworkMVC Framework
MVC Framework
 
Model viewviewmodel2
Model viewviewmodel2Model viewviewmodel2
Model viewviewmodel2
 
當ZK遇芋Front-End
當ZK遇芋Front-End當ZK遇芋Front-End
當ZK遇芋Front-End
 
Why Use MVC?
Why Use MVC?Why Use MVC?
Why Use MVC?
 
Jsp with mvc
Jsp with mvcJsp with mvc
Jsp with mvc
 
Portable Class Libraries and MVVM
Portable Class Libraries and MVVMPortable Class Libraries and MVVM
Portable Class Libraries and MVVM
 
Structuring a Client-Side App
Structuring a Client-Side AppStructuring a Client-Side App
Structuring a Client-Side App
 

Andere mochten auch

Enhancing user experiences with reactive extensions tccc10
Enhancing user experiences with reactive extensions   tccc10Enhancing user experiences with reactive extensions   tccc10
Enhancing user experiences with reactive extensions tccc10
Bryan Anderson
 

Andere mochten auch (6)

MVVM ĐČ WinForms – DevExpress Way (Ń‚Đ”ĐŸŃ€ĐžŃ Đž праĐșтоĐșĐ°)
MVVM ĐČ WinForms – DevExpress Way (Ń‚Đ”ĐŸŃ€ĐžŃ Đž праĐșтоĐșĐ°)MVVM ĐČ WinForms – DevExpress Way (Ń‚Đ”ĐŸŃ€ĐžŃ Đž праĐșтоĐșĐ°)
MVVM ĐČ WinForms – DevExpress Way (Ń‚Đ”ĐŸŃ€ĐžŃ Đž праĐșтоĐșĐ°)
 
Enhancing user experiences with reactive extensions tccc10
Enhancing user experiences with reactive extensions   tccc10Enhancing user experiences with reactive extensions   tccc10
Enhancing user experiences with reactive extensions tccc10
 
The impact of innovation on travel and tourism industries (World Travel Marke...
The impact of innovation on travel and tourism industries (World Travel Marke...The impact of innovation on travel and tourism industries (World Travel Marke...
The impact of innovation on travel and tourism industries (World Travel Marke...
 
Open Source Creativity
Open Source CreativityOpen Source Creativity
Open Source Creativity
 
Reuters: Pictures of the Year 2016 (Part 2)
Reuters: Pictures of the Year 2016 (Part 2)Reuters: Pictures of the Year 2016 (Part 2)
Reuters: Pictures of the Year 2016 (Part 2)
 
The Outcome Economy
The Outcome EconomyThe Outcome Economy
The Outcome Economy
 

Ähnlich wie Mvvm in the real world tccc10

Building an enterprise app in silverlight 4 and NHibernate
Building an enterprise app in silverlight 4 and NHibernateBuilding an enterprise app in silverlight 4 and NHibernate
Building an enterprise app in silverlight 4 and NHibernate
bwullems
 
Model View ViewModel
Model View ViewModelModel View ViewModel
Model View ViewModel
Doncho Minkov
 
Stephen Kennedy Silverlight 3 Deep Dive
Stephen Kennedy Silverlight 3 Deep DiveStephen Kennedy Silverlight 3 Deep Dive
Stephen Kennedy Silverlight 3 Deep Dive
MicrosoftFeed
 

Ähnlich wie Mvvm in the real world tccc10 (20)

Training: MVVM Pattern
Training: MVVM PatternTraining: MVVM Pattern
Training: MVVM Pattern
 
WPF with MVVM: From the Trenches
WPF with MVVM: From the TrenchesWPF with MVVM: From the Trenches
WPF with MVVM: From the Trenches
 
Building an enterprise app in silverlight 4 and NHibernate
Building an enterprise app in silverlight 4 and NHibernateBuilding an enterprise app in silverlight 4 and NHibernate
Building an enterprise app in silverlight 4 and NHibernate
 
Model View ViewModel
Model View ViewModelModel View ViewModel
Model View ViewModel
 
Introduction To MVVM
Introduction To MVVMIntroduction To MVVM
Introduction To MVVM
 
Mvvw patterns
Mvvw patternsMvvw patterns
Mvvw patterns
 
J2EE pattern 5
J2EE pattern 5J2EE pattern 5
J2EE pattern 5
 
ASP.MVC Training
ASP.MVC TrainingASP.MVC Training
ASP.MVC Training
 
SOLID Principles and The Clean Architecture
SOLID Principles and The Clean ArchitectureSOLID Principles and The Clean Architecture
SOLID Principles and The Clean Architecture
 
MVC Pattern. Flex implementation of MVC
MVC Pattern. Flex implementation of MVCMVC Pattern. Flex implementation of MVC
MVC Pattern. Flex implementation of MVC
 
Stephen Kennedy Silverlight 3 Deep Dive
Stephen Kennedy Silverlight 3 Deep DiveStephen Kennedy Silverlight 3 Deep Dive
Stephen Kennedy Silverlight 3 Deep Dive
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentation
 
Porting the Legacy Application to Composite Application Guidance
Porting the Legacy Application to Composite Application GuidancePorting the Legacy Application to Composite Application Guidance
Porting the Legacy Application to Composite Application Guidance
 
Deep Dive: MVC Controller Architecture
Deep Dive: MVC Controller ArchitectureDeep Dive: MVC Controller Architecture
Deep Dive: MVC Controller Architecture
 
Architectural Design Pattern: Android
Architectural Design Pattern: AndroidArchitectural Design Pattern: Android
Architectural Design Pattern: Android
 
Code Camp 06 Model View Presenter Architecture
Code Camp 06   Model View Presenter ArchitectureCode Camp 06   Model View Presenter Architecture
Code Camp 06 Model View Presenter Architecture
 
рДалОО ĐžŃĐżĐŸĐ»ŃŒĐ·ĐŸĐČĐ°ĐœĐžŃ Mv ĐČ i os Ń€Đ°Đ·Ń€Đ°Đ±ĐŸŃ‚ĐșĐ”
рДалОО ĐžŃĐżĐŸĐ»ŃŒĐ·ĐŸĐČĐ°ĐœĐžŃ Mv ĐČ i os Ń€Đ°Đ·Ń€Đ°Đ±ĐŸŃ‚ĐșДрДалОО ĐžŃĐżĐŸĐ»ŃŒĐ·ĐŸĐČĐ°ĐœĐžŃ Mv ĐČ i os Ń€Đ°Đ·Ń€Đ°Đ±ĐŸŃ‚ĐșĐ”
рДалОО ĐžŃĐżĐŸĐ»ŃŒĐ·ĐŸĐČĐ°ĐœĐžŃ Mv ĐČ i os Ń€Đ°Đ·Ń€Đ°Đ±ĐŸŃ‚ĐșĐ”
 
MVC in PHP
MVC in PHPMVC in PHP
MVC in PHP
 
Adopting MVVM
Adopting MVVMAdopting MVVM
Adopting MVVM
 
MVVM+MEF in Silvelight - W 2010ebday
MVVM+MEF in Silvelight - W 2010ebdayMVVM+MEF in Silvelight - W 2010ebday
MVVM+MEF in Silvelight - W 2010ebday
 

KĂŒrzlich hochgeladen

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

KĂŒrzlich hochgeladen (20)

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 

Mvvm in the real world tccc10

  • 1. or How I Learned to Stop Worrying and Love the Binding Bryan Anderson MVVM in the Real World
  • 2. Vocabulary Presentation Model pattern MVVM Architecture Compare MVVM to MVC Religious Fights Common Issues & Solutions What am I going to talk about?
  • 3. //Notifies clients that a property value has changed. publicinterfaceINotifyPropertyChanged { //Occurs when a property value changes. eventPropertyChangedEventHandler PropertyChanged; } INotifyPropertyChanged
  • 4. //Notifies listeners of dynamic changes, such as when items get //added and removedor the whole list is refreshed. publicinterfaceINotifyCollectionChanged { //Occurs when the collection changes. eventNotifyCollectionChangedEventHandler CollectionChanged; } //Describes the action that caused a CollectionChangedevent. publicenumNotifyCollectionChangedAction { Add, Remove, Replace, Move, Reset } INotifyCollectionChanged
  • 5. Keeps data in two properties “bound” together Allows data to flow in either or both directions Uses PropertyChanged & CollectionChanged to keep values updated Data Binding
  • 6. Implements IValueConverter or IMultiValueConverter object Convert(object value, Type targetType, object parameter, CultureInfo culture) object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) Converts inputs from one value to another and back Used extensively in data binding Value Converter
  • 7. Looks like a standard CLR property on the class’s interface Adds additional infrastructure features like Data Binding Change Notification Value Coercion Used extensively by WPF and Silverlight to create fast, reactive user interfaces Dependency Property
  • 8. Groups a related set of controls Reduces repetition – DRYer Has its own code behind – allows new dependency properties User Control
  • 9. An implementation of the Command Pattern In WPF & Silverlight the ICommand interface is used to define a class that represents a command bool CanExecute(object parameter) void Execute(object parameter) event EventHandler CanExecuteChanged Frequently implemented by creating a DelegateCommand class Commands
  • 10. INotifyPropertyChanged INotifyCollectionChanged Data Binding Value Converter Dependency Property User Control Commands Questions?
  • 11. Guide the separation of concerns Encapsulate what changes UI Web services Databases Anything else that interfaces with something outside the application The Purpose of Architecture Patterns
  • 12. Separate presentation from functionality Testability Consistency Maintainability Allow a combined Blend/Visual Studio workflow Goals of the Presentation Model
  • 13. Abstract Pattern that defines a family of platform/framework specific patterns MVVM – WPF, Silverlight MVC – Web MVP – Winforms Designed to pull the state and behavior out of the View into a more stable and testable layer Presentation Model View Presentation Model Model
  • 14. Abstract Pattern that defines a family of platform/framework specific patterns MVVM – WPF, Silverlight MVC – Web MVP – Winforms Designed to pull the state and behavior out of the View into a more stable and testable layer Presentation Model View Presentation Model Model
  • 15. MVVM Architecture – Model Responsible for business logic Interacts with persistent storage, e.g. database, web services, files, etc. Capable of being shared among related applications View Unit Tests View Model Model File System Web Services Database
  • 16. MVVM Architecture – View Model Should be thought of as an Abstract View Exposes properties and commands for use in a View Gets data from the Model and updates it according to property changes and command calls View Unit Tests View Model Model File System Web Services Database
  • 17. MVVM Architecture - View Presents data to the user Handles input Interacts with the View Model by data binding to properties and commands Should contain no logic that isn’t entirely a view concern, e.g. which screen to show View Unit Tests View Model Model File System Web Services Database
  • 18. MVVM Architecture - Tests Acts as another View Interacts with the Model and View Model to ensure correct behavior Provide an early warning that the architecture isn’t correct If testing is difficult, coupling is too high or concerns aren’t separated View Unit Tests View Model Model File System Web Services Database
  • 19. The Model holds data and handles business logic The Controller receives input and makes changes to the View and Model accordingly The View renders the Model into a form suitable for interaction MVC Controller Model View
  • 21. Multiple, mutually exclusive options People form strong opinions and will argue the benefits of their choice for all eternity Each side has its own benefits and drawbacks A decision needs to be made before the “correct choice” can be determined In the end it comes down to a combination of reason and instinct Religious Fights
  • 22. View Model Driven Allows more complete testing of logic to open new Views/View Models Tends to be DRYer as applications grow More difficult to use in Silverlight projects Religious Fights – Round 1 View Driven Easy to track which View Model is used by a View Much easier to use when sharing code between WPF and Silverlight Difficult or confusing for a single View to be used with multiple View Models
  • 23. How much code should I actually have in the View’s code behind? Value converters are fine as long as they’re only converting values User Control code behind should only contain Dependency Property definitions and rare view-specific event handlers DataTemplateSelectors as long as their code is limited to choosing between DataTemplates Otherwise there should be no code-behind Religious Fights – Round 2
  • 24. Should the View be allowed to use/display a Model class directly or should all interactions be through the View Model? The View should never edit a Model instance My rule of thumb – Only allow the view to display immutable Model objects, even then try to avoid it It should be considered technical debt if done, but it’s a relatively harmless area to take on debt Religious Fights – Round 3
  • 25. Where should INotifyPropertyChanged and INotifyCollectionChanged be used? Definitely in the View Model Occasionally in the View - usually in Custom Controls and more rarely User Controls It’s becoming more accepted to them in the Model unless added to push updates to a View Religious Fights – Round 4
  • 26. Notifying users from a View Model, i.e. How do I show a message box? How do I handle non-command events without code behind? Something should or should not be shown based on state. What goes in the View vs. View Model? Should I use an additional property or the command parameter to pass contextual data to a View Model’s command? View Models seem to copy all of my Model’s properties Common Issues & Solutions
  • 27. Message boxes are annoying Notifying users from a View Model
  • 28. Message boxes are annoying Messages to the user are useful Use a mediator – Allows you to aggregate messages from all of your VMs, log them, and display them. Also easy to test. If you only need it in one or two places an Error/Notification property or, more rarely, event works well. Implement the IDataErrorInfo interface for notifications related to property validation Notifying users from a View Model
  • 29. Usually done using an attached behavior, search for “Attached Command Behavior” Can it be handled by binding? If absolutely necessary and there’s no logic involved it can be put into code behind. Handling events without code behind
  • 30. Code Behind & Gotos http://xkcd.com/292 Beware of Raptor Attacks
  • 31. Is it a View-only concern? E.g. Master/Detail view Bind the detail view to the selected master item Is it a View Model concern? E.g. IsEditMode Use a DataTemplateSelector if available to switch Views Use Triggers, Visual State Manager, or another method to switch views based on the View Model properties Is it a combination? E.g. IsBusy Use the Visual State Manager if available Visibility based on state, what goes in the View vs. View Model?
  • 32. Would the property be referenced anywhere outside of the command(s)? Does the property make sense in the context of the View Model’s interface? Is the command used in multiple places that would need to set the property to different objects? Property or command parameter?
  • 33. View Models are not just Façades or Adapters for Model classes View Models are not the code behind for a View View Models are an Abstract View or the Model for a View View Models will present multiple Models and multiple View Models might use the same Model View Models just copy my Models
  • 34. I love feedback! Bryan Anderson bryan.anderson@ilmservice.com @SolaAesir Questions?

Hinweis der Redaktion

  1. http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspxWhen implemented on a class,INotifyPropertyChanged allows you to notify consumers about changes in the values of your properties by raising the PropertyChanged event. The PropertyChangedEventHandler takes the sender (instance raising the event) and PropertyChangedEventArgs (adds [string PropertyName] to the standard EventArgs) as arguments.
  2. http://msdn.microsoft.com/en-us/library/system.collections.specialized.inotifycollectionchanged.aspxWhen implemented on a class (almost always a collection),INotifyCollectionChanged allows it to notify consumers that the collection has changed by raising the CollectionChanged event. The event arguments specify how the collection changed (NotifyCollectionChangedAction) and the items that changed.Add – Item(s) were addedRemove – Item(s) were removedReplace – One item was exchanged for another. I.e. say x[3] = Foo; if I then say x[3] = Bar; the object (Foo) at index 3 is replaced (with Bar)Move – An objects was moved to a different index, e.g. collection was sorted, the object at index 3 was moved to index 5.Reset – A large change has happened to the collection and anything watching it should just reinitialize. Most commonly happens when the Clear() method is called.
  3. http://msdn.microsoft.com/en-us/library/ms750612.aspxDataBinding allows two properties (as long as one is a DependencyProperty, discussed later) to have their values stay synced up.
  4. Value converters (classes that implement IValueConverter and/or IMultiValueConverter) are used to convert values from value to another. Frequently used in data binding where the two properties have a known relationship but not necessarily the same value. For instance I might convert a booleantrue into Visibility.Visible and false into Visibility.Collapsed.
  5. http://msdn.microsoft.com/en-us/library/system.windows.dependencyproperty.aspx
  6. A User Control allows you to group a set of visual elements into a single unit and gives you a code behind file, allowing you to add custom dependency properties. If you are not going to have any code behind in your User Control it’s usually better to use a DataTemplate instead which basically functions as a User Control without the code behind.
  7. Command Pattern = a design pattern where an object is used to represent and encapsulate all the information needed to call a method at a later timeDelegateCommand overview - http://kentb.blogspot.com/2009/04/mvvm-infrastructure-delegatecommand.html
  8. Blend/Visual studio workflow is really a goal of MVVM rather than the more general Presentation Model pattern. However use of a Presentation Model pattern will tend increase the separation of designer and developer allowing them to work without stepping on each other’s toes.
  9. See http://martinfowler.com/eaaDev/PresentationModel.html
  10. The highlighted portions of each pattern are their “Presentation Model”, this is where the real differences in the patterns reside and is often the most difficult layer to get right.
  11. The model is/should be exactly the same across all of the presentation model patterns and many other architectural patterns allowing you to share it among applications if necessary.
  12. The View Model is the hardest layer to get right in MVVM. Most people when first using the pattern will try to make the View Models either be a code behind for the view or a façade/adapter for the model. Neither is correct. We go over some of the warning signs and how to shift your approach throughout the presentation.
  13. The interface to the user. Shouldn’t contain much in the way of code or logic other than what’s necessary to display data.
  14. Your unit tests will tell you very early if your View Model is starting to become too tightly coupled to a particular View or Model.
  15. Check Wikipedia or one of a hundred blog posts for a more in-depth explanation.
  16. The one thing to remember is to choose one and stick with it.
  17. Most talks and blog posts about MVVM claim you should have no code in the View. That’s mostly true but there are a few times when you won’t be able to avoid it.
  18. Think of it as technical debt with a low interest rate. Not to be taken on lightly, but a better choice than some other areas.
  19. Use them wherever necessary but they can let others do stupid things if put into the Model so consider what people will do in the future with the extra power before putting them in the model.
  20. These are the issues I’ve seen pop up the most often. If you’ve run into other general issues I’d like to hear about them. Feel free to send me an email at bryan.anderson@ilmservice.com
  21. Fluffy represents both, your users who are annoyed that you popped up a message box on them, and your fellow developers annoyed that unit tests no long run unattended because they have to click OK on a message box. You’ve been warned.
  22. There are many ways to display an error/warning/notification in the user interface without resorting to a message box. I personally like the way www.stackoverflow.com does it but you could also do something like a browser’s status bar or use adorners.
  23. This is the page I recommended searching for http://marlongrech.wordpress.com/2008/12/13/attachedcommandbehavior-v2-aka-acb/
  24. Code behind is a lot like a goto, you might not think it will cause a problem but you should check for lurking raptors first.
  25. It really just comes down to logic and experience. Ask yourself if a certain portion would change if you changed the way you’re presenting the information in the view. If it would it probably belongs in the view.
  26. I tend to lean toward using the command parameter more often than not because it tends to have fewer side effects and I think it presents a more consistent interface to consumers of the view model. However, many people favor an extra property because they find that it’s easier to understand what the value is and where it comes from.
  27. Don’t think of MVVM as sets of M, V, and VM running around as triples. There is a many-to-many relationship among all of them even if they sometimes pretend it’s a one-to-one.The single responsibility principle comes into play here especially in the View Model, follow it and a lot of your issues will go away.
  28. I’d love to hear feedback on the talk and/or these slides (both positive and negative). Please don’t hesitate to let me know what you thought.