Upload
stanley-cross
View
222
Download
0
Embed Size (px)
Citation preview
ViewModel and Application Patterns for Silverlight
Nikhil KothariSoftware ArchitectMicrosoft CorporationSession 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
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
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
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
Hello WorldFrom code-behind to ViewModel
demo
Interaction Logic in Code-behind
Data Model
View
XAML
Code-BehindEvent Handlers
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
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; }}
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;}
ViewModel-based ApplicationTwitterBug
demo
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
Encapsulating View LogicBehaviors, Actions and Triggers
demo
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>
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
Dependency InjectionUsing the Managed Extensibility Framework
demo
DI by HandView Code-behind – TweetBoxView.xaml.cs
public class TweetBoxView : UserControl {
public TweetBoxView() { InitializeComponent();
ITwitterService svc = new ServerTwitterService(); DataContext = new TweetBoxViewModel(svc); }}
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;
Visual Representation of DI
View Model #2
View Model #1
IoC ContainerServices ViewViewModelRegistry
BindingLookup
Contains
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
View Model Communication using an EventAggregator
demo
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) { … }}
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
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
question & answer
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
Complete a session evaluation and enter to win!
10 pairs of MP3 sunglasses to be won
© 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.