windows 10 uwp mvvm in depth brian noyes cto & co-founder, solliance inc ()...
TRANSCRIPT
Windows 10 UWP MVVM In DepthBrian Noyes
CTO & Co-founder, Solliance Inc (www.solliance.net)
[email protected], @briannoyes
About Brian Noyes
CTO and Co-founder, Solliancewww.solliance.net
Microsoft Regional Director
Microsoft MVP
Pluralsight authorwww.pluralsight.com
@briannoyes
http://briannoyes.net
Web API Insider, Windows Azure Insider,Window Store App Insider, C#/VB Insider
© Brian Noyes. All rights reserved.
Agenda
Windows 10 UWP Big Picture MVVM Pattern Fundamentals MVVM Construction Approaches MVVM Communications Integrating MVVM with Windows 10 UWP Platform Features Leveraging MVVM Frameworks
3
© Brian Noyes. All rights reserved.
Windows 10 Universal Windows Platform
Native APIs of Windows 10 Core APIs common across all Windows 10 platforms Device-Family extensions for desktop, mobile, IoT
Derivative from Windows 8 “Windows Runtime” Less prescriptive/constraining than Windows Runtime was
Styling Windowing Background tasks App activation
© Brian Noyes. All rights reserved.
Windows 10 UWP MVVM
Not “baked” into the platform at all Same core capabilities exist to use MVVM in UWP XAML apps as
other XAML platforms: DataContext Rich two way data binding Property change notifications DataTemplates
© Brian Noyes. All rights reserved.
Windows 10 UWP MVVM
Need to be able to leverage platform specific capabilities and limitations when using MVVM in UWP
Frame-based navigation App activation / lifecycle schemes Transient state management Compiled bindings Lack of Implicit DataTemplates
© Brian Noyes. All rights reserved.
UI Separation Patterns Goals
• Architectural goals Loose coupling Separation of concerns
• Leads to Maintainability Testability Extensibility
Putting all your logic here is not good enough
No Separation of Concerns
private void ComputeCustomerOrdersTotal(object sender, RoutedEventArgs e){ var selectedCustomer = this.customerDataGrid.SelectedItem as Customer; var orders = (from order in dbContext.Orders.Include("OrderItems") where order.CustomerId == selectedCustomer.Id select order); var sum = 0; foreach (var order in orders) { foreach (var item in order.OrderItems) { sum += item.UnitPrice * item.Quantity; } } this.customerOrderTotal.Text = sum.ToString();}
UI Element Access
Data Access
Interaction/Business Logic
Good Separation of Concerns
UI Element Access
Data Access
View Interaction Logic
Shared Client Logic
Business Logic
Model Entities
MVVM Responsibilities
View
ViewModel
ModelObject
ModelObject
ModelObject
Model
Data Binding
Client Services / Repositories
Contain the client data Expose relationships between model
objects Computed properties Raise change notifications
- INotifyPropertyChanged.PropertyChanged
Validation- INotifyDataErrorInfo/IDataErrorInfo
Model Responsibilities
Structural definition of what the user sees on the screen
GOAL: “No Code Behind” Reality: Sometimes need some code
behind
View Responsibilities
Expose data to the view for presentation and manipulation
Encapsulate interaction logic- Calls to business/data layer/service- Navigation logic- State transformation logic
ViewModel Responsibilities
ViewModel Data
ViewModel Customer
Order
Order_Detail
Product
Model
OrderItemOrderDateQuantityProductName
1
1
1
*
*
*public Customer Customer { get; set; }
public ObservableCollection<OrderItem> Orders { get; set; }
public bool LoggedIn { get; set; }
Authentication
Service
“Wrapped”
Client State
“Expose”
public bool ShowCustomerAlert { get; set; }
Shared functionality or data access Consumed by one or more ViewModels Decouples ViewModels from external
dependencies- Data storage- Service access- Client environment
Can act as data caching container
Client Services / Repositories
© Brian Noyes. All rights reserved.
MVVM Construction / “Marrying” Schemes
Fundamental equation of MVVM: View.DataContext = ViewModel]
Approaches: View-First XAML construction View-First Code behind construction View-First ViewModelLocator construction ViewModel-First DataTemplate construction
View-First - XAML
<UserControl x:Class="ZzaDashboard.Customers.CustomerEditView“ Width="400“
Loaded="OnLoaded"...>
<UserControl.DataContext> <local:CustomerEditViewModel /> </UserControl.DataContext>
...
</UserControl>
InitializeComponent()
View-First Code-Behind
public partial class CustomerListView : UserControl{ public CustomerListView() { this.DataContext = new CustomerListViewModel(); InitializeComponent(); }}
View-First - ViewModelLocator
ViewModelLocator is a meta-pattern for automatically locating and hooking up the right ViewModel
© Brian Noyes. All rights reserved.
What view is being constructed? What ViewModel should I construct? Construct (and DI) ViewModel Set ViewModel as View DataContext
ViewModelLocator Process
Data Binding
<UserControl x:Class="..." ...> <Grid>
... <Label Content="First Name:" ... /> <TextBox ... Text="{Binding
Customer.FirstName}"/> <Label Content="Last Name:" ... /> <TextBox ... Text="{Binding
Customer.LastName}" /> <Button ... Command="{Binding SaveCommand}" /> </Grid></UserControl>
public class CustomerEditViewModel : INotifyPropertyChanged{ public Customer Customer { ... } public ICommand SaveCommand { get; set; }}
DataContext
ViewModel-First with Implicit DataTemplates
<DataTemplate DataType="{x:Type local:CustomersOrderTreeViewModel}"> <local:CustomersOrderTreeView /></DataTemplate>
CustomersOrderTreeViewModel
<ContentControl Content="{Binding CurrentViewModel}" />
© Brian Noyes. All rights reserved.
MVVM Communications
ViewModel => View : Data binding + property change notifications View => ViewModel : Commands ViewModel = > ViewModel : Pub/Sub messaging
23
© Brian Noyes. All rights reserved.
Commands
Based on classic Command design pattern
Invoker – View control Receiver - ViewModel Use delegating command
implementation Supports decoupled command
handling invocation Supports enabling/disabling
associated control
Invoker
Receiver
DelegateCommand
ICommand
Hierarchical MVVM / Navigation
Page
Root View
ListView
ListViewModel
ItemView
ItemView
ItemViewModel
DetailsView
DetailsViewModel
ItemViewModel
Root ViewModel
MVVM and UWP Navigation
INavigationService
Page
ViewModel
FrameNavigationService
Frame
Page
ViewModel
© Brian Noyes. All rights reserved.
Application Lifecycle Management
• UWP application lifecycle states:• Not Running• Running• Suspended• ClosedByUser• Terminated
NotRunning
Running
SuspendedTerminated
Launch
SwitchApps
SwitchBack
Low Memory Shutdown
ClosedByUser
Launch Launch
© Brian Noyes. All rights reserved.
UWP MVVM Frameworks
Prism 6 Template10 MVVM Light Caliburn MVVMCross
© Brian Noyes. All rights reserved.
Prism 6 for UWP Contents Prism.Core
MVVM Support Commands PubSubEvents
Prism.Windows MVVM Support Navigation Application State management Validation
© Brian Noyes. All rights reserved.
Please use Event Board to fill out a session evaluation.
Questions?
Thank you!