29

Nikhil Kothari Software Architect Microsoft Corporation Session Code: WUX312

Embed Size (px)

Citation preview

Page 1: Nikhil Kothari Software Architect Microsoft Corporation Session Code: WUX312
Page 2: Nikhil Kothari Software Architect Microsoft Corporation Session Code: WUX312

ViewModel and Application Patterns for Silverlight

Nikhil KothariSoftware ArchitectMicrosoft CorporationSession Code: WUX312

Page 3: Nikhil Kothari Software Architect Microsoft Corporation Session Code: WUX312

Agenda

A practical look at patterns for developing and designing well structured applications

ViewModel (data-binding, commanding)

Supporting Application PatternsTriggers, Actions and BehaviorsInversion of ControlEventAggregator

Page 4: Nikhil Kothari Software Architect Microsoft Corporation Session Code: WUX312

Why Bother with Patterns?

Guidelines and prescriptive approaches based on prior success

Not rulesCommon vocabulary, nomenclature for describing building blocks, and their relationshipsEnable better tools support

Page 5: Nikhil Kothari Software Architect Microsoft Corporation Session Code: WUX312

Patterns for Separating UI and Logic

MVC, MVP, ViewModel, …General approach

Separate interaction logic from viewDecouple components of app

MotivationsLoosely coupled building blocksDesigner-developer workflowGreater degree of testability

Data Model

User Interface

Interaction Logic

Page 6: Nikhil Kothari Software Architect Microsoft Corporation Session Code: WUX312

ViewModel Pattern

MVVM (Model – View – ViewModel), Presentation ModelBasic idea

View model encapsulates application behavior independent of viewView is responsible for rendering and user inputLeverage data-binding and commanding to hook up view to its view model

Page 7: Nikhil Kothari Software Architect Microsoft Corporation Session Code: WUX312

Hello WorldFrom code-behind to ViewModel

demo

Page 8: Nikhil Kothari Software Architect Microsoft Corporation Session Code: WUX312

Interaction Logic in Code-behind

Data Model

View

XAML

Code-BehindEvent Handlers

Page 9: Nikhil Kothari Software Architect Microsoft Corporation Session Code: WUX312

Interaction Logic in View Model

Data Model

View

XAML

Code-Behind

View Model

State + Operations + Notifications

Property change and other event notifications

Data-binding and commands

Page 10: Nikhil Kothari Software Architect Microsoft Corporation Session Code: WUX312

BindingView – HelloWorldView.xaml

<TextBlock Text=“{Binding Greeting}” /><TextBox Text=“{Binding Name, Mode=TwoWay}” />

View Model – HelloWorldViewModel.cs

public class HelloWorldViewModel : INotifyPropertyChanged { public string Greeting { get; } public string Name { get; set; }}

Page 11: Nikhil Kothari Software Architect Microsoft Corporation Session Code: WUX312

CommandingView – HelloWorldView.xaml

<Button pfx:Commands.Command=“{Binding HelloCommand}” />

View Model – HelloWorldViewModel.cs

public class HelloWorldViewModel : INotifyPropertyChanged { public ICommand HelloCommand { get; } private void SayHello() { … } private bool CanSayHello() { … } private DelegateCommand _helloCommand = new DelegateCommand(SayHello, CanSayHello);}

interface ICommand { bool CanExecute(object parameter); void Execute(object parameter); event EventHandler CanExecuteChanged;}

Page 12: Nikhil Kothari Software Architect Microsoft Corporation Session Code: WUX312

ViewModel-based ApplicationTwitterBug

demo

Page 13: Nikhil Kothari Software Architect Microsoft Corporation Session Code: WUX312

Declarative InteractivityImplement View-specific Logic

Repeating patterns in code-behind encapsulated into components

Reuse and less repetitionSimplify design experience

When an event occurs, perform some work…Triggers and Actions

Encapsulation of specific triggers and actionsAttach a Behavior to an existing UI element

Page 14: Nikhil Kothari Software Architect Microsoft Corporation Session Code: WUX312

Encapsulating View LogicBehaviors, Actions and Triggers

demo

Page 15: Nikhil Kothari Software Architect Microsoft Corporation Session Code: WUX312

Triggers, Actions and BehaviorsView – TweetBoxView.xaml

<UserControl> <i:Interaction.Triggers> <pfx:ModelEventTrigger EventName=“TweetPosted”> <i:PlaySoundAction Source=“Tweet.mp3” /> </pfx:ModelEventTrigger> </i:Interaction.Triggers></UserControl>

<TextBox Text=“{Binding Tweet, Mode=TwoWay}”> <i:Interaction.Behaviors> <app:ImmediateCommit /> </i:Interaction.Behaviors></TextBox>

Page 16: Nikhil Kothari Software Architect Microsoft Corporation Session Code: WUX312

Inversion of ControlManaging Dependencies

View models are very likely coupled to data modelsCoupling can get in the way of maintainability and testability

View model should not instantiate its dependenciesInversion of ControlDependencies are handed to the view model through some form of initialization or dependency injection

Page 17: Nikhil Kothari Software Architect Microsoft Corporation Session Code: WUX312

Dependency InjectionUsing the Managed Extensibility Framework

demo

Page 18: Nikhil Kothari Software Architect Microsoft Corporation Session Code: WUX312

DI by HandView Code-behind – TweetBoxView.xaml.cs

public class TweetBoxView : UserControl {

public TweetBoxView() { InitializeComponent();

ITwitterService svc = new ServerTwitterService(); DataContext = new TweetBoxViewModel(svc); }}

Page 19: Nikhil Kothari Software Architect Microsoft Corporation Session Code: WUX312

DI with an IoC ContainerServerTwitterService.cs

[Export(typeof(ITwitterService))]public class ServerTwitterService : ITwitterService {}

[Export]public class TweetBoxViewModel { [ImportingConstructor] public TweetBoxViewModel(ITwitterService twitterService) { … }}

TweetBoxViewModel viewModel = container.GetExport<TweetBoxViewModel>().Value;

Page 20: Nikhil Kothari Software Architect Microsoft Corporation Session Code: WUX312

Visual Representation of DI

View Model #2

View Model #1

IoC ContainerServices ViewViewModelRegistry

BindingLookup

Contains

Page 21: Nikhil Kothari Software Architect Microsoft Corporation Session Code: WUX312

EventAggregatorEnable View Model Communication

View models may want to talk to each otherUnwanted coupling between event publisher and subscriber

Use an event aggregator for light-weight pub/sub

View Model

View Model

View Model

View Model

View Model

View Model

Event Aggregator

Page 22: Nikhil Kothari Software Architect Microsoft Corporation Session Code: WUX312

View Model Communication using an EventAggregator

demo

Page 23: Nikhil Kothari Software Architect Microsoft Corporation Session Code: WUX312

Using EventAggregatorTweetBoxViewModel.cs, TwitterProfileViewModel.cs

public class TweetBoxViewModel { public TweetBoxViewModel(IEventAggregator eventAggregator) { … } … _eventAggregator.Publish(new TweetPostedEventArgs(…));}

public class TwitterProfileViewModel { public TwitterProfileViewModel(IEventAggregator eventAggregator) { eventAggregator.Subscribe<TweetPostedEventArgs>(OnTweet); } private void OnTweet(TweetPostedEventArgs e) { … }}

Page 24: Nikhil Kothari Software Architect Microsoft Corporation Session Code: WUX312

Summary

ViewModel is simple and natural fit for separating view and logic

Application behavior in view modelData-binding and commanding as the glue between view and its model

Decouple individual parts of applicationUse an IoC container and event aggregator

Think about encapsulating view logic into triggers, actions and behaviors

Page 25: Nikhil Kothari Software Architect Microsoft Corporation Session Code: WUX312

Resources

Slides + Demo Code + ViewModel-related blog posts

http://www.nikhilk.netManaged Extensibility Framework

http://mef.codeplex.comSilverlight Unit Testing Framework

http://code.msdn.microsoft.com/silverlightut Other ViewModel-related reading

Josh Smith’s MSDN articlehttp://msdn.microsoft.com/en-us/magazine/dd419663.aspx

Page 26: Nikhil Kothari Software Architect Microsoft Corporation Session Code: WUX312

question & answer

Page 27: Nikhil Kothari Software Architect Microsoft Corporation Session Code: WUX312

www.microsoft.com/teched

International Content & Community

http://microsoft.com/technet

Resources for IT Professionals

http://microsoft.com/msdn

Resources for Developers

www.microsoft.com/learning

Microsoft Certification & Training Resources

Resources Tech·Ed Africa 2009 sessions will be made available for download the week after the event from: www.tech-ed.co.za

Page 28: Nikhil Kothari Software Architect Microsoft Corporation Session Code: WUX312

Complete a session evaluation and enter to win!

10 pairs of MP3 sunglasses to be won

Page 29: Nikhil Kothari Software Architect Microsoft Corporation Session Code: WUX312

© 2009 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS,

IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.