Post on 17-Dec-2015
transcript
Consultant for ILMWorked with WPF & Silverlight for the past 2
yearsIn industry for 4 ½ yearsProgramming for 14 yearsOf all of the features to come to .NET 4.0,
Code Contracts are the most important
About Me
Vocabulary & relevant Design PatternsPresentation Model patternMVVM ArchitectureCompare MVVM to MVCReligious fights you’ll encounter when
implementing MVVMCommon issues you’ll run into with MVVM
and their solutions
What am I going to talk about?
//Notifies clients that a property value has changed.
public interface INotifyPropertyChanged
{
//Occurs when a property value changes.
event PropertyChangedEventHandler PropertyChanged;
}
INotifyPropertyChanged
//Notifies listeners of dynamic changes, such as when items get //added and removed or the whole list is refreshed.
public interface INotifyCollectionChanged
{
//Occurs when the collection changes.
event NotifyCollectionChangedEventHandler CollectionChanged;
}
//Describes the action that caused a CollectionChanged event.
public enum NotifyCollectionChangedAction
{
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 IMultiValueConverterobject 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 likeData BindingChange NotificationValue Coercion
Used extensively by WPF and Silverlight to create fast, reactive user interfaces
Dependency Property
Groups a related set of controlsReduces repetition – DRYerHas its own code behind – allows new
dependency properties
User Control
An implementation of the Command PatternIn WPF & Silverlight the ICommand interface
is used to define a class that represents a commandbool CanExecute(object parameter)void Execute(object parameter)event EventHandler CanExecuteChanged
Frequently implemented by creating a DelegateCommand class
Commands
Design patterns give programmers a proven solution to a given problem with known benefits, drawbacks, and a shared vocabulary.
Command – Encapsulates method callsMediator - Encapsulates messages between
objectsAdapter – Translates one interface into anotherFaçade – Simplifies a larger interfaceSingleton - Restricts a class to a single instanceFactory – Encapsulates the creation of an objectEtc.
Design patterns
Architectural patterns serve the same purpose as other design patterns, but they focus on the whole application or a very large portion of it.
The Purpose of Architecture Patterns
Guide the separation of concernsEncapsulate what changes
UIWeb servicesDatabasesAnything else that interfaces with something
outside the application
The Purpose of Architecture Patterns
Separate presentation from functionalityTestabilityConsistencyMaintainabilityAllow 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
Model
Presentation Model
View
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
Model
Presentation Model
View
MVVM Architecture – Model
Model
View Model
ViewUnit Tests
Web Servic
es
File Syste
m
Database
Responsible for business logic
Interacts with persistent storage, e.g. database, web services, files, etc.
Capable of being shared among related applications
MVVM Architecture – View Model
Model
View Model
ViewUnit Tests
Web Servic
es
File Syste
m
Database
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
MVVM Architecture - View
Model
View Model
ViewUnit Tests
Web Servic
es
File Syste
m
Database
Presents data to the user
Handles inputInteracts 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
MVVM Architecture - Tests
Model
View Model
ViewUnit Tests
Web Servic
es
File Syste
m
Database
Acts as another ViewInteracts 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
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
Model
Controller
View
Multiple, mutually exclusive optionsPeople form strong opinions and will argue
the benefits of their choice for all eternityEach side has its own benefits and drawbacksA decision needs to be made before the
“correct choice” can be determinedIn the end it comes down to a combination of
reason and instinct
Religious Fights
View Model DrivenAllows 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 1View DrivenEasy 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 valuesUser 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 instanceMy 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 ModelOccasionally in the View - usually in Custom
Controls and more rarely User ControlsIt’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 annoyingMessages 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
Is it a View-only concern? E.g. Master/Detail viewBind the detail view to the selected master
itemIs 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. IsBusyUse 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