<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:georss='http://www.georss.org/georss' xmlns:gd='http://schemas.google.com/g/2005' xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-8085117242240449595</id><updated>2012-01-24T22:14:02.855-06:00</updated><category term='xpath funciton'/><category term='Magic String'/><category term='Message Trigger Service'/><category term='Visual Studio'/><category term='table valued constructor'/><category term='control'/><category term='wpf StartupEventArgs'/><category term='Open Closed'/><category term='C++ stored proc'/><category term='application settings'/><category term='Listeners'/><category term='IValueProvider'/><category term='CTRL'/><category term='Single responsibility'/><category term='DbContext'/><category term='title case'/><category term='message queuing'/><category term='msmq'/><category term='XPATH Injection'/><category term='inter process'/><category term='Func'/><category term='pass data to WF'/><category term='APPLY'/><category term='VSTS'/><category term='OnError'/><category term='Tracking Runtime'/><category term='WMI'/><category term='powershell'/><category term='Subscribe'/><category term='compromise'/><category term='System.Runtime.Caching'/><category term='computed column'/><category term='Tracking Store'/><category term='radiobutton'/><category term='performance monitoring'/><category term='microsoft robotics'/><category term='perfmon.exe'/><category term='SSIS'/><category term='FTPWebRequest'/><category term='EventData'/><category term='x lock'/><category term='IInvokeProvider'/><category term='case sensitive'/><category term='IoC'/><category term='expander'/><category term='ObjectDataProvider'/><category term='UDF'/><category term='SILVERLIGHT 5 BETA'/><category term='SQLServerCompactEditionUnderWebHosting'/><category term='wpf royale theme'/><category term='F#'/><category term='Word'/><category term='mvvm light'/><category term='test suite'/><category term='TextBoxAutomationPeer'/><category term='ASynchDelegate'/><category term='isasynchronous'/><category term='workflow events'/><category term='Enabling CLR Integration'/><category term='resotore'/><category term='IValueConverter'/><category term='reactive model'/><category term='TextSearch'/><category term='Converter'/><category term='BindingReflector'/><category term='policy activity'/><category term='WS-POLICY'/><category term='ButtonAutomationPeer'/><category term='Workflow Monitoring Tool'/><category term='NamedPipeServerStream'/><category term='Microsoft'/><category term='CCR'/><category term='multiple datasources'/><category term='debugger'/><category term='memory mapped file'/><category term='rollup'/><category term='Proper Case'/><category term='Data Model'/><category term='MERGE Statement'/><category term='DTSWizard'/><category term='workspace'/><category term='new features'/><category term='MaxConcurrentExecutables'/><category term='EventWaitHandle'/><category term='AutomationPeer'/><category term='MEF'/><category term='S.O.L.I.D'/><category term='Exception'/><category term='persistence service'/><category term='Lazy initialization'/><category term='StackPanel'/><category term='pkzip'/><category term='column set'/><category term='polymorphism'/><category term='DbSet'/><category term='BeginInvoke'/><category term='Deploy'/><category term='mosue capture'/><category term='array operations'/><category term='scripting integration Services'/><category term='axum'/><category term='.net framework'/><category term='cacheitempolicy'/><category term='user settings'/><category term='Database programming'/><category term='robotics'/><category term='.net 4.5'/><category term='AdornerLayer'/><category term='SpellCheck.IsEnabled'/><category term='wpf application parameters'/><category term='GetPattern'/><category term='cube'/><category term='dispatcher'/><category term='WS-METADATAEXCHANGE'/><category term='join'/><category term='Action'/><category term='team system'/><category term='C stored proc'/><category term='Throttle'/><category term='VARCHAR(1)'/><category term='intellisence'/><category term='datatype'/><category term='c#. .net'/><category term='wpf'/><category term='check in'/><category term='linq pdf'/><category term='DELETE'/><category term='log'/><category term='TextInfo'/><category term='index'/><category term='.net 2.0'/><category term='MemoryCacheSection'/><category term='caching'/><category term='entity framework'/><category term='assignment'/><category term='DSS'/><category term='PreviewMouseDownOutsideCapturedElement'/><category term='grouping sets'/><category term='pixel shader'/><category term='Silverlight'/><category term='bulk delete'/><category term='winzip'/><category term='data parallelism'/><category term='SQL Agent'/><category term='MVVM'/><category term='PRINT SCREEN'/><category term='local path'/><category term='managed OS'/><category term='Barrier'/><category term='LostMouseCapture'/><category term='Window_PreviewMouseDownOutsideCapturedElement'/><category term='StyleSelector'/><category term='ClickOnce'/><category term='REGULAR EXPERSSION'/><category term='INSERTED'/><category term='EventAggregator'/><category term='.net framework 3.5'/><category term='SSMS'/><category term='sql server package deployment'/><category term='Dependency Property'/><category term='wf persistence'/><category term='WPF 4.5 Developer&apos;s Preview'/><category term='ObserveOnDispatcher'/><category term='UI thread'/><category term='textboxbase'/><category term='OUTPUT clause'/><category term='Tracking Service'/><category term='IObserver'/><category term='Observer pattern'/><category term='.net'/><category term='performance'/><category term='Trace.Flush'/><category term='LINQ to SQL'/><category term='review'/><category term='updatesourcetrigger'/><category term='WCA'/><category term='CROSS APPLY'/><category term='working folder'/><category term='ServiceBehavior'/><category term='xml'/><category term='simulation'/><category term='case insensitive'/><category term='priority binding'/><category term='Dynamics AX configuration key code'/><category term='authority'/><category term='wpf resx'/><category term='cassini'/><category term='BaseEnum Dynamics AX table Axapta Mandatory None'/><category term='linq to IObservable'/><category term='Windows pipes'/><category term='wf parameters'/><category term='immutable'/><category term='TraceTextListnener'/><category term='DependencyProperty'/><category term='BLOBTempStoragePath'/><category term='XPATH'/><category term='OnNext'/><category term='Resource Governor'/><category term='BCC'/><category term='BackgroundWorker'/><category term='Static'/><category term='sqlserver 2008'/><category term='PipeTransmissionMode'/><category term='Windows Communication Activity Generator'/><category term='.net remoting'/><category term='IN'/><category term='MemoryMappedFile'/><category term='explicit'/><category term='IEvent'/><category term='EventStream'/><category term='WPF 4.5'/><category term='inline intialization'/><category term='software'/><category term='ConverterParameter'/><category term='partition'/><category term='smart client'/><category term='Invoke'/><category term='objectcache'/><category term='delegate'/><category term='openxml'/><category term='sql server management studio'/><category term='test case'/><category term='initializer'/><category term='Velocity'/><category term='Messaging'/><category term='Long in Oracle DML trigger'/><category term='Dependency Injection'/><category term='cluster cache'/><category term='trace'/><category term='StaticResource'/><category term='UPDATE'/><category term='Configuration Manager'/><category term='Google Custom search'/><category term='EF Code First'/><category term='Creational pattern'/><category term='extended stored procedure'/><category term='light weight view'/><category term='FileStream'/><category term='assembly'/><category term='forward chaining'/><category term='memorycache'/><category term='GPU accelerated effects'/><category term='relaycommand'/><category term='bulk insert'/><category term='power shell'/><category term='multithread SSIS'/><category term='VSTO'/><category term='SQL Server Credential'/><category term='Business Rule Engine'/><category term='.net 4.0'/><category term='assembly resource'/><category term='spell check'/><category term='.net security'/><category term='managed'/><category term='implicit DataTemplate'/><category term='complex number'/><category term='CSM'/><category term='ItemsPanelTemplate'/><category term='Model Driven'/><category term='Claims based security'/><category term='IMultiValueConverter'/><category term='Operating System'/><category term='Unit Testing'/><category term='PropertyChanged'/><category term='Injection'/><category term='Mail'/><category term='Singularity'/><category term='ThreadPool'/><category term='for each row'/><category term='Table Buffer Axapta Dynamics data clone cloneable'/><category term='concurrency coordination runtime'/><category term='modal window'/><category term='AdornerDecorator'/><category term='Managed Extensibility Framework'/><category term='Thread'/><category term='bulk update'/><category term='UpdateBatchSize'/><category term='WQL'/><category term='pad'/><category term='Style Selector'/><category term='Alert'/><category term='Workflow'/><category term='audit'/><category term='compound assignment operator'/><category term='listbox'/><category term='constructor'/><category term='null'/><category term='StringFormat'/><category term='asynch wpf'/><category term='C#'/><category term='DDL'/><category term='EXCLUSION'/><category term='Certified Scrum Master'/><category term='Object library'/><category term='Enterprise Library'/><category term='markup extension'/><category term='orcas'/><category term='wpf resource'/><category term='reactive extensions'/><category term='Interface Segregation'/><category term='RANGE'/><category term='sharpzip'/><category term='EngineThreads'/><category term='command line arguments'/><category term='StrConv'/><category term='ESCAPE SEQUENCE'/><category term='wow64'/><category term='binding'/><category term='OUTER APPLY'/><category term='Midori'/><category term='appdomain slots'/><category term='RegisterWaitForSingleObject'/><category term='SQL Server Agent'/><category term='translate'/><category term='relativesource'/><category term='wpf 4'/><category term='DataTemplate'/><category term='.net 3.5'/><category term='Outlook'/><category term='wow'/><category term='leading zeros'/><category term='ContentStringFormat'/><category term='AddLostMouseCaptureHandler'/><category term='multiple observer'/><category term='Visual Studio 2008'/><category term='Visual simulation environment'/><category term='.net framework 3.5  enhancements'/><category term='timer'/><category term='SELECT'/><category term='accelerator project'/><category term='FTP'/><category term='sparse'/><category term='Lazy'/><category term='teardown'/><category term='wf properties'/><category term='virtual'/><category term='synchronous'/><category term='INotifyPropertyChanged'/><category term='View Model'/><category term='captured variables'/><category term='timer accuracy'/><category term='minus'/><category term='C stored procedure'/><category term='prism'/><category term='c++ stored Procedure'/><category term='CommandParameter'/><category term='DataContext'/><category term='Integration Services'/><category term='ManualReset'/><category term='result set'/><category term='linq'/><category term='remote debugger'/><category term='WIN32_'/><category term='host'/><category term='lock'/><category term='isasync'/><category term='WF Local Services'/><category term='theme'/><category term='Observable.ToAsync'/><category term='observable'/><category term='DLL Stored procedure'/><category term='synchronization'/><category term='composite application library'/><category term='remote debug'/><category term='Change Data Capture'/><category term='Batch Update'/><category term='mutable'/><category term='inter-domain messaging'/><category term='AppDomain'/><category term='ShaderEffect'/><category term='wpf thread synchroization'/><category term='LIKE OPERATOR'/><category term='Validation Application Block'/><category term='attached properties'/><category term='imaginary number'/><category term='parallel execution SSIS'/><category term='Blind copy'/><category term='databinding'/><category term='SolidColorBrush'/><category term='Event Data'/><category term='Scrum'/><category term='VS2010'/><category term='object search'/><category term='Business Rules Framework'/><category term='asp.net'/><category term='opacitymask'/><category term='DELETED'/><category term='T-SQL'/><category term='cruise control'/><category term='Tuples'/><category term='Excel'/><category term='Visual Studio Tools for Office'/><category term='unshelving'/><category term='DrawingContext'/><category term='CLR'/><category term='activity'/><category term='PipeDirection'/><category term='OnCompleted'/><category term='simulate key press'/><category term='Synch'/><category term='visual studio 2011'/><category term='Valie'/><category term='opacity Mask'/><category term='Credential'/><category term='IncludeExceptionDetailInFaults'/><category term='parallel execution integration services'/><category term='Sort'/><category term='silverlight 5'/><category term='Business Intelligence'/><category term='wpf spanish'/><category term='Windows WF'/><category term='3.5'/><category term='google sqlserver'/><category term='Unit Testing Framework'/><category term='Geneva'/><category term='batch delete'/><category term='itemsPanel'/><category term='message loop'/><category term='TranslatePoint'/><category term='MailItem'/><category term='SET'/><category term='static constructor'/><category term='ItemsControl'/><category term='parallel extensions .net'/><category term='shujaat'/><category term='artificial intelligence'/><category term='hardware'/><category term='code metric'/><category term='close window from View model'/><category term='SSIS package deployment'/><category term='WBEMTEST'/><category term='IObsevable'/><category term='string.format'/><category term='Client Profile'/><category term='System.Net'/><category term='SQL Server 2008'/><category term='SQL Server Alerts'/><category term='wpf theme'/><category term='Office Programming'/><category term='Office'/><category term='zermatt'/><category term='communication viewmodel view'/><category term='deployment'/><category term='remote'/><category term='solid state drive'/><category term='WF Tracking Service'/><category term='prism 4.0'/><category term='version'/><category term='revert'/><category term='System.Windows.Threading.DispatcherTimer'/><category term='issue'/><category term='Reactive extension'/><category term='research project'/><category term='VirtualizingStackPanel'/><category term='wpf binding'/><category term='system.threading.timer'/><category term='closure'/><category term='BufferTemppStoragePath'/><category term='Routed Event'/><category term='Design Pattern'/><category term='Katmai'/><category term='system.windows.forms.timer'/><category term='multiple view models'/><category term='ProperCase'/><category term='frame'/><category term='CDC'/><category term='Tracking Profile'/><category term='custom search'/><category term='performance improvement'/><category term='batch insert'/><category term='WCFDataService'/><category term='SQL'/><category term='ILMerge'/><category term='overwrite application'/><category term='ItemTemplate'/><category term='build action'/><category term='multithreading SSIS'/><category term='IObservable'/><category term='Windows Workflow Foundation'/><category term='Model'/><category term='INSERT'/><category term='shelving'/><category term='BitmapEffect'/><category term='AdornedElementPlaceHolder'/><category term='wpf effects'/><category term='delay'/><category term='command time out'/><category term='validation'/><category term='XAML'/><category term='new features C# 4.0'/><category term='sqlworkflowpersistenceservice'/><category term='.net framework 4.0'/><category term='cursor'/><category term='NamedCaches'/><category term='attached behavior'/><category term='Environment.GetCommandLineArguments'/><category term='non-windows'/><category term='Observable. Observable.ForkJoin'/><category term='InputSimulator'/><category term='SQL Browser'/><category term='system.timers.timer'/><category term='claim'/><category term='Liskov Substitution'/><category term='navigationservice'/><category term='Page'/><category term='sql server 2005'/><category term='composable DML'/><category term='Dependency Inversion'/><category term='wpf localization'/><category term='MessageBus'/><category term='WF Interceptor Biztalk Serrver'/><category term='t-sql debugger'/><category term='64-bit'/><category term='vsts 2008'/><category term='security'/><category term='team system 2008'/><category term='Input Binding'/><category term='trailing zeros'/><category term='mousecapture'/><category term='Compare Dynamics AX Axapta'/><category term='ultidev'/><category term='WIN32_COMPUTERSYSTEM'/><category term='LinearGradientBrush'/><category term='Filter'/><category term='MERGE'/><category term='dynamic updates'/><category term='Lambda'/><category term='ICollectionView'/><category term='SQL Server Alert'/><category term='application domain'/><category term='inference engine'/><category term='OUTPUT'/><category term='sql server integration services'/><category term='locking'/><category term='Rx'/><category term='MemoryCacheElement'/><category term='setup'/><category term='cheat sheet'/><category term='rules'/><category term='DTUtil'/><category term='proxy'/><category term='asynchronous'/><category term='debugging'/><category term='cache'/><category term='Observable.Start'/><category term='SQL Server'/><category term='online index'/><category term='Command RoutedCommand'/><category term='multiBinding'/><category term='imagebrush'/><category term='CountdownEvent'/><category term='complexity'/><category term='Visual Studio 2010'/><category term='partitioning'/><category term='changemonitor'/><category term='trigger action'/><category term='asynchronous binding'/><category term='grouping set'/><category term='32-bit'/><category term='functional'/><category term='parallel'/><category term='Decentralized software service'/><category term='AutoReset'/><category term='lambda statement'/><category term='ADO .net'/><category term='Relay Command'/><category term='database'/><category term='code review'/><category term='Model Driven Engineering'/><category term='WS-TRUST'/><category term='editable combobox'/><category term='CallExternalMethodActivity'/><category term='stored procedure'/><category term='lambda expression'/><category term='objects'/><category term='trigger'/><category term='linq help'/><category term='ICommand'/><category term='attacks'/><category term='Signal constructs'/><category term='SQL Server Browser'/><category term='Inversion of Control'/><category term='Adorner effect'/><category term='windows power shell'/><category term='XUnit'/><category term='nullable'/><category term='WPF relative positoin'/><category term='Items Style'/><category term='Alerts'/><category term='SSD'/><category term='functional programming'/><category term='dictionary'/><category term='winpower shell'/><category term='solid principles'/><category term='HandleExternalEventActivity'/><category term='power shell scripting'/><category term='slot'/><category term='message passing'/><category term='MarshalByRefObject'/><category term='zip'/><category term='toTitleCase'/><title type='text'>Muhammad Shujaat Siddiqi</title><subtitle type='html'>Exploring the world of software engineering...</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://www.shujaat.net/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default?max-results=100'/><link rel='alternate' type='text/html' href='http://www.shujaat.net/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><link rel='next' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default?start-index=101&amp;max-results=100'/><author><name>Muhammad Shujaat Siddiqi</name><uri>http://www.blogger.com/profile/02519138704633566929</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>197</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>100</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-8085117242240449595.post-5020516417488756839</id><published>2012-01-19T22:19:00.000-06:00</published><updated>2012-01-21T07:23:16.346-06:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='entity framework'/><category scheme='http://www.blogger.com/atom/ns#' term='.net 4.0'/><category scheme='http://www.blogger.com/atom/ns#' term='.net'/><category scheme='http://www.blogger.com/atom/ns#' term='DbSet'/><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><category scheme='http://www.blogger.com/atom/ns#' term='DbContext'/><category scheme='http://www.blogger.com/atom/ns#' term='EF Code First'/><title type='text'>Entity Framework 4.2 Code First</title><content type='html'>This is a series of post in which we will be discussion about the Entity Framework Code First. In this post we will be discussing how we can create a simple database oriented application using Entity Framework 4.2 released Nov, 2011. This post assumes that you have SQL Server Express installed on your machine with its Database engine and Management Studio.&lt;br/&gt;&lt;br/&gt;Let's create a console application, named &lt;i&gt;EFCodeFirstDatabaseCreation&lt;/i&gt;. In order to use the features of Entity framework, we need to add &lt;i&gt;EntityFramework&lt;/i&gt; Nuget to the project. [&lt;a href="http://nuget.codeplex.com/wikipage?title=Getting%20Started"&gt;Introduction to Nuget&lt;/a&gt;]&lt;br/&gt;&lt;br/&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://4.bp.blogspot.com/-oS19Oe0xx5s/TxjcV3HaykI/AAAAAAAABEg/-Tj0FUtAokg/s1600/1.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="222" width="400" src="http://4.bp.blogspot.com/-oS19Oe0xx5s/TxjcV3HaykI/AAAAAAAABEg/-Tj0FUtAokg/s400/1.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br/&gt;In this example, we would consider a simple application to maintain data about students. We would seed testing data using initializing code. We would be querying this data using Entity Framework Code First. Let's first define Student entity. As we can see this is a simple POCO (Plain Old CLR Object) based class with a few auto-implemented properties. Most certainly, we don't need to inherit it from any special class.&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;namespace EFCodeFirstDatabaseCreation.Entities&lt;br /&gt;{&lt;br /&gt;    class Student&lt;br /&gt;    {&lt;br /&gt;        public int StudentId { get; set; }&lt;br /&gt;        public string FirstName { get; set; }&lt;br /&gt;        public string LastName { get; set; }&lt;br /&gt;        public int GradePointAverage { get; set; }&lt;br /&gt;        public bool IsOutStanding { get; set; }&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;Now we need to define the &lt;i&gt;DbContext&lt;/i&gt; for querying the entities from Database. Here Entities are defined in terms of &lt;i&gt;DbSet&lt;/i&gt;based properties. We can query the database using these properties. It also supports insert / update and delete operations on these entities.&lt;br/&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;namespace EFCodeFirstDatabaseCreation.Entities&lt;br /&gt;{&lt;br /&gt;    using System.Data.Entity;&lt;br /&gt;&lt;br /&gt;    class InstituteEntities : DbContext&lt;br /&gt;    {&lt;br /&gt;        public DbSet&amp;lt;Student&amp;gt; Students { get; set; }&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;&lt;br/&gt;&lt;br/&gt;Now we need to insert seed data to the database. The initializer can inherit from one of the following:&lt;ol&gt;&lt;li&gt;DropCreateDatabaseAlways&amp;ltT;Context&amp;gt; &lt;/li&gt;&lt;li&gt;DropCreateDatabaseIfModelChanges&amp;ltT;Context&amp;gt; &lt;/li&gt;&lt;li&gt;CreateDatabaseIfNotExists&amp;ltT;Context&amp;gt;&lt;/li&gt;&lt;/ol&gt;&lt;br/&gt;All of the above three initializers are basically the implementation of &lt;i&gt;IDatabaseInitializer&amp;ltT;Context&amp;gt;&lt;/i&gt;. Basically Code First supports automatic creation / updates of the Database based on POCO entities. These implementations specify what circumstances should cause creation of a new Database. By default the name of the database would be based on the name of class inheriting from DbContext and its namespace. e.g. for our case it is &lt;i&gt;EFCodeFirstDatabaseCreation.Entities.InstituteEntities&lt;/i&gt;. We can specify a different name by causing the relevant constructor of &lt;i&gt;DbContext&lt;/i&gt; (base class) to be used. So if we just update the code as following then the name of created database would be &lt;i&gt;InstituteDB&lt;/i&gt;.&lt;br/&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;public InstituteEntities()&lt;br /&gt;    : base("InstituteDB")&lt;br /&gt;{ }&lt;/pre&gt;&lt;br /&gt;As discussed above, we add &lt;i&gt;InstituteDatabaseInitializer&lt;/i&gt; to the project. As you can see we are adding four students to the database. It seems all four of them are outstanding :). Calling base class's seed method would cause data to be pushed to the database saving the changes in the entities.&lt;br/&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;namespace EFCodeFirstDatabaseCreation&lt;br /&gt;{&lt;br /&gt;    using EFCodeFirstDatabaseCreation.Entities;&lt;br /&gt;    using System.Data.Entity;&lt;br /&gt;&lt;br /&gt;    class InstituteDatabaseInitializer : DropCreateDatabaseAlways&amp;lt;InstituteEntities&amp;gt;&lt;br /&gt;    {&lt;br /&gt;        protected override void Seed(InstituteEntities context)&lt;br /&gt;        {&lt;br /&gt;&lt;br /&gt;            Student student1 = new Student()&lt;br /&gt;            {&lt;br /&gt;                FirstName = "Muhammad",&lt;br /&gt;                LastName = "Siddiqi",&lt;br /&gt;                IsOutStanding = true,&lt;br /&gt;                GradePointAverage = 3&lt;br /&gt;            };&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;            Student student2 = new Student()&lt;br /&gt;            {&lt;br /&gt;                FirstName = "Chattan",&lt;br /&gt;                LastName = "Shah",&lt;br /&gt;                IsOutStanding = true,&lt;br /&gt;                GradePointAverage = 4&lt;br /&gt;            };&lt;br /&gt;&lt;br /&gt;            Student student3 = new Student()&lt;br /&gt;            {&lt;br /&gt;                FirstName = "Imran",&lt;br /&gt;                LastName = "Ashraf",&lt;br /&gt;                IsOutStanding = true,&lt;br /&gt;                GradePointAverage = 4&lt;br /&gt;            };&lt;br /&gt;&lt;br /&gt;            Student student4 = new Student()&lt;br /&gt;            {&lt;br /&gt;                FirstName = "Jawad",&lt;br /&gt;                LastName = "Qureshi",&lt;br /&gt;                IsOutStanding = true,&lt;br /&gt;                GradePointAverage = 4&lt;br /&gt;            };&lt;br /&gt;&lt;br /&gt;            context.Students.Add(student1);&lt;br /&gt;            context.Students.Add(student2);&lt;br /&gt;            context.Students.Add(student3);&lt;br /&gt;            context.Students.Add(student4);&lt;br /&gt;&lt;br /&gt;            base.Seed(context);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;}&lt;/pre&gt;&lt;br/&gt;Now we just need to query the database after seed data is inserted. We can use this data for our testing. Just first initilze the database using the &lt;i&gt;InstituteDatabaseInitializer&lt;/i&gt; defined above. Then we are just printing student's data to the console.&lt;br/&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;namespace EFCodeFirstDatabaseCreation&lt;br /&gt;{&lt;br /&gt;    using System.Linq;&lt;br /&gt;    using EFCodeFirstDatabaseCreation.Entities;&lt;br /&gt;    using System.Data.Entity;&lt;br /&gt;    using System;&lt;br /&gt;&lt;br /&gt;    class Program&lt;br /&gt;    {&lt;br /&gt;        static void Main(string[] args)&lt;br /&gt;        {&lt;br /&gt;            Database.SetInitializer&amp;lt;InstituteEntities&amp;gt;(new InstituteDatabaseInitializer());&lt;br /&gt; &lt;br /&gt;            InstituteEntities instituteEntites = new InstituteEntities();&lt;br /&gt;            var students = instituteEntites.Students.ToList&amp;lt;Student&amp;gt;();&lt;br /&gt;&lt;br /&gt;            foreach (var student in students)&lt;br /&gt;            { &lt;br /&gt;                Console.WriteLine(&lt;br /&gt;                            string.Format("Name : {0} {1}, GPA : {2}", &lt;br /&gt;                                       student.FirstName,&lt;br /&gt;                                       student.LastName,&lt;br /&gt;                                       student.GradePointAverage));                                       &lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;            Console.ReadLine();&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;When we run the application, it shows the following output. This shows that the correct seed data is inserted to the database.&lt;br/&gt;&lt;br/&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://3.bp.blogspot.com/-OGMZZT59Jfk/Txjd_xdRfOI/AAAAAAAABEs/mCkIhQ23xgc/s1600/2.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="202" width="400" src="http://3.bp.blogspot.com/-OGMZZT59Jfk/Txjd_xdRfOI/AAAAAAAABEs/mCkIhQ23xgc/s400/2.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br/&gt;The interesting thing to notice is that we are not specifying any connection string anywhere in the application and yet we are able to run the application without any issues. This is only possible if you have local SQL Express installed on the development machine, otherwise, we can specify the connection string in the &lt;i&gt;app.config&lt;/i&gt;. We can also access the same database using a query tool. In the following, we are connecting this using SQL Management studio and querying the student's data. Notice the same data as seeded by the application.&lt;br/&gt;&lt;br/&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/-VG3TKZm98rY/TxjfyYvWQeI/AAAAAAAABE4/bmFSICXV_d8/s1600/3.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="213" width="400" src="http://2.bp.blogspot.com/-VG3TKZm98rY/TxjfyYvWQeI/AAAAAAAABE4/bmFSICXV_d8/s400/3.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br/&gt;&lt;b&gt;Download : &lt;/b&gt;&lt;br/&gt;&lt;br/&gt;&lt;iframe title ="Preview" scrolling="no" marginheight="0" marginwidth="0" frameborder="0" width="98px" height="120px" style="padding:0;background-color:#fcfcfc;" src="https://skydrive.live.com/embed?cid=6F3051EF13F3137E&amp;resid=6F3051EF13F3137E%21204&amp;authkey=AGtIY3PHxGBOV5o"&gt;&lt;/iframe&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8085117242240449595-5020516417488756839?l=www.shujaat.net' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.shujaat.net/feeds/5020516417488756839/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8085117242240449595&amp;postID=5020516417488756839&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/5020516417488756839'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/5020516417488756839'/><link rel='alternate' type='text/html' href='http://www.shujaat.net/2012/01/entity-framework-42-code-first.html' title='Entity Framework 4.2 Code First'/><author><name>Muhammad Shujaat Siddiqi</name><uri>http://www.blogger.com/profile/02519138704633566929</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://4.bp.blogspot.com/-oS19Oe0xx5s/TxjcV3HaykI/AAAAAAAABEg/-Tj0FUtAokg/s72-c/1.jpg' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8085117242240449595.post-2858775477696202447</id><published>2011-12-23T00:28:00.000-06:00</published><updated>2011-12-30T10:25:19.248-06:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='wpf'/><category scheme='http://www.blogger.com/atom/ns#' term='WPF 4.5'/><category scheme='http://www.blogger.com/atom/ns#' term='WPF 4.5 Developer&apos;s Preview'/><category scheme='http://www.blogger.com/atom/ns#' term='.net'/><category scheme='http://www.blogger.com/atom/ns#' term='XAML'/><category scheme='http://www.blogger.com/atom/ns#' term='.net 4.5'/><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><title type='text'>WPF 4.5 - Accessing DataBound Collections on Non-UI Thread</title><content type='html'>WPF has &lt;i&gt;ItemsControl&lt;/i&gt; to show a collection of items. In MVVM, ItemsControl is data-bound with a collection in the view model. These collections might take a long time to load when the form is being shown. They might be constantly updated throughout the life cycle of the view. If we do it in the main application thread then it might cost the responsiveness of the application. Hence the need for a background thread for these operations. Well, the world has not been so simple. &lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://4.bp.blogspot.com/-mqowHONbv48/TvpqPE_XFKI/AAAAAAAABD4/7fXfE2Cspos/s1600/2.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="198" width="400" src="http://4.bp.blogspot.com/-mqowHONbv48/TvpqPE_XFKI/AAAAAAAABD4/7fXfE2Cspos/s400/2.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;As we know that the UI elements have affinity to the UI thread in WPF. It also does not allow playing with the elements collection bound as &lt;i&gt;DataSource&lt;/i&gt; on any thread other than UI thread. And believe me, &lt;i&gt;this really hurts&lt;/i&gt; !!! All we had were a few workarounds but no real solution. With WPF 4.5 Developer's preview, the situation improves a little. It is a step forward in the direction for providing these updates in some other thread. Although I do think that the way it is provided could be a little better than that but whatever makes my collection available to a non-UI thread. I don't really mind.&lt;br /&gt;&lt;br /&gt;Let's understand this neat feature by creating a simple example. Let's have a simple view with a &lt;i&gt;ListBox&lt;/i&gt;. The ListBox is supposed to display the history of signals received from a central server. &lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://4.bp.blogspot.com/-FLMq8Vr53ZI/TvphgZ8qZxI/AAAAAAAABDs/dD38n2pnKi4/s1600/1.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="267" width="400" src="http://4.bp.blogspot.com/-FLMq8Vr53ZI/TvphgZ8qZxI/AAAAAAAABDs/dD38n2pnKi4/s400/1.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;We can design the above view in XAML as follows:&lt;pre class="brush: xml; gutter: false;"&gt;&lt;br /&gt;&amp;lt;Window x:Class="MVVMCollectionNonUIThread.MainWindow"&lt;br /&gt;        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"&lt;br /&gt;        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&lt;br /&gt;        xmlns:local="clr-namespace:MVVMCollectionNonUIThread"&lt;br /&gt;        Title="MainWindow" Height="350" Width="525"&amp;gt;&lt;br /&gt;    &amp;lt;Window.DataContext&amp;gt;&lt;br /&gt;        &amp;lt;local:MainWindowViewModel /&amp;gt;&lt;br /&gt;    &amp;lt;/Window.DataContext&amp;gt;&lt;br /&gt;    &amp;lt;Grid&amp;gt;&lt;br /&gt;        &amp;lt;Grid.RowDefinitions&amp;gt;&lt;br /&gt;            &amp;lt;RowDefinition Height="30" /&amp;gt;&lt;br /&gt;            &amp;lt;RowDefinition Height="*" /&amp;gt;&lt;br /&gt;        &amp;lt;/Grid.RowDefinitions&amp;gt;&lt;br /&gt;        &amp;lt;Border Background="Navy" Grid.Row="0"&amp;gt;&lt;br /&gt;            &amp;lt;TextBlock Text="WPF 4.5 - Collections Access Across Threads" FontSize="20" &lt;br /&gt;                       Foreground="White" FontWeight="Bold"&lt;br /&gt;                       TextAlignment="Center" VerticalAlignment="Center" /&amp;gt;&lt;br /&gt;        &amp;lt;/Border&amp;gt;&lt;br /&gt;        &amp;lt;ListBox Margin="3,5,3,5" Grid.Row="1" ItemsSource="{Binding RandomList}"  /&amp;gt;&lt;br /&gt;    &amp;lt;/Grid&amp;gt;&lt;br /&gt;&amp;lt;/Window&amp;gt;&lt;br /&gt;&lt;/pre&gt;The above view has &lt;i&gt;MainWindowViewModel&lt;/i&gt; set as the &lt;i&gt;DataContext&lt;/i&gt;. It expects the DataContext to have a collection, named &lt;i&gt;RandomList&lt;/i&gt;. This collection is data-bound to the ListBox so it should have the history of instances when the signal is received from the server. Now let's start defining the view model as per expectation. &lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;namespace MVVMCollectionNonUIThread&lt;br /&gt;{&lt;br /&gt;    using System.Collections.ObjectModel;&lt;br /&gt;    using System.Timers;&lt;br /&gt;    using System.Windows.Data;&lt;br /&gt;&lt;br /&gt;    class MainWindowViewModel&lt;br /&gt;    {&lt;br /&gt;        Timer _t1;&lt;br /&gt;&lt;br /&gt;        ObservableCollection&amp;lt;string&amp;gt; _randomList;&lt;br /&gt;        public ObservableCollection&amp;lt;string&amp;gt; RandomList&lt;br /&gt;        {&lt;br /&gt;            get&lt;br /&gt;            {&lt;br /&gt;                if (_randomList == null)&lt;br /&gt;                {&lt;br /&gt;                    _randomList = new ObservableCollection&amp;lt;string&amp;gt;();&lt;br /&gt;                }&lt;br /&gt;&lt;br /&gt;                return _randomList;&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public MainWindowViewModel()&lt;br /&gt;        {&lt;br /&gt;            _t1 = new Timer(300);&lt;br /&gt;            _t1.Elapsed += new System.Timers.ElapsedEventHandler(_t1_Elapsed);&lt;br /&gt;            _t1.Start();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        void _t1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)&lt;br /&gt;        {&lt;br /&gt;            RandomList.Add(string.Format("Signal Time : {0}", e.SignalTime));&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;In order to simulate the signal reception, we have used &lt;i&gt;System.Timers.Timer&lt;/i&gt;. The timer would tick after at least 300 ms. This event is handled by &lt;i&gt;_t1_Elapsed&lt;/i&gt;. We are just adding an item to &lt;i&gt;RandomList&lt;/i&gt; each time the timer ticks. This event handler is to simulate the signal received from the server. Generally, this client / server communication is handled on a different thread like this handler. Since we are following through this post, if we run the application this results in the EXPECTED exception when the item is being added to &lt;i&gt;RandomList&lt;/i&gt; in &lt;i&gt;_t1_Elapsed&lt;/i&gt; (non-UI thread) [This is generally UNEXPECTED and comes as a surprise if developer doesn't know about it yet.]&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://3.bp.blogspot.com/-UOJv99QHYv4/Tvpyy9uDyOI/AAAAAAAABEE/-3XWKyMU7n4/s1600/3.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="99" width="400" src="http://3.bp.blogspot.com/-UOJv99QHYv4/Tvpyy9uDyOI/AAAAAAAABEE/-3XWKyMU7n4/s400/3.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;FYI: In Winform, we can cause Elapsed event for System.Timers.Timer to be raised in UI thread by setting the SyncrhnizingObject property. We have discussed about this in our timers discussion [&lt;a href="http://shujaatsiddiqi.blogspot.com/2010/10/timers-for-net-applications.html"&gt;http://shujaatsiddiqi.blogspot.com/2010/10/timers-for-net-applications.html&lt;/a&gt;]&lt;br /&gt;&lt;br /&gt;WPF 4.5 Developer's preview has provided certain new static methods in &lt;i&gt;BindingOperations&lt;/i&gt; class to fix this behavior. The list of new methods I could find is as follows:&lt;ol&gt;&lt;li&gt;AccessCollection&lt;/li&gt;&lt;li&gt;DisableCollectionSynchronization&lt;/li&gt;&lt;li&gt;EnableCollectionSynchronization&lt;/li&gt;&lt;/ol&gt;This also have some overloads. Let's see how we can fix our little example with these methods. We really can go around by just using &lt;i&gt;EnableCollectionSynchronization&lt;/i&gt;. It is to report a collection to be accessible in non-UI threads. In order to provide thread synchronization, we need to provide the synchronization mechanism. Simply we can use the overload which needs lock object. Let's update the view model as follows:&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;namespace MVVMCollectionNonUIThread&lt;br /&gt;{&lt;br /&gt;    using System.Collections.ObjectModel;&lt;br /&gt;    using System.Timers;&lt;br /&gt;    using System.Windows.Data;&lt;br /&gt;&lt;br /&gt;    class MainWindowViewModel&lt;br /&gt;    {&lt;br /&gt;        Timer _t1;&lt;br /&gt;        object _lockObj = new object();&lt;br /&gt;&lt;br /&gt;        ObservableCollection&amp;lt;string&amp;gt; _randomList;&lt;br /&gt;        public ObservableCollection&amp;lt;string&amp;gt; RandomList&lt;br /&gt;        {&lt;br /&gt;            get&lt;br /&gt;            {&lt;br /&gt;                if (_randomList == null)&lt;br /&gt;                {&lt;br /&gt;                    _randomList = new ObservableCollection&amp;lt;string&amp;gt;();&lt;br /&gt;                }&lt;br /&gt;&lt;br /&gt;                return _randomList;&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public MainWindowViewModel()&lt;br /&gt;        {&lt;br /&gt;             BindingOperations.EnableCollectionSynchronization(RandomList, _lockObj);&lt;br /&gt;&lt;br /&gt;            _t1 = new Timer(300);&lt;br /&gt;            _t1.Elapsed += new System.Timers.ElapsedEventHandler(_t1_Elapsed);&lt;br /&gt;            _t1.Start();&lt;br /&gt;&lt;br /&gt;            &lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        void _t1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)&lt;br /&gt;        {&lt;br /&gt;            RandomList.Add(string.Format("Signal Time : {0}", e.SignalTime));&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;Here we just have added BindingOperations.EnableCollectionSynchronization to the view model's contructor for the RandomList collection. We have used the instance member &lt;i&gt;_lockObj&lt;/i&gt; as the lock object. That's it! Let's run this now!&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/-IsWoaEYZnXg/Tvp1Ey5-3cI/AAAAAAAABEQ/TStKZLuSDKM/s1600/4.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="267" width="400" src="http://2.bp.blogspot.com/-IsWoaEYZnXg/Tvp1Ey5-3cI/AAAAAAAABEQ/TStKZLuSDKM/s400/4.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;b&gt;Download:&lt;/b&gt;&lt;br /&gt;&lt;iframe title ="Preview" scrolling="no" marginheight="0" marginwidth="0" frameborder="0" width="98px" height="120px" style="padding:0;background-color:#fcfcfc;" src="https://skydrive.live.com/embed?cid=6F3051EF13F3137E&amp;resid=6F3051EF13F3137E%21203&amp;authkey=AMCAKhQZWxd7Z54"&gt;&lt;/iframe&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8085117242240449595-2858775477696202447?l=www.shujaat.net' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.shujaat.net/feeds/2858775477696202447/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8085117242240449595&amp;postID=2858775477696202447&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/2858775477696202447'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/2858775477696202447'/><link rel='alternate' type='text/html' href='http://www.shujaat.net/2011/12/wpf-45-accessing-databound-collections.html' title='WPF 4.5 - Accessing DataBound Collections on Non-UI Thread'/><author><name>Muhammad Shujaat Siddiqi</name><uri>http://www.blogger.com/profile/02519138704633566929</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://4.bp.blogspot.com/-mqowHONbv48/TvpqPE_XFKI/AAAAAAAABD4/7fXfE2Cspos/s72-c/2.jpg' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8085117242240449595.post-2347122112534377079</id><published>2011-12-21T19:51:00.000-06:00</published><updated>2011-12-21T21:01:24.557-06:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='MVVM'/><category scheme='http://www.blogger.com/atom/ns#' term='binding'/><category scheme='http://www.blogger.com/atom/ns#' term='wpf'/><category scheme='http://www.blogger.com/atom/ns#' term='.net'/><category scheme='http://www.blogger.com/atom/ns#' term='visual studio 2011'/><category scheme='http://www.blogger.com/atom/ns#' term='.net 4.5'/><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><category scheme='http://www.blogger.com/atom/ns#' term='databinding'/><category scheme='http://www.blogger.com/atom/ns#' term='delay'/><title type='text'>WPF 4.5 Developer's Preview - Delay Binding</title><content type='html'>In this post, let's discuss one great feature of Binding as in WPF 4.5 Developer's preview. This feature is called &lt;i&gt;Delayed Binding&lt;/i&gt;. As a XAML technologies developers we are specially concerned about the timing when the values are copied between SOURCE and TARGET of binding.&lt;p/&gt;From the very early stages, human has tried finding answer of this question. Who am I? Even famous eastern poet Bulleh Shah explained in one of his master piece.&lt;pre&gt;Not a believer inside the mosque, am I&lt;br /&gt;Nor a pagan disciple of false rites&lt;br /&gt;Not the pure amongst the impure&lt;br /&gt;Neither Moses, nor the Pharoh&lt;br /&gt;Bulleh! to me, I am not known&lt;/pre&gt;&lt;p/&gt;Since WPF / Silverlight has very sophisticated Binding, the difference between Source and Target is blurred. Now the main question is what should be called Source and what should be considered as Binding Target. Although the question is not a philosophical one but we clearly need a way to identify the source and target of Binding. Charles Petzold makes it easier by calling Binding Target to be the one where the Binding is actually defined. Now the other party becomes the Binding Source. So if &lt;i&gt;TextBox.Text&lt;/i&gt; is bound to &lt;i&gt;FirstName&lt;/i&gt; property of the &lt;i&gt;DataContext&lt;/i&gt; then &lt;i&gt;TextBox.Text&lt;/i&gt; becomes the Binding target and hence &lt;i&gt;DataContext.FirstName&lt;/i&gt; might be taken as Binding source.&lt;p/&gt;From &lt;b&gt;Target to Source&lt;/b&gt;, we control the timing by using &lt;i&gt;UpdateSourceTrigger&lt;/i&gt; property of &lt;i&gt;Binding&lt;/i&gt;. As we know that it has three possible modes. &lt;i&gt;PropertyChanged&lt;/i&gt;, &lt;i&gt;LostFocus&lt;/i&gt; and &lt;i&gt;Explicit&lt;/i&gt;. &lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://4.bp.blogspot.com/-YVmT0sgJJpA/TvE5f8FB9YI/AAAAAAAABC8/OCUBbs6nv8k/s1600/2.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="262" width="400" src="http://4.bp.blogspot.com/-YVmT0sgJJpA/TvE5f8FB9YI/AAAAAAAABC8/OCUBbs6nv8k/s400/2.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;p/&gt;From &lt;b&gt;Source to Target&lt;/b&gt;, this flow of update happens based on the nature of &lt;i&gt;Source&lt;/i&gt; property. Generally, the view models implement &lt;i&gt;INotifyPropertyChanged&lt;/i&gt; interface. Now setting the property causes PropertyChanged event to be raised. Binding Target listens to this event and update itself. The event has the details which property of the DataContext is updated which makes it easier for the runtime to update the view. The source property might be a DependencyProperty. As we know one of the feature of &lt;i&gt;DependencyProperty&lt;/i&gt; is change notification. As WPF runtime receives such notifications, it propagates these changes to the Binding system, which causes updating the target's value.&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://1.bp.blogspot.com/-BhGYnpjkP1c/TvE-Y8CiwDI/AAAAAAAABDI/tGS6gTHIhfU/s1600/3.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="262" width="400" src="http://1.bp.blogspot.com/-BhGYnpjkP1c/TvE-Y8CiwDI/AAAAAAAABDI/tGS6gTHIhfU/s400/3.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;p&gt;The direction of flow of these updates are controlled by Binding mode. Different XAML technologies can have different default mode of binding. There are three different Binding modes in WPF / Silverlight. These Binding modes are as follows:&lt;ol&gt;&lt;li&gt;TwoWay&lt;/li&gt;&lt;li&gt;OneWay&lt;/li&gt;&lt;li&gt;OneTime&lt;/li&gt;&lt;li&gt;OneWayToSource&lt;/li&gt;&lt;li&gt;Default&lt;/li&gt;&lt;/ol&gt;Except possibly &lt;i&gt;Default&lt;/i&gt; option, the modes which support flowing the value updates from Target to Source are &lt;i&gt;OneWayToSource&lt;/i&gt; and &lt;i&gt;TwoWay&lt;/i&gt;. It must be noted that the feature we are discussing in this post only applies to this case when the updates are propagated from &lt;i&gt;Target&lt;/i&gt; property to &lt;i&gt;Source&lt;/i&gt; property.&lt;p/&gt;Now the main question is why we need this delay? Basically it is to provide a compromise between two selections for &lt;i&gt;UpdateSourceTrigger&lt;/i&gt;. These selections are &lt;i&gt;PropertyChanged&lt;/i&gt; and &lt;i&gt;LostFocus&lt;/i&gt;. With &lt;i&gt;LostFocus&lt;/i&gt;, the binding system waits until focus is lost from the target control. So all these intermediate updates are lost. If this is a TextBox, the user might expect immediate response from the system. Since updates are not flowing from Target to source, no converters are applied. Similarly none of the validation rules are used. This might be frustrating for the application's user. On the other hand, if we change this to be using &lt;i&gt;PropertyChanged&lt;/i&gt;, all the updates are propagated from Target to Source which might involve value conversion and validation. These operations might cause expensive logic to run. When we are using the control, we don't want to wait until we change focus to the other control. But we, definitely, don't want to run all of this with every key stroke or any other way in which user interaction is causing Target value to be updated. We need a mechanism similar to throttling which helps us in this regard. &lt;b&gt;Binding Delay&lt;/b&gt; is just for the same purpose.&lt;p/&gt;Let's create a simple WPF project &lt;i&gt;MVVMDelayedBinding&lt;/i&gt; as follows:&lt;p/&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://3.bp.blogspot.com/-yaoFB0Anqqg/TvEzvEhjNEI/AAAAAAAABCk/fjuMTKlLnag/s1600/1.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="266" width="400" src="http://3.bp.blogspot.com/-yaoFB0Anqqg/TvEzvEhjNEI/AAAAAAAABCk/fjuMTKlLnag/s400/1.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;p/&gt;Let's add a simple view model. The view model implements &lt;i&gt;INotifyPropertyChanged&lt;/i&gt; interface. The view model just has one property &lt;i&gt;FirstName&lt;/i&gt;. We will be binding this property to a &lt;i&gt;TextBox&lt;/i&gt; in the view. Since we would just be binding this to support the flow of value update from Target to Source, it wouldn't really matter if this supports change notification or not. As a Binding Source, the only requirement is that the source should be a property, change notification support is just to update target from the property updates in the source.&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;namespace MVVMDelayedBinding&lt;br /&gt;{&lt;br /&gt;    using System.ComponentModel;&lt;br /&gt;&lt;br /&gt;    class MainWindowViewModel : INotifyPropertyChanged&lt;br /&gt;    {&lt;br /&gt;        private string _firstName;&lt;br /&gt;        public string FirstName&lt;br /&gt;        {&lt;br /&gt;            get { return _firstName; }&lt;br /&gt;            set&lt;br /&gt;            {&lt;br /&gt;                _firstName = value;&lt;br /&gt;                OnPropertyChanged("FirstName");&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        #region INotifyPropertyChanged implementation&lt;br /&gt;&lt;br /&gt;        public event PropertyChangedEventHandler PropertyChanged = delegate { };&lt;br /&gt;        private void OnPropertyChanged(string propertyName)&lt;br /&gt;        {&lt;br /&gt;            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        #endregion&lt;br /&gt;        &lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;Since this is a &lt;i&gt;WPF 4.5 Developer's Preview&lt;/i&gt; feature, we need .net framework 4.5 installed on the machine. We also need &lt;i&gt;Visual Studio 11 Developer's Preview&lt;/i&gt;. Let's open this in the IDE and update the framework to .net framework 4.5.&lt;p/&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://4.bp.blogspot.com/-JNaQAUt-4AU/TvKGWcNOHkI/AAAAAAAABDU/8KXaU3a8eRI/s1600/4.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="214" width="400" src="http://4.bp.blogspot.com/-JNaQAUt-4AU/TvKGWcNOHkI/AAAAAAAABDU/8KXaU3a8eRI/s400/4.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;p/&gt;Now let's update &lt;i&gt;MainWindow.xaml&lt;/i&gt; as follows:&lt;pre class="brush: xml; gutter: false;"&gt;&lt;br /&gt;&amp;lt;Window x:Class="MVVMDelayedBinding.MainWindow"&lt;br /&gt;        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"&lt;br /&gt;        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&lt;br /&gt;        xmlns:local="clr-namespace:MVVMDelayedBinding"&lt;br /&gt;        Title="MainWindow" Height="350" Width="525"&amp;gt;&lt;br /&gt;    &amp;lt;Window.DataContext&amp;gt;&lt;br /&gt;        &amp;lt;local:MainWindowViewModel /&amp;gt;&lt;br /&gt;    &amp;lt;/Window.DataContext&amp;gt;&lt;br /&gt;    &amp;lt;Grid&amp;gt;&lt;br /&gt;        &amp;lt;Grid.RowDefinitions&amp;gt;&lt;br /&gt;            &amp;lt;RowDefinition Height="45" /&amp;gt;&lt;br /&gt;            &amp;lt;RowDefinition Height="auto" /&amp;gt;&lt;br /&gt;            &amp;lt;RowDefinition Height="*"/&amp;gt;&lt;br /&gt;        &amp;lt;/Grid.RowDefinitions&amp;gt;&lt;br /&gt;        &amp;lt;Grid.ColumnDefinitions&amp;gt;&lt;br /&gt;            &amp;lt;ColumnDefinition Width="0.20*" /&amp;gt;&lt;br /&gt;            &amp;lt;ColumnDefinition Width="*" /&amp;gt;&lt;br /&gt;        &amp;lt;/Grid.ColumnDefinitions&amp;gt;&lt;br /&gt;        &amp;lt;Border Background="Navy" Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2" &amp;gt;&lt;br /&gt;            &amp;lt;TextBlock Text="Personal Information" Foreground="White" FontSize="20"&lt;br /&gt;                       TextAlignment="Center" FontWeight="Bold" VerticalAlignment="Center"/&amp;gt;&lt;br /&gt;        &amp;lt;/Border&amp;gt;&lt;br /&gt;        &amp;lt;Label Content="First Name" Grid.Row="1" Grid.Column="0" Margin="2,3,2,2"/&amp;gt;&lt;br /&gt;        &amp;lt;TextBox Grid.Row="1" Grid.Column="1" Margin="2,3,2,2" &amp;gt;&lt;br /&gt;            &amp;lt;TextBox.Text&amp;gt;&lt;br /&gt;                &amp;lt;Binding Path="FirstName" &lt;br /&gt;                         Mode="OneWayToSource" &lt;br /&gt;                         UpdateSourceTrigger="PropertyChanged"&lt;br /&gt;                         Delay="200" /&amp;gt;&lt;br /&gt;            &amp;lt;/TextBox.Text&amp;gt;&lt;br /&gt;        &amp;lt;/TextBox&amp;gt;&lt;br /&gt;        &amp;lt;Border BorderBrush="Silver" BorderThickness="1" &lt;br /&gt;                Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="2"&amp;gt;&lt;br /&gt;            &amp;lt;TextBlock Text="Other Details" TextAlignment="Center"&lt;br /&gt;                       VerticalAlignment="Center"&lt;br /&gt;                       FontSize="20"/&amp;gt;&lt;br /&gt;        &amp;lt;/Border&amp;gt;&lt;br /&gt;    &amp;lt;/Grid&amp;gt;&lt;br /&gt;&amp;lt;/Window&amp;gt;&lt;br /&gt;&lt;/pre&gt;This is simple example of MVVM based view. We are using the new &lt;i&gt;MainWindowViewModel&lt;/i&gt; instance as the &lt;i&gt;DataContext&lt;/i&gt; of the view. The most interesting thing is the &lt;i&gt;TextBox&lt;/i&gt; Binding. We are binding the TextBox with &lt;i&gt;FirstName&lt;/i&gt; property from the &lt;i&gt;DataContext&lt;/i&gt;. The mode is set as &lt;i&gt;OneWayToSource&lt;/i&gt; supporting the flow of value updates only from Target to Source. The UpdateSourceTrigger is set as &lt;i&gt;PropertyChanged&lt;/i&gt;, resulting in the updates in the Target properties to be copied to the Source without waiting for losing the focus. Now look at the &lt;b&gt;Delay&lt;/b&gt;. We are setting the delay as 200. This is in milliseconds. It means the runtime should wait for 200 ms to copy a property update to the Source. This would throttle fast changes to the view and wait for the interaction to get settled before the view state gets updated. Let's run this and use the First Name as &lt;b&gt;Muhammad&lt;/b&gt;. Instead of the regular behavior of &lt;b&gt;PropertyChanged&lt;/b&gt;. It throttled my input, waited for 200ms and updated the view model's property. This is perfect!&lt;p/&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://1.bp.blogspot.com/-f1CjFs_HOYY/TvKIz0cBB3I/AAAAAAAABDg/fO5jPAMow0w/s1600/5.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="267" width="400" src="http://1.bp.blogspot.com/-f1CjFs_HOYY/TvKIz0cBB3I/AAAAAAAABDg/fO5jPAMow0w/s400/5.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;b&gt;Download:&lt;/b&gt;&lt;p/&gt;&lt;iframe title ="Preview" scrolling="no" marginheight="0" marginwidth="0" frameborder="0" width="98px" height="120px" style="padding:0;background-color:#fcfcfc;" src="https://skydrive.live.com/embed?cid=6F3051EF13F3137E&amp;resid=6F3051EF13F3137E%21202&amp;authkey=AKFcyc3jFebk-Io"&gt;&lt;/iframe&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8085117242240449595-2347122112534377079?l=www.shujaat.net' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.shujaat.net/feeds/2347122112534377079/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8085117242240449595&amp;postID=2347122112534377079&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/2347122112534377079'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/2347122112534377079'/><link rel='alternate' type='text/html' href='http://www.shujaat.net/2011/12/wpf-45-developers-preview-delay-binding.html' title='WPF 4.5 Developer&apos;s Preview - Delay Binding'/><author><name>Muhammad Shujaat Siddiqi</name><uri>http://www.blogger.com/profile/02519138704633566929</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://4.bp.blogspot.com/-YVmT0sgJJpA/TvE5f8FB9YI/AAAAAAAABC8/OCUBbs6nv8k/s72-c/2.jpg' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8085117242240449595.post-4905797068400285194</id><published>2011-08-14T16:52:00.003-05:00</published><updated>2011-08-15T04:14:54.202-05:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='relativesource'/><category scheme='http://www.blogger.com/atom/ns#' term='SILVERLIGHT 5 BETA'/><category scheme='http://www.blogger.com/atom/ns#' term='XAML'/><category scheme='http://www.blogger.com/atom/ns#' term='asynchronous binding'/><category scheme='http://www.blogger.com/atom/ns#' term='Silverlight'/><category scheme='http://www.blogger.com/atom/ns#' term='View Model'/><title type='text'>Silverlight 5 Beta - Relative Source Binding</title><content type='html'>In this post we will be discussing another new feature of Silverlight 5 Beta. It is &lt;i&gt;Relative Source&lt;/i&gt; binding. RelativeSource has long been missing from Silverlight. It has always been there in WPF. &lt;i&gt;Silverlight 5&lt;/i&gt; is currently available in Beta and can be downloaded from here:&lt;br /&gt;&lt;br /&gt;&lt;a href="http://www.microsoft.com/download/en/details.aspx?id=23887"&gt;http://www.microsoft.com/download/en/details.aspx?id=23887&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Let's create a MVVM Light Silverlight application &lt;i&gt;AppSilverlightRelativeSourceBinding&lt;/i&gt;. It would have a list of students on display. The user should be allowed to remove any student on the list. In order to see the application of Relative Source binding, we would see how we can bind the &lt;i&gt;Command&lt;/i&gt; on the child element to a parent element. Actually, the &lt;i&gt;Remove&lt;/i&gt; button on child view should be bound to a Command in the DataContext of a parent element in the hierarchy [UserControl].&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/-1Psi9WLTFdQ/TkWdC1Gj_9I/AAAAAAAABBk/x-V-bPNFcRs/s1600/1.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="252" width="400" src="http://2.bp.blogspot.com/-1Psi9WLTFdQ/TkWdC1Gj_9I/AAAAAAAABBk/x-V-bPNFcRs/s400/1.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;Just make sure that you have Silverlight 5 version selected in the project's properties.&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://4.bp.blogspot.com/-f9S-cLQcztE/TkjjY3S6MAI/AAAAAAAABB0/LybUtxE35ss/s1600/3.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="161" width="400" src="http://4.bp.blogspot.com/-f9S-cLQcztE/TkjjY3S6MAI/AAAAAAAABB0/LybUtxE35ss/s400/3.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;This view model is the Main view model of the application. It has a collection of students (&lt;i&gt;StudentViewModel&lt;/i&gt;). Since the collection is an ObservableCollection, all the addition / removal of elements in the collection would directly reflected in the view. It also has a Command which removes the student from the collection. This is the Command which would be bound by child elements.&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;namespace AppSilverlightRelativeSourceBinding.ViewModel&lt;br /&gt;{&lt;br /&gt;    using GalaSoft.MvvmLight;&lt;br /&gt;    using System.Collections.ObjectModel;&lt;br /&gt;    using GalaSoft.MvvmLight.Command;&lt;br /&gt;&lt;br /&gt;    public class MainViewModel : ViewModelBase&lt;br /&gt;    {&lt;br /&gt;        #region Properties&lt;br /&gt;&lt;br /&gt;        public string Welcome&lt;br /&gt;        {&lt;br /&gt;            get&lt;br /&gt;            {&lt;br /&gt;                return "Silverlight 5 Beta - Relative Source Binding";&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        ObservableCollection&amp;lt;StudentViewModel&amp;gt; _students;&lt;br /&gt;        public ObservableCollection&amp;lt;StudentViewModel&amp;gt; Students&lt;br /&gt;        {&lt;br /&gt;            get&lt;br /&gt;            {&lt;br /&gt;                if (_students == null)&lt;br /&gt;                {&lt;br /&gt;                    _students = new ObservableCollection&amp;lt;StudentViewModel&amp;gt;();&lt;br /&gt;&lt;br /&gt;                    _students.Add(new StudentViewModel() { StudentFirstName = "Kamran", StudentLastName = "Khan" });&lt;br /&gt;                    _students.Add(new StudentViewModel() { StudentFirstName = "Asad", StudentLastName = "Hussain" });&lt;br /&gt;                    _students.Add(new StudentViewModel() { StudentFirstName = "Faisal", StudentLastName = "Lashari" });&lt;br /&gt;                    _students.Add(new StudentViewModel() { StudentFirstName = "Hyder", StudentLastName = "Baloch" });&lt;br /&gt;                    _students.Add(new StudentViewModel() { StudentFirstName = "Baber", StudentLastName = "Chaudhari" });&lt;br /&gt;                }&lt;br /&gt;                return _students;&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        #endregion&lt;br /&gt;&lt;br /&gt;        #region Commands&lt;br /&gt;&lt;br /&gt;        RelayCommand&amp;lt;StudentViewModel&amp;gt; _removeStudentCommand;&lt;br /&gt;        public RelayCommand&amp;lt;StudentViewModel&amp;gt; RemoveStudentCommand&lt;br /&gt;        {&lt;br /&gt;            get&lt;br /&gt;            {&lt;br /&gt;                return _removeStudentCommand ??&lt;br /&gt;                        new RelayCommand&amp;lt;StudentViewModel&amp;gt;((student) =&amp;gt;&lt;br /&gt;                        {&lt;br /&gt;                            if (this.Students.Contains(student))&lt;br /&gt;                            {&lt;br /&gt;                                this.Students.Remove(student);&lt;br /&gt;                            }&lt;br /&gt;                        });&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        #endregion        &lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;The definition of StudentViewModel used above is as follows:&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;namespace AppSilverlightRelativeSourceBinding.ViewModel&lt;br /&gt;{   &lt;br /&gt;    using GalaSoft.MvvmLight;&lt;br /&gt;&lt;br /&gt;    public class StudentViewModel : ViewModelBase&lt;br /&gt;    {&lt;br /&gt;        #region Notifiable Properties&lt;br /&gt;&lt;br /&gt;        string _studentLastName;&lt;br /&gt;        public string StudentLastName&lt;br /&gt;        {&lt;br /&gt;            get { return _studentLastName; }&lt;br /&gt;            set&lt;br /&gt;            {&lt;br /&gt;                _studentLastName = value;&lt;br /&gt;                RaisePropertyChanged("StudentLastName");&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        string _studentFirstName;&lt;br /&gt;        public string StudentFirstName&lt;br /&gt;        {&lt;br /&gt;            get { return _studentFirstName; }&lt;br /&gt;            set&lt;br /&gt;            {&lt;br /&gt;                _studentFirstName = value;&lt;br /&gt;                RaisePropertyChanged("StudentFirstName");&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        #endregion&lt;br /&gt;&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;It simply has two properties for first and last names of a student. The view model inherits from &lt;i&gt;ViewModelBase&lt;/i&gt; which is provided by MVVM Light toolkit. Now let's see how we can display this view model. It is an implicit &lt;i&gt;DataTemplate&lt;/i&gt; to show the student. The first and last names are displayed in a &lt;i&gt;TextBlock&lt;/i&gt;. It also has a &lt;i&gt;Remove&lt;/i&gt; button. Clicking the button would delete the student from the collection. Since &lt;i&gt;StudentViewModel&lt;/i&gt; has no idea about which collection it has been part of and it has to be handled by something which holds this collection. So the button's Command needs to be bound to &lt;i&gt;MainViewModel&lt;/i&gt;. This is why &lt;i&gt;Relative Source&lt;/i&gt; binding makes most sense to be used here. Let's define this &lt;i&gt;DataTemplate&lt;/i&gt; in &lt;i&gt;MainSkin.xaml&lt;/i&gt; resource dictionary provided by MVVM Light.&lt;br /&gt;&lt;pre class="brush: xml; gutter: false;"&gt;&amp;lt;DataTemplate DataType="vm:StudentViewModel" &amp;gt;&lt;br /&gt;    &amp;lt;Grid&amp;gt;&lt;br /&gt;        &amp;lt;Grid.ColumnDefinitions&amp;gt;&lt;br /&gt;            &amp;lt;ColumnDefinition Width="auto" /&amp;gt;&lt;br /&gt;            &amp;lt;ColumnDefinition Width="30" /&amp;gt;&lt;br /&gt;            &amp;lt;ColumnDefinition Width="*" /&amp;gt;&lt;br /&gt;        &amp;lt;/Grid.ColumnDefinitions&amp;gt;&lt;br /&gt;        &amp;lt;Button Content="Remove" Grid.Column="0"                       &lt;br /&gt;                CommandParameter="{Binding}" &amp;gt;                &lt;br /&gt;            &amp;lt;Button.Command&amp;gt;&lt;br /&gt;                &amp;lt;Binding RelativeSource="{RelativeSource AncestorType=UserControl}" &lt;br /&gt;                         Path="DataContext.RemoveStudentCommand" /&amp;gt;&lt;br /&gt;            &amp;lt;/Button.Command&amp;gt;&lt;br /&gt;        &amp;lt;/Button&amp;gt;&lt;br /&gt;        &amp;lt;Border Grid.Column="1" /&amp;gt;&lt;br /&gt;        &amp;lt;Grid Grid.Column="2" &amp;gt;&lt;br /&gt;            &amp;lt;TextBlock&amp;gt;  &lt;br /&gt;                &amp;lt;Run Text="{Binding StudentLastName}" FontWeight="Bold" /&amp;gt;&lt;br /&gt;                &amp;lt;Run&amp;gt;&lt;br /&gt;                    &amp;lt;Run.Text&amp;gt;&lt;br /&gt;                        &amp;lt;Binding Path="StudentFirstName" StringFormat=",{0}" /&amp;gt;&lt;br /&gt;                    &amp;lt;/Run.Text&amp;gt;&lt;br /&gt;                    &amp;lt;/Run&amp;gt;&lt;br /&gt;            &amp;lt;/TextBlock&amp;gt;&lt;br /&gt;        &amp;lt;/Grid&amp;gt;&lt;br /&gt;    &amp;lt;/Grid&amp;gt;&lt;br /&gt;&amp;lt;/DataTemplate&amp;gt;&lt;/pre&gt;We need to include this namespace in the above resource dictionary.&lt;br /&gt;&lt;pre class="brush: xml; gutter: false;"&gt;xmlns:vm="clr-namespace:AppSilverlightRelativeSourceBinding.ViewModel"&lt;/pre&gt;Now the design of MainPage is simple enough. Mainly it has a ListBox to display the collection of &lt;i&gt;StudentViewModel&lt;/i&gt;. Since &lt;i&gt;MainSkin.xaml&lt;/i&gt; resource dictionary is merged here, the implicit &lt;i&gt;DataTemplate&lt;/i&gt; is automatically applied.&lt;br /&gt;&lt;pre class="brush: xml; gutter: false;"&gt;&amp;lt;UserControl x:Class="AppSilverlightRelativeSourceBinding.MainPage"&lt;br /&gt;             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"&lt;br /&gt;             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&lt;br /&gt;             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"&lt;br /&gt;             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"&lt;br /&gt;             mc:Ignorable="d"            &lt;br /&gt;             DataContext="{Binding Main, Source={StaticResource Locator}}"&amp;gt;&lt;br /&gt;    &amp;lt;UserControl.Resources&amp;gt;&lt;br /&gt;        &amp;lt;ResourceDictionary&amp;gt;&lt;br /&gt;            &amp;lt;ResourceDictionary.MergedDictionaries&amp;gt;&lt;br /&gt;                &amp;lt;ResourceDictionary Source="Skins/MainSkin.xaml" /&amp;gt;&lt;br /&gt;            &amp;lt;/ResourceDictionary.MergedDictionaries&amp;gt;&lt;br /&gt;        &amp;lt;/ResourceDictionary&amp;gt;&lt;br /&gt;    &amp;lt;/UserControl.Resources&amp;gt;&lt;br /&gt;    &amp;lt;Grid x:Name="LayoutRoot"&amp;gt;&lt;br /&gt;        &amp;lt;Grid.RowDefinitions&amp;gt;&lt;br /&gt;            &amp;lt;RowDefinition Height="auto" /&amp;gt;&lt;br /&gt;            &amp;lt;RowDefinition Height="*" /&amp;gt;&lt;br /&gt;        &amp;lt;/Grid.RowDefinitions&amp;gt;&lt;br /&gt;        &amp;lt;TextBlock FontSize="36" Grid.Row="0"&lt;br /&gt;                   FontWeight="Bold"&lt;br /&gt;                   Foreground="Purple"&lt;br /&gt;                   Text="{Binding Welcome}"&lt;br /&gt;                   VerticalAlignment="Center"&lt;br /&gt;                   HorizontalAlignment="Center"&lt;br /&gt;                   TextWrapping="Wrap" /&amp;gt;&lt;br /&gt;        &amp;lt;ListBox ItemsSource="{Binding Students}"&lt;br /&gt;                 Grid.Row="1" /&amp;gt;&lt;br /&gt;    &amp;lt;/Grid&amp;gt;&lt;br /&gt;&amp;lt;/UserControl&amp;gt;&lt;/pre&gt;When we run the application, the application is loaded as follows:&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://3.bp.blogspot.com/-DjLQCun2qUo/TkhCj8LNJhI/AAAAAAAABBs/0nE15iyj6Bc/s1600/2.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="337" width="400" src="http://3.bp.blogspot.com/-DjLQCun2qUo/TkhCj8LNJhI/AAAAAAAABBs/0nE15iyj6Bc/s400/2.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;b&gt;Download Code:&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;&lt;iframe title ="Preview" scrolling="no" marginheight="0" marginwidth="0" frameborder="0" style="width:98px;height:115px;padding:0;background-color:#fcfcfc;" src="https://skydrive.live.com/embedicon.aspx/.Public/AppSilverlightRelativeSourceBinding.zip?cid=6f3051ef13f3137e&amp;sc=documents"&gt;&lt;/iframe&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8085117242240449595-4905797068400285194?l=www.shujaat.net' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.shujaat.net/feeds/4905797068400285194/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8085117242240449595&amp;postID=4905797068400285194&amp;isPopup=true' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/4905797068400285194'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/4905797068400285194'/><link rel='alternate' type='text/html' href='http://www.shujaat.net/2011/08/in-this-post-we-will-be-discussing.html' title='Silverlight 5 Beta - Relative Source Binding'/><author><name>Muhammad Shujaat Siddiqi</name><uri>http://www.blogger.com/profile/02519138704633566929</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://2.bp.blogspot.com/-1Psi9WLTFdQ/TkWdC1Gj_9I/AAAAAAAABBk/x-V-bPNFcRs/s72-c/1.jpg' height='72' width='72'/><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8085117242240449595.post-8262917896264727350</id><published>2011-08-12T07:44:00.001-05:00</published><updated>2011-08-12T07:45:11.329-05:00</updated><title type='text'>Silverlight 5 Beta - Binding Style's Setter.Value</title><content type='html'>In this post we will be discussing a binding enhancements in Silverlight 5. Now Style's Setters also support binding for their &lt;i&gt;Value&lt;/i&gt; property. &lt;i&gt;Silverlight 5&lt;/i&gt; is currently available in Beta and can be downloaded from here:&lt;br /&gt;&lt;br /&gt;&lt;a href="http://www.microsoft.com/download/en/details.aspx?id=23887"&gt;http://www.microsoft.com/download/en/details.aspx?id=23887&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Let's consider a simple example in which we need to define an application banner in a &lt;i&gt;TextBlock&lt;/i&gt;. The application banner will provided by the view model so it needs to be bound to the &lt;i&gt;TextBlock&lt;/i&gt;'s &lt;i&gt;Text&lt;/i&gt; property using Binding extension.&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://1.bp.blogspot.com/-7PvUFsYlxYc/TkC0eWlxDII/AAAAAAAABBM/xZo-hXi1dEM/s1600/1.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="262" width="400" src="http://1.bp.blogspot.com/-7PvUFsYlxYc/TkC0eWlxDII/AAAAAAAABBM/xZo-hXi1dEM/s400/1.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;Let's consider a simple example in which we need to define an application banner in a &lt;i&gt;TextBlock&lt;/i&gt;. The application banner will provided by the view model so it needs to be bound to the &lt;i&gt;TextBlock&lt;/i&gt;'s Text property using Binding extension. Let's update the &lt;i&gt;MainPage&lt;/i&gt; as follows:&lt;br /&gt;&lt;pre class="brush: xml; gutter: false;"&gt;&amp;lt;UserControl x:Class="AppSilverlightBindingInStyle.MainPage"&lt;br /&gt;        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"&lt;br /&gt;        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&lt;br /&gt;        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"&lt;br /&gt;        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"&lt;br /&gt;        xmlns:local="clr-namespace:AppSilverlightBindingInStyle"&lt;br /&gt;        mc:Ignorable="d"&lt;br /&gt;        d:DesignHeight="300" d:DesignWidth="400"&amp;gt;&lt;br /&gt;    &amp;lt;UserControl.DataContext&amp;gt;&lt;br /&gt;        &amp;lt;local:MainViewModel BannerText ="Application Banner" /&amp;gt;&lt;br /&gt;    &amp;lt;/UserControl.DataContext&amp;gt;&lt;br /&gt;    &amp;lt;UserControl.Resources&amp;gt;&lt;br /&gt;        &amp;lt;Style TargetType="TextBlock" &amp;gt;            &lt;br /&gt;            &amp;lt;Setter Property="Text" Value="{Binding BannerText}" /&amp;gt;&lt;br /&gt;            &amp;lt;Setter Property="FontSize" Value="30" /&amp;gt;           &lt;br /&gt;        &amp;lt;/Style&amp;gt;&lt;br /&gt;    &amp;lt;/UserControl.Resources&amp;gt;&lt;br /&gt;    &amp;lt;Grid x:Name="LayoutRoot" Background="White"&amp;gt;&lt;br /&gt;        &amp;lt;TextBlock Name="bannerBox" TextAlignment="Center" /&amp;gt;&lt;br /&gt;    &amp;lt;/Grid&amp;gt;&lt;br /&gt;&amp;lt;/UserControl&amp;gt;&lt;br /&gt;&lt;/pre&gt;It has a simple &lt;i&gt;TextBlock&lt;/i&gt; in the view. The &lt;i&gt;DataContext&lt;/i&gt; is specified as MainViewModel. It has an inline assignment to its &lt;i&gt;BannerText&lt;/i&gt; property. In the &lt;i&gt;Resources&lt;/i&gt; we have a &lt;i&gt;Style&lt;/i&gt; defined for the TextBlock. This would serve as the default Style of any TextBlock in the page unless overriden. Look at how we are able to bind the &lt;i&gt;Value&lt;/i&gt; property of Style's Setter.&lt;br /&gt;&lt;br /&gt;The view model just needs to have a property &lt;i&gt;BannerText&lt;/i&gt;. The definition of &lt;i&gt;MainViewModel&lt;/i&gt; used as &lt;i&gt;DataContext&lt;/i&gt; in the above view is as follows:&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;namespace AppSilverlightBindingInStyle&lt;br /&gt;{&lt;br /&gt;    using System.ComponentModel;&lt;br /&gt;&lt;br /&gt;    public class MainViewModel : INotifyPropertyChanged&lt;br /&gt;    {&lt;br /&gt;        #region Properties&lt;br /&gt;&lt;br /&gt;        string _bannerText;&lt;br /&gt;        public string BannerText&lt;br /&gt;        {&lt;br /&gt;            get { return _bannerText; }&lt;br /&gt;            set&lt;br /&gt;            {&lt;br /&gt;                _bannerText = value;&lt;br /&gt;                OnPropertyChanged("BannerText");&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        #endregion&lt;br /&gt;        &lt;br /&gt;        #region INotifyPropertyChanged implementation&lt;br /&gt;&lt;br /&gt;        public event PropertyChangedEventHandler PropertyChanged = delegate { };&lt;br /&gt;        private void OnPropertyChanged(string propertyName)&lt;br /&gt;        {&lt;br /&gt;            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        #endregion        &lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;When we run the application, it is shown as follows:&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://1.bp.blogspot.com/-gBbxYWI3Emc/TkUdUz1-PWI/AAAAAAAABBc/MV2uLg4ATrE/s1600/2.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="315" width="400" src="http://1.bp.blogspot.com/-gBbxYWI3Emc/TkUdUz1-PWI/AAAAAAAABBc/MV2uLg4ATrE/s400/2.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;b&gt;Download Code:&lt;/b&gt;&lt;br /&gt;&lt;iframe title ="Preview" scrolling="no" marginheight="0" marginwidth="0" frameborder="0" style="width:98px;height:115px;padding:0;background-color:#fcfcfc;" src="https://skydrive.live.com/embedicon.aspx/.Public/AppSilverlightBindingInStyle.zip?cid=6f3051ef13f3137e&amp;sc=documents"&gt;&lt;/iframe&gt;&lt;br /&gt;&lt;br /&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8085117242240449595-8262917896264727350?l=www.shujaat.net' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.shujaat.net/feeds/8262917896264727350/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8085117242240449595&amp;postID=8262917896264727350&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/8262917896264727350'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/8262917896264727350'/><link rel='alternate' type='text/html' href='http://www.shujaat.net/2011/08/silverlight-5-beta-binding-styles.html' title='Silverlight 5 Beta - Binding Style&apos;s Setter.Value'/><author><name>Muhammad Shujaat Siddiqi</name><uri>http://www.blogger.com/profile/02519138704633566929</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://1.bp.blogspot.com/-7PvUFsYlxYc/TkC0eWlxDII/AAAAAAAABBM/xZo-hXi1dEM/s72-c/1.jpg' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8085117242240449595.post-7878186334503269482</id><published>2011-08-08T18:03:00.000-05:00</published><updated>2011-08-08T18:03:10.318-05:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='SILVERLIGHT 5 BETA'/><category scheme='http://www.blogger.com/atom/ns#' term='XAML'/><category scheme='http://www.blogger.com/atom/ns#' term='asynch wpf'/><category scheme='http://www.blogger.com/atom/ns#' term='Silverlight'/><category scheme='http://www.blogger.com/atom/ns#' term='new features'/><category scheme='http://www.blogger.com/atom/ns#' term='implicit DataTemplate'/><category scheme='http://www.blogger.com/atom/ns#' term='DataTemplate'/><title type='text'>Implicit DataTempates in Silverlight 5 Beta</title><content type='html'>In this post we are going to discuss a new feature expected to be released in Silverlight 5. This feature is implicit &lt;b&gt;DataTemplates&lt;/b&gt;. Those who come from WPF background to Silverlight often find it difficult to design without implicit DataTemplates. Well, this limitation has been worked in Silverlight 5 and it is available in the beta release. Silverlight 5 beta tools can be downloaded from here:&lt;br /&gt;&lt;br /&gt;&lt;a href="http://www.microsoft.com/download/en/details.aspx?id=23887"&gt;http://www.microsoft.com/download/en/details.aspx?id=23887&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Let's create a sample Silverlight application and name it &lt;i&gt;AppSilverlightImplicitDataTemplates&lt;/i&gt;. &lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://4.bp.blogspot.com/-ZQqOiGtrLdk/Tj83-jIcv8I/AAAAAAAABAc/7TiBV5GGI50/s1600/1.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="244" width="400" src="http://4.bp.blogspot.com/-ZQqOiGtrLdk/Tj83-jIcv8I/AAAAAAAABAc/7TiBV5GGI50/s400/1.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;Make sure that you have Silverlight 5 option selected in the following screen displayed right after the previous one.&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://1.bp.blogspot.com/-5lP1IR2KDp0/Tj85IgZFRdI/AAAAAAAABAk/7Qq_rh_bE7k/s1600/2.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="320" width="400" src="http://1.bp.blogspot.com/-5lP1IR2KDp0/Tj85IgZFRdI/AAAAAAAABAk/7Qq_rh_bE7k/s400/2.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;You would need a reference of System.Windows.Controls.Data.Input assembly for Labels. If you directly drag and drop the Label Control from Toolbox on the designer surface, the assembly is automatically referenced.&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://1.bp.blogspot.com/-E4zKd56uuyo/Tj9m1ppFdwI/AAAAAAAABAs/b9V1wO8A9Hg/s1600/3.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="230" width="400" src="http://1.bp.blogspot.com/-E4zKd56uuyo/Tj9m1ppFdwI/AAAAAAAABAs/b9V1wO8A9Hg/s400/3.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;Let's suppose we have the following view model. It has a collection of students. We want the user to select a particular student and allow that to be edited. &lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;namespace AppSilverlightImplicitDataTemplates&lt;br /&gt;{&lt;br /&gt;    using System.Collections.ObjectModel;&lt;br /&gt;    using System.Collections.Generic;&lt;br /&gt;&lt;br /&gt;    public class MainViewModel : ViewModelBase&lt;br /&gt;    {&lt;br /&gt;        ObservableCollection&amp;lt;StudentViewModel&amp;gt; _students;&lt;br /&gt;        public  ObservableCollection&amp;lt;StudentViewModel&amp;gt; Students&lt;br /&gt;        {&lt;br /&gt;            get&lt;br /&gt;            {&lt;br /&gt;                if (_students == null)&lt;br /&gt;                {&lt;br /&gt;                    _students = new ObservableCollection&amp;lt;StudentViewModel&amp;gt;();&lt;br /&gt;                    _students.Add(new StudentViewModel() { StudentFirstName = "Muhammad", StudentLastName = "Siddiqi" });&lt;br /&gt;                    _students.Add(new StudentViewModel() { StudentFirstName = "Jayson", StudentLastName = "Abante" });&lt;br /&gt;                    _students.Add(new StudentViewModel() { StudentFirstName = "Meena", StudentLastName = "Gulla" });                                        &lt;br /&gt;                }&lt;br /&gt;                return _students;&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;The view model is inheriting from &lt;i&gt;ViewModelBase&lt;/i&gt; class. It is basically for providing general functionality to all view models specially implementation of &lt;i&gt;INotifyPropertyChanged&lt;/i&gt; interface. As you might have guessed, like this view model, all others view models in the application would also be inheriting from this.&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;namespace AppSilverlightImplicitDataTemplates&lt;br /&gt;{&lt;br /&gt;    using System.ComponentModel;&lt;br /&gt;&lt;br /&gt;    public class ViewModelBase : INotifyPropertyChanged&lt;br /&gt;    {&lt;br /&gt;        #region INotifyPropertyChanged Implementation&lt;br /&gt;&lt;br /&gt;        public event PropertyChangedEventHandler PropertyChanged = delegate { };&lt;br /&gt;        protected void OnPropertyChanged(string propertyName)&lt;br /&gt;        {&lt;br /&gt;            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        #endregion&lt;br /&gt;&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;In &lt;i&gt;MainViewModel&lt;/i&gt; we have used &lt;i&gt;StudentViewModel&lt;/i&gt; collection. It basically has two properties &lt;i&gt;StudentFirstName&lt;/i&gt; and &lt;i&gt;StudentLastName&lt;/i&gt;. Its definition can be as follows:&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;namespace AppSilverlightImplicitDataTemplates&lt;br /&gt;{&lt;br /&gt;    using System.ComponentModel;&lt;br /&gt;&lt;br /&gt;    public class StudentViewModel : ViewModelBase&lt;br /&gt;    {&lt;br /&gt;        #region Notifiable Properties&lt;br /&gt;&lt;br /&gt;        string _studentLastName;&lt;br /&gt;        public string StudentLastName&lt;br /&gt;        {&lt;br /&gt;            get { return _studentLastName; }&lt;br /&gt;            set&lt;br /&gt;            {&lt;br /&gt;                _studentLastName = value;&lt;br /&gt;                OnPropertyChanged("StudentLastName");&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        string _studentFirstName;&lt;br /&gt;        public string StudentFirstName&lt;br /&gt;        {&lt;br /&gt;            get { return _studentFirstName; }&lt;br /&gt;            set&lt;br /&gt;            {&lt;br /&gt;                _studentFirstName = value;&lt;br /&gt;                OnPropertyChanged("StudentFirstName");&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        #endregion&lt;br /&gt;&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;As you can see above, it also inherits from &lt;i&gt;ViewModelBase&lt;/i&gt;. The two properties support change notification by calling &lt;i&gt;OnPropertyChanged&lt;/i&gt; method. In turn this would raise &lt;i&gt;PropertyChanged&lt;/i&gt; event. As we have discussed already that we would be needing to use this view model in two different types of views. One is just for display for selection based control used to display the collection of students. We also need a different view to allow a student to be edited. &lt;br /&gt;&lt;br /&gt;&lt;b&gt;For displaying in collection based control:&lt;/b&gt;&lt;br /&gt;&lt;pre class="brush: xml; gutter: false;"&gt;&amp;lt;UserControl x:Class="AppSilverlightImplicitDataTemplates.StudentDisplayView"&lt;br /&gt;        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"&lt;br /&gt;        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&lt;br /&gt;        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"&lt;br /&gt;        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"&lt;br /&gt;        mc:Ignorable="d" &amp;gt;    &lt;br /&gt;    &amp;lt;TextBlock&amp;gt;&lt;br /&gt;        &amp;lt;Run Text="{Binding StudentLastName}" FontWeight="Bold" /&amp;gt;&lt;br /&gt;        &amp;lt;Run Text="," /&amp;gt;&lt;br /&gt;        &amp;lt;Run Text="{Binding StudentFirstName}" /&amp;gt;&lt;br /&gt;    &amp;lt;/TextBlock&amp;gt;&lt;br /&gt;&amp;lt;/UserControl&amp;gt;&lt;/pre&gt;&lt;br /&gt;&lt;b&gt;For editing StudentViewModel:&lt;/b&gt;&lt;br /&gt;&lt;pre class="brush: xml; gutter: false;"&gt;&amp;lt;UserControl x:Class="AppSilverlightImplicitDataTemplates.StudentEditView"&lt;br /&gt;        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"&lt;br /&gt;        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&lt;br /&gt;        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"&lt;br /&gt;        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"    &lt;br /&gt;        mc:Ignorable="d"&lt;br /&gt;        xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk" &amp;gt;&lt;br /&gt;    &amp;lt;Grid x:Name="LayoutRoot" Background="White"&amp;gt;&lt;br /&gt;        &amp;lt;Grid.ColumnDefinitions&amp;gt;&lt;br /&gt;            &amp;lt;ColumnDefinition Width="93" /&amp;gt;&lt;br /&gt;            &amp;lt;ColumnDefinition Width="307" /&amp;gt;&lt;br /&gt;        &amp;lt;/Grid.ColumnDefinitions&amp;gt;&lt;br /&gt;        &amp;lt;Grid.RowDefinitions&amp;gt;           &lt;br /&gt;            &amp;lt;RowDefinition Height="35" /&amp;gt;&lt;br /&gt;            &amp;lt;RowDefinition Height="*" /&amp;gt;            &lt;br /&gt;        &amp;lt;/Grid.RowDefinitions&amp;gt;     &lt;br /&gt;        &amp;lt;sdk:Label Height="23" HorizontalAlignment="Left"&lt;br /&gt;                   Margin="12,12,0,0"  VerticalAlignment="Top"                    &lt;br /&gt;                   Content="First Name" Width="83" Grid.ColumnSpan="2" /&amp;gt;&lt;br /&gt;        &amp;lt;TextBox Height="23" HorizontalAlignment="Left" Margin="8,8,0,0" &lt;br /&gt;                 VerticalAlignment="Top" Width="287" Text="{Binding StudentFirstName}" Grid.Column="1" /&amp;gt;&lt;br /&gt;        &amp;lt;sdk:Label Content="Last Name" Height="23" HorizontalAlignment="Left" &lt;br /&gt;                   Margin="12,7,0,0" VerticalAlignment="Top" Width="83" Grid.Row="1" Grid.ColumnSpan="2" /&amp;gt;&lt;br /&gt;        &amp;lt;TextBox Height="23" HorizontalAlignment="Left" Margin="8,3,0,0" &lt;br /&gt;                 VerticalAlignment="Top" Width="287" Grid.Row="1" &lt;br /&gt;                 Text="{Binding StudentLastName}" Grid.Column="1" /&amp;gt;&lt;br /&gt;    &amp;lt;/Grid&amp;gt;&lt;br /&gt;&amp;lt;/UserControl&amp;gt;&lt;/pre&gt;&lt;br /&gt;&lt;b&gt;Using UserControls in DataTemplate&lt;/b&gt;&lt;br /&gt;By default we need the StudentViewModel type of objects to be using the display one. So we can define it as application resource. Just updated &lt;i&gt;App.xaml&lt;/i&gt; as follows:&lt;br /&gt;&lt;pre class="brush: xml; gutter: false;"&gt;&amp;lt;Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"&lt;br /&gt;             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" &lt;br /&gt;             x:Class="AppSilverlightImplicitDataTemplates.App"&lt;br /&gt;             xmlns:local="clr-namespace:AppSilverlightImplicitDataTemplates"&lt;br /&gt;             &amp;gt;&lt;br /&gt;    &amp;lt;Application.Resources&amp;gt;&lt;br /&gt;        &amp;lt;DataTemplate DataType="local:StudentViewModel"&amp;gt;&lt;br /&gt;            &amp;lt;local:StudentDisplayView /&amp;gt;&lt;br /&gt;        &amp;lt;/DataTemplate&amp;gt;&lt;br /&gt;    &amp;lt;/Application.Resources&amp;gt;&lt;br /&gt;&amp;lt;/Application&amp;gt;&lt;/pre&gt;Now we define the Main application view. As we have discussed, we need to provide a collection of Students and allow the user to select any one of them and edit that.&lt;br /&gt;&lt;pre class="brush: xml; gutter: false;"&gt;&amp;lt;UserControl x:Class="AppSilverlightImplicitDataTemplates.MainPage"&lt;br /&gt;        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"&lt;br /&gt;        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&lt;br /&gt;        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"&lt;br /&gt;        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"&lt;br /&gt;        xmlns:local="clr-namespace:AppSilverlightImplicitDataTemplates"&lt;br /&gt;        mc:Ignorable="d"&lt;br /&gt;        d:DesignHeight="300" d:DesignWidth="400"&lt;br /&gt;        xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"&amp;gt;&lt;br /&gt;    &amp;lt;UserControl.DataContext&amp;gt;&lt;br /&gt;        &amp;lt;local:MainViewModel /&amp;gt;&lt;br /&gt;    &amp;lt;/UserControl.DataContext&amp;gt;    &lt;br /&gt;    &amp;lt;Grid x:Name="LayoutRoot" Background="White"&amp;gt;&lt;br /&gt;        &amp;lt;Grid.ColumnDefinitions&amp;gt;&lt;br /&gt;            &amp;lt;ColumnDefinition Width="97*" /&amp;gt;&lt;br /&gt;            &amp;lt;ColumnDefinition Width="303*" /&amp;gt;&lt;br /&gt;        &amp;lt;/Grid.ColumnDefinitions&amp;gt;&lt;br /&gt;        &amp;lt;Grid.RowDefinitions&amp;gt;&lt;br /&gt;            &amp;lt;RowDefinition Height="43*" /&amp;gt;&lt;br /&gt;            &amp;lt;RowDefinition Height="257*" /&amp;gt;&lt;br /&gt;        &amp;lt;/Grid.RowDefinitions&amp;gt;&lt;br /&gt;        &amp;lt;sdk:Label Height="22" HorizontalAlignment="Left" Margin="11,18,0,0"&lt;br /&gt;                   Name="label1" VerticalAlignment="Top" Width="86"&lt;br /&gt;                   Content="Select Student" DataContext="{Binding Path=Students}" /&amp;gt;&lt;br /&gt;        &amp;lt;ComboBox Height="24" HorizontalAlignment="Left" Margin="6,14,0,0"&lt;br /&gt;                  Name="cmbStudents" VerticalAlignment="Top" Width="285"&lt;br /&gt;                  ItemsSource="{Binding Students}" Grid.Column="1" /&amp;gt;&lt;br /&gt;        &amp;lt;ContentControl &lt;br /&gt;            DataContext="{Binding ElementName=cmbStudents, Path=SelectedItem}" &lt;br /&gt;            Content="{Binding}" Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2" &lt;br /&gt;            Margin="11,18,0,0"/&amp;gt;&lt;br /&gt;    &amp;lt;/Grid&amp;gt;&lt;br /&gt;&amp;lt;/UserControl&amp;gt;&lt;br /&gt;&lt;/pre&gt;Now lets run the application. It appears as follows:&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://3.bp.blogspot.com/-z_LsAGQyMKc/Tj_aUNL1BoI/AAAAAAAABA0/IuwWjRx0boc/s1600/4.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="283" width="400" src="http://3.bp.blogspot.com/-z_LsAGQyMKc/Tj_aUNL1BoI/AAAAAAAABA0/IuwWjRx0boc/s400/4.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;Now select a student from the combo box. The same student is loaded in the &lt;i&gt;ContentControl&lt;/i&gt; as follows:&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://1.bp.blogspot.com/-Is_bDNtBAgs/Tj_aametBYI/AAAAAAAABA8/G78zyAwvWDs/s1600/5.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="283" width="400" src="http://1.bp.blogspot.com/-Is_bDNtBAgs/Tj_aametBYI/AAAAAAAABA8/G78zyAwvWDs/s400/5.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;Now we need the &lt;i&gt;ContentControl&lt;/i&gt; to be using the editing type of &lt;i&gt;UserControl&lt;/i&gt; for &lt;i&gt;StudentViewModel&lt;/i&gt; so that it could be edited. Let's override it as follows in the main view:&lt;br /&gt;&lt;pre class="brush: xml; gutter: false;"&gt;&amp;lt;UserControl x:Class="AppSilverlightImplicitDataTemplates.MainPage"&lt;br /&gt;        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"&lt;br /&gt;        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&lt;br /&gt;        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"&lt;br /&gt;        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"&lt;br /&gt;        xmlns:local="clr-namespace:AppSilverlightImplicitDataTemplates"&lt;br /&gt;        mc:Ignorable="d"&lt;br /&gt;        d:DesignHeight="300" d:DesignWidth="400"&lt;br /&gt;        xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"&amp;gt;&lt;br /&gt;    &amp;lt;UserControl.DataContext&amp;gt;&lt;br /&gt;        &amp;lt;local:MainViewModel /&amp;gt;&lt;br /&gt;    &amp;lt;/UserControl.DataContext&amp;gt;    &lt;br /&gt;    &amp;lt;Grid x:Name="LayoutRoot" Background="White"&amp;gt;&lt;br /&gt;        &amp;lt;Grid.ColumnDefinitions&amp;gt;&lt;br /&gt;            &amp;lt;ColumnDefinition Width="97*" /&amp;gt;&lt;br /&gt;            &amp;lt;ColumnDefinition Width="303*" /&amp;gt;&lt;br /&gt;        &amp;lt;/Grid.ColumnDefinitions&amp;gt;&lt;br /&gt;        &amp;lt;Grid.RowDefinitions&amp;gt;&lt;br /&gt;            &amp;lt;RowDefinition Height="43*" /&amp;gt;&lt;br /&gt;            &amp;lt;RowDefinition Height="257*" /&amp;gt;&lt;br /&gt;        &amp;lt;/Grid.RowDefinitions&amp;gt;&lt;br /&gt;        &amp;lt;sdk:Label Height="22" HorizontalAlignment="Left" Margin="11,18,0,0"&lt;br /&gt;                   Name="label1" VerticalAlignment="Top" Width="86"&lt;br /&gt;                   Content="Select Student" DataContext="{Binding Path=Students}" /&amp;gt;&lt;br /&gt;        &amp;lt;ComboBox Height="24" HorizontalAlignment="Left" Margin="6,14,0,0"&lt;br /&gt;                  Name="cmbStudents" VerticalAlignment="Top" Width="285"&lt;br /&gt;                  ItemsSource="{Binding Students}" Grid.Column="1" /&amp;gt;&lt;br /&gt;        &amp;lt;StackPanel Margin="11,18,0,0" Grid.Row="1" &lt;br /&gt;                    Grid.Column="0" Grid.ColumnSpan="2" &amp;gt;&lt;br /&gt;            &amp;lt;StackPanel.Resources&amp;gt;&lt;br /&gt;                &amp;lt;DataTemplate DataType="local:StudentViewModel" &amp;gt;&lt;br /&gt;                    &amp;lt;local:StudentEditView /&amp;gt;&lt;br /&gt;                &amp;lt;/DataTemplate&amp;gt;&lt;br /&gt;            &amp;lt;/StackPanel.Resources&amp;gt;&lt;br /&gt;            &amp;lt;ContentControl &lt;br /&gt;            DataContext="{Binding ElementName=cmbStudents, Path=SelectedItem}" &lt;br /&gt;            Content="{Binding}" &lt;br /&gt;            /&amp;gt;&lt;br /&gt;        &amp;lt;/StackPanel&amp;gt;&lt;br /&gt;    &amp;lt;/Grid&amp;gt;&lt;br /&gt;&amp;lt;/UserControl&amp;gt;&lt;/pre&gt;Here we have thrown the &lt;i&gt;ContentControl&lt;/i&gt; inside a &lt;i&gt;StackPanel&lt;/i&gt;. In the Resources section of the &lt;i&gt;StackPanel&lt;/i&gt;, we have overridden the &lt;i&gt;DataTemplate&lt;/i&gt; for &lt;i&gt;StudentViewModel&lt;/i&gt;. Since local resource have preference over application level resources so this &lt;i&gt;DataTemplate&lt;/i&gt; is applied for the &lt;i&gt;StudentViewModel&lt;/i&gt; in &lt;i&gt;ContentControl&lt;/i&gt;. When we run the application and select a student, the instance is loaded in the &lt;i&gt;ContentControl&lt;/i&gt; with correct &lt;i&gt;DataTemplate&lt;/i&gt; applied.&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://4.bp.blogspot.com/-bZFjFUCmJFw/TkBpceh8hWI/AAAAAAAABBE/TVpNhU78bZA/s1600/6.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="386" width="400" src="http://4.bp.blogspot.com/-bZFjFUCmJFw/TkBpceh8hWI/AAAAAAAABBE/TVpNhU78bZA/s400/6.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;b&gt;Download:&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;&lt;iframe title ="Preview" scrolling="no" marginheight="0" marginwidth="0" frameborder="0" style="width:98px;height:115px;padding:0;background-color:#fcfcfc;" src="https://skydrive.live.com/embedicon.aspx/.Public/SilverlightImplicitDataTemplates.zip?cid=6f3051ef13f3137e&amp;sc=documents"&gt;&lt;/iframe&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8085117242240449595-7878186334503269482?l=www.shujaat.net' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.shujaat.net/feeds/7878186334503269482/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8085117242240449595&amp;postID=7878186334503269482&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/7878186334503269482'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/7878186334503269482'/><link rel='alternate' type='text/html' href='http://www.shujaat.net/2011/08/implicit-datatempates-in-silverlight-5.html' title='Implicit DataTempates in Silverlight 5 Beta'/><author><name>Muhammad Shujaat Siddiqi</name><uri>http://www.blogger.com/profile/02519138704633566929</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://4.bp.blogspot.com/-ZQqOiGtrLdk/Tj83-jIcv8I/AAAAAAAABAc/7TiBV5GGI50/s72-c/1.jpg' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8085117242240449595.post-649792701316035288</id><published>2011-08-07T18:18:00.000-05:00</published><updated>2011-08-07T18:18:02.572-05:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='debugger'/><category scheme='http://www.blogger.com/atom/ns#' term='binding'/><category scheme='http://www.blogger.com/atom/ns#' term='silverlight 5'/><category scheme='http://www.blogger.com/atom/ns#' term='Silverlight'/><category scheme='http://www.blogger.com/atom/ns#' term='new features'/><category scheme='http://www.blogger.com/atom/ns#' term='debugging'/><title type='text'>Binding Debugging in Silverlight 5</title><content type='html'>In this post we will be discussing a long desired feature in XAML based applications. This feature is &lt;b&gt;Binding Debugging specified in XAML&lt;/b&gt;. This feature is introduced in Silverlight 5.&lt;br /&gt;&lt;br /&gt;Let's create a sample Silverlight application &lt;b&gt;AppSilverlightDebuggingDemo&lt;/b&gt;.&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;br /&gt;&lt;a href="http://4.bp.blogspot.com/-owkp2IyvcQY/Tj6VzFbb2wI/AAAAAAAAA_k/DRSW2KAzbuI/s1600/1.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="244" width="400" src="http://4.bp.blogspot.com/-owkp2IyvcQY/Tj6VzFbb2wI/AAAAAAAAA_k/DRSW2KAzbuI/s400/1.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;Definitely an installation of Silverlight 5 is required for this example. Silverlight 5 beta tools can be downloaded from here:&lt;br /&gt;&lt;br /&gt;&lt;a href="http://www.microsoft.com/download/en/details.aspx?id=23887"&gt;http://www.microsoft.com/download/en/details.aspx?id=23887&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;If you have it installed already, the second step would allow you to select &lt;b&gt;Silverlight 5&lt;/b&gt; as the Silverlight version.&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/-1d9E_mndmnQ/Tj6WvH7t8WI/AAAAAAAAA_s/pCZKM7uJM4w/s1600/2.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="320" width="400" src="http://2.bp.blogspot.com/-1d9E_mndmnQ/Tj6WvH7t8WI/AAAAAAAAA_s/pCZKM7uJM4w/s400/2.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;Here in order to test our example we are selecting the option to create a new website to host the silvelight application specified in previous step. When you hit &lt;b&gt;OK&lt;/b&gt; the two projects should be available in Solution Explorer as follows:&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://3.bp.blogspot.com/-MlT3qI3W2g4/Tj6Xxp5wNpI/AAAAAAAAA_0/kv-xNu3_AtM/s1600/3.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="350" width="400" src="http://3.bp.blogspot.com/-MlT3qI3W2g4/Tj6Xxp5wNpI/AAAAAAAAA_0/kv-xNu3_AtM/s400/3.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;Now we add a view model to the Silverlight project &lt;b&gt;MainPageViewModel&lt;/b&gt;. It is a simple view model implementing &lt;i&gt;INotifyPropertyChanged&lt;/i&gt; interface for supporting change notification for its properties. The view model has two properties &lt;b&gt;StudentId&lt;/b&gt; and &lt;b&gt;StudentName&lt;/b&gt;, setting both would cause PropertyChanged event to be triggered.&lt;br /&gt;&lt;pre class="brush:csharp;gutter:false;"&gt;namespace AppSilverlightDebuggingDemo&lt;br /&gt;{&lt;br /&gt;    using System.ComponentModel;&lt;br /&gt;&lt;br /&gt;    public class MainPageViewModel : INotifyPropertyChanged&lt;br /&gt;    {&lt;br /&gt;        #region Notifiable Properties&lt;br /&gt;&lt;br /&gt;        string _studentId;&lt;br /&gt;        public string StudentId&lt;br /&gt;        {&lt;br /&gt;            get { return _studentId; }&lt;br /&gt;            set&lt;br /&gt;            {&lt;br /&gt;                _studentId = value;&lt;br /&gt;                OnPropertyChanged("StudentId");&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        string _studentName;&lt;br /&gt;        public string StudentName&lt;br /&gt;        {&lt;br /&gt;            get { return _studentName; }&lt;br /&gt;            set&lt;br /&gt;            {&lt;br /&gt;                _studentName = value;&lt;br /&gt;                OnPropertyChanged("StudentName");&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        #endregion&lt;br /&gt;&lt;br /&gt;        #region INotifyPropertyChanged Implementation&lt;br /&gt;&lt;br /&gt;        public event PropertyChangedEventHandler PropertyChanged = delegate { };&lt;br /&gt;        private void OnPropertyChanged(string propertyName)&lt;br /&gt;        {&lt;br /&gt;            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        #endregion        &lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;Let us update the definition of &lt;i&gt;MainPage.xaml&lt;/i&gt; as follows:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:xml;gutter:false;"&gt;&amp;lt;UserControl x:Class="AppSilverlightDebuggingDemo.MainPage"&lt;br /&gt;    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"&lt;br /&gt;    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&lt;br /&gt;    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"&lt;br /&gt;    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"&lt;br /&gt;    xmlns:local="clr-namespace:AppSilverlightDebuggingDemo"             &lt;br /&gt;    mc:Ignorable="d"&lt;br /&gt;    d:DesignHeight="300" d:DesignWidth="400" &lt;br /&gt;    xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"&amp;gt;&lt;br /&gt;    &amp;lt;UserControl.DataContext&amp;gt;&lt;br /&gt;        &amp;lt;local:MainPageViewModel StudentId="1" StudentName="Muhammad" /&amp;gt;&lt;br /&gt;    &amp;lt;/UserControl.DataContext&amp;gt;&lt;br /&gt;    &amp;lt;Grid x:Name="LayoutRoot" Background="White"&amp;gt;&lt;br /&gt;        &amp;lt;Grid.RowDefinitions&amp;gt;&lt;br /&gt;            &amp;lt;RowDefinition Height="48*" /&amp;gt;&lt;br /&gt;            &amp;lt;RowDefinition Height="35*" /&amp;gt;&lt;br /&gt;            &amp;lt;RowDefinition Height="36*" /&amp;gt;&lt;br /&gt;            &amp;lt;RowDefinition Height="181*" /&amp;gt;&lt;br /&gt;        &amp;lt;/Grid.RowDefinitions&amp;gt;&lt;br /&gt;        &amp;lt;sdk:Label Height="24" HorizontalAlignment="Center" &lt;br /&gt;                   VerticalAlignment="Center" Width="189" FontWeight="Bold" FontSize="16"&lt;br /&gt;                   Content="Student Information" Margin="106,24,106,0" /&amp;gt;&lt;br /&gt;        &amp;lt;sdk:Label Height="23" HorizontalAlignment="Left"&lt;br /&gt;                   Margin="12,12,0,0" Name="lblStudentId" VerticalAlignment="Top"                    &lt;br /&gt;                   Content="Student Id" Width="83" Grid.Row="1" /&amp;gt;&lt;br /&gt;        &amp;lt;TextBox Height="23" HorizontalAlignment="Left" Margin="101,8,0,0" &lt;br /&gt;                 VerticalAlignment="Top" Width="287" Grid.Row="1"&lt;br /&gt;                 Text="{Binding StudentId}" /&amp;gt;&lt;br /&gt;        &amp;lt;sdk:Label Content="Student Name" Height="23" HorizontalAlignment="Left" &lt;br /&gt;                   Margin="12,8,0,0" VerticalAlignment="Top" Width="83" Grid.Row="2" /&amp;gt;&lt;br /&gt;        &amp;lt;TextBox Height="23" HorizontalAlignment="Left" Margin="101,4,0,0" &lt;br /&gt;                 VerticalAlignment="Top" Width="287" Grid.Row="2" &lt;br /&gt;                 Text="{Binding StudentName}"/&amp;gt;        &lt;br /&gt;    &amp;lt;/Grid&amp;gt;&lt;br /&gt;&amp;lt;/UserControl&amp;gt;&lt;/pre&gt;In the above view we are using the view model defined previously as &lt;i&gt;DataContext&lt;/i&gt;. Here we have assigned some default values the two properties so that the view is loaded with some already existing information. We are binding the properties &lt;i&gt;StudentId&lt;/i&gt; and &lt;i&gt;StudentName&lt;/i&gt; to the two &lt;i&gt;TextBox&lt;/i&gt;(es).Now when we run the application, it should display as follows:&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://4.bp.blogspot.com/-kJEellzRFWU/Tj8NqqrINxI/AAAAAAAAA_8/HIPJc_QKaCY/s1600/4.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="246" width="400" src="http://4.bp.blogspot.com/-kJEellzRFWU/Tj8NqqrINxI/AAAAAAAAA_8/HIPJc_QKaCY/s400/4.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;Now open the view's XAML and try hitting &lt;b&gt;F9&lt;/b&gt; while putting the cursor on each of the bindings. This would insert a break point in the Binding expression. The execution would break at these bindings like a regular break point but the difference is that now this break point has been inserted in XAML.&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://4.bp.blogspot.com/-k2qcli577rs/Tj8PCA9WwBI/AAAAAAAABAE/i8GTaDFwaRY/s1600/5.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="115" width="400" src="http://4.bp.blogspot.com/-k2qcli577rs/Tj8PCA9WwBI/AAAAAAAABAE/i8GTaDFwaRY/s400/5.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;Now let us run the application again. The execution would step at the break point as follows:&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/-fsFAQFHvjPA/Tj8QG8i5wkI/AAAAAAAABAM/wPZX7qTTXuk/s1600/6.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="191" width="400" src="http://2.bp.blogspot.com/-fsFAQFHvjPA/Tj8QG8i5wkI/AAAAAAAABAM/wPZX7qTTXuk/s400/6.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;It not only steps at the breakpoint, it also lets us to use regular debugging tools provided in Visual Studio. You can see that we have the &lt;i&gt;Locals&lt;/i&gt; window opened and it is showing the values of the properties of the &lt;i&gt;DataContext&lt;/i&gt;. It also lets us find the issues with binding. Let's update the &lt;i&gt;StudentName&lt;/i&gt; binding as follows: &lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/-ZgVBbfvYzgg/Tj8bLkHitGI/AAAAAAAABAU/MLxMsPVxeM4/s1600/7.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="162" width="400" src="http://2.bp.blogspot.com/-ZgVBbfvYzgg/Tj8bLkHitGI/AAAAAAAABAU/MLxMsPVxeM4/s400/7.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;How easy do you think your life would be. Easy debugging...no late sittings at work...more time with family :)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Download Code:&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;&lt;iframe title ="Preview" scrolling="no" marginheight="0" marginwidth="0" frameborder="0" style="width:98px;height:115px;padding:0;background-color:#fcfcfc;" src="https://skydrive.live.com/embedicon.aspx/.Public/SilverlightDebuggingBinding.zip?cid=6f3051ef13f3137e&amp;sc=documents"&gt;&lt;/iframe&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8085117242240449595-649792701316035288?l=www.shujaat.net' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.shujaat.net/feeds/649792701316035288/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8085117242240449595&amp;postID=649792701316035288&amp;isPopup=true' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/649792701316035288'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/649792701316035288'/><link rel='alternate' type='text/html' href='http://www.shujaat.net/2011/08/binding-debugging-in-silverlight-5.html' title='Binding Debugging in Silverlight 5'/><author><name>Muhammad Shujaat Siddiqi</name><uri>http://www.blogger.com/profile/02519138704633566929</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://4.bp.blogspot.com/-owkp2IyvcQY/Tj6VzFbb2wI/AAAAAAAAA_k/DRSW2KAzbuI/s72-c/1.jpg' height='72' width='72'/><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8085117242240449595.post-1330405382009838947</id><published>2011-08-04T23:38:00.004-05:00</published><updated>2011-08-05T00:12:47.350-05:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='MVVM'/><category scheme='http://www.blogger.com/atom/ns#' term='mvvm light'/><category scheme='http://www.blogger.com/atom/ns#' term='wpf'/><category scheme='http://www.blogger.com/atom/ns#' term='multiBinding'/><category scheme='http://www.blogger.com/atom/ns#' term='relaycommand'/><category scheme='http://www.blogger.com/atom/ns#' term='INotifyPropertyChanged'/><category scheme='http://www.blogger.com/atom/ns#' term='PropertyChanged'/><title type='text'>Binding ObservableCollection to Text Properties</title><content type='html'>In this post we will be discussing the issue when we bind a collection based (&lt;i&gt;ObservableCollection&lt;/i&gt;) property to some scalar &lt;i&gt;DependencyProperty&lt;/i&gt; e.g. Text property of a &lt;i&gt;TextBlock&lt;/i&gt;.&lt;br /&gt;&lt;br /&gt;Let's create a sample MVVM Light based WPF application.&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/-QHqJRM2AySY/Tjcx84ThdVI/AAAAAAAAA_M/OFAtQKJPxqE/s1600/1.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="254" width="400" src="http://2.bp.blogspot.com/-QHqJRM2AySY/Tjcx84ThdVI/AAAAAAAAA_M/OFAtQKJPxqE/s400/1.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;i&gt;Note:&lt;/i&gt;&lt;br /&gt;Yes, you would need an installation of MVVM Light in order to follow this example.&lt;br /&gt;&lt;br /&gt;Let's update &lt;i&gt;MainWindow's &lt;/i&gt;definition as follows:&lt;br /&gt;&lt;pre class="brush: xml; gutter: false;"&gt;&amp;lt;Window x:Class="AppBindingScalarPropertiesCollections.MainWindow"&lt;br /&gt;        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"&lt;br /&gt;        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&lt;br /&gt;        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"&lt;br /&gt;        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"&lt;br /&gt;        xmlns:converters="clr-namespace:AppBindingScalarPropertiesCollections.Converters"&lt;br /&gt;        mc:Ignorable="d"&lt;br /&gt;        Height="386"&lt;br /&gt;        Width="514"&lt;br /&gt;        Title="MVVM Light Application"&lt;br /&gt;        DataContext="{Binding Main, Source={StaticResource Locator}}"&amp;gt;&lt;br /&gt;    &lt;br /&gt;    &amp;lt;Window.Resources&amp;gt;&lt;br /&gt;        &amp;lt;ResourceDictionary&amp;gt;&lt;br /&gt;            &amp;lt;ResourceDictionary.MergedDictionaries&amp;gt;&lt;br /&gt;                &amp;lt;ResourceDictionary Source="Skins/MainSkin.xaml" /&amp;gt;&lt;br /&gt;            &amp;lt;/ResourceDictionary.MergedDictionaries&amp;gt;&lt;br /&gt;        &amp;lt;/ResourceDictionary&amp;gt;&lt;br /&gt;    &amp;lt;/Window.Resources&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;Grid x:Name="LayoutRoot"&amp;gt;&lt;br /&gt;        &amp;lt;Grid.Resources&amp;gt;&lt;br /&gt;            &amp;lt;converters:StudentsListToStringConverter x:Key="studentConverter" /&amp;gt;&lt;br /&gt;        &amp;lt;/Grid.Resources&amp;gt;&lt;br /&gt;        &amp;lt;Grid.RowDefinitions&amp;gt;&lt;br /&gt;            &amp;lt;RowDefinition Height="42*" /&amp;gt;&lt;br /&gt;            &amp;lt;RowDefinition Height="37*" /&amp;gt;&lt;br /&gt;            &amp;lt;RowDefinition Height="189*" /&amp;gt;&lt;br /&gt;            &amp;lt;RowDefinition Height="79*" /&amp;gt;&lt;br /&gt;        &amp;lt;/Grid.RowDefinitions&amp;gt;&lt;br /&gt;        &amp;lt;TextBlock FontSize="36"&lt;br /&gt;                   FontWeight="Bold"&lt;br /&gt;                   Foreground="Purple"&lt;br /&gt;                   Text="{Binding Welcome}"&lt;br /&gt;                   VerticalAlignment="Center"&lt;br /&gt;                   HorizontalAlignment="Center"&lt;br /&gt;                   TextWrapping="Wrap" Margin="246,104,246,71" Grid.Row="2" /&amp;gt;&lt;br /&gt;        &amp;lt;Label Content="New Student" Height="23" HorizontalAlignment="Left"&lt;br /&gt;               Margin="6,15,0,0" Name="label1" VerticalAlignment="Top" Width="97" /&amp;gt;&lt;br /&gt;        &amp;lt;TextBox Height="25" HorizontalAlignment="Right" Margin="0,13,12,0"  &lt;br /&gt;                 VerticalAlignment="Top" Width="370"&lt;br /&gt;                 Text="{Binding NewStudentName, UpdateSourceTrigger=PropertyChanged}" /&amp;gt;&lt;br /&gt;        &amp;lt;GroupBox Header="Students List" Height="179" HorizontalAlignment="Left" Margin="6,2,0,0" &lt;br /&gt;                  Name="groupBox1" VerticalAlignment="Top" Width="476" Grid.Row="2"&amp;gt;&lt;br /&gt;            &amp;lt;Grid&amp;gt;&lt;br /&gt;                &amp;lt;ListBox ItemsSource="{Binding Students}"  /&amp;gt;&lt;br /&gt;            &amp;lt;/Grid&amp;gt;&lt;br /&gt;        &amp;lt;/GroupBox&amp;gt;&lt;br /&gt;        &amp;lt;GroupBox Header="Comma Separated Students List" Height="57" HorizontalAlignment="Left"&lt;br /&gt;                   VerticalAlignment="Top" Width="476" Grid.Row="3" Margin="0,8,0,0"&amp;gt;&lt;br /&gt;            &amp;lt;TextBlock &lt;br /&gt;                Text="{Binding Students, Converter={StaticResource studentConverter}}" &lt;br /&gt;                Height="21" /&amp;gt;&lt;br /&gt;        &amp;lt;/GroupBox&amp;gt;&lt;br /&gt;        &amp;lt;Button Content="Add" Grid.Row="1" Height="26" HorizontalAlignment="Left" &lt;br /&gt;                Margin="382,7,0,0" VerticalAlignment="Top" Width="99"&lt;br /&gt;                Command="{Binding AddNewStudentCommand}" /&amp;gt;&lt;br /&gt;    &amp;lt;/Grid&amp;gt;&lt;br /&gt;&amp;lt;/Window&amp;gt;&lt;/pre&gt;The above view has some expectations from view model. Let's update the view model provided by MVVM Light's view model locator as follows:&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;namespace AppBindingScalarPropertiesCollections.ViewModel&lt;br /&gt;{&lt;br /&gt;    using GalaSoft.MvvmLight;&lt;br /&gt;    using System.Collections.ObjectModel;&lt;br /&gt;    using System.Windows.Input;&lt;br /&gt;    using GalaSoft.MvvmLight.Command;&lt;br /&gt;  &lt;br /&gt;    public class MainViewModel : ViewModelBase&lt;br /&gt;    {&lt;br /&gt;        public string Welcome&lt;br /&gt;        {&lt;br /&gt;            get&lt;br /&gt;            {&lt;br /&gt;                return "Welcome to MVVM Light";&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        string _newStudentName;&lt;br /&gt;        public string NewStudentName&lt;br /&gt;        {&lt;br /&gt;            get { return _newStudentName; }&lt;br /&gt;            set &lt;br /&gt;            {&lt;br /&gt;                _newStudentName = value;&lt;br /&gt;                RaisePropertyChanged("NewStudentName");&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        ObservableCollection&amp;lt;string&amp;gt; _students;&lt;br /&gt;        public ObservableCollection&amp;lt;string&amp;gt; Students&lt;br /&gt;        {&lt;br /&gt;            get&lt;br /&gt;            {&lt;br /&gt;                if (_students == null)&lt;br /&gt;                {&lt;br /&gt;                    _students = new ObservableCollection&amp;lt;string&amp;gt;();&lt;br /&gt;                    _students.Add("Muhammad");&lt;br /&gt;                    _students.Add("Ryan");&lt;br /&gt;                    _students.Add("Jim");&lt;br /&gt;                    _students.Add("Brian");&lt;br /&gt;                    _students.Add("Josh");                   &lt;br /&gt;                    _students.Add("Jeremy");&lt;br /&gt;                }&lt;br /&gt;                return _students;&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        ICommand _addNewStudentCommand;&lt;br /&gt;        public ICommand AddNewStudentCommand&lt;br /&gt;        {&lt;br /&gt;            get &lt;br /&gt;            {&lt;br /&gt;                if (_addNewStudentCommand == null)&lt;br /&gt;                {&lt;br /&gt;                    _addNewStudentCommand = new RelayCommand(&lt;br /&gt;                        () =&amp;gt;&lt;br /&gt;                        {&lt;br /&gt;                            if (!Students.Contains(NewStudentName))&lt;br /&gt;                            {&lt;br /&gt;                                Students.Add(NewStudentName);&lt;br /&gt;                            }&lt;br /&gt;                        });&lt;br /&gt;                }&lt;br /&gt;                &lt;br /&gt;                return _addNewStudentCommand;&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;Mainly it has three things. &lt;i&gt;NewStudentName &lt;/i&gt;property to be bound to the TextBox to enter the name of a new student. &lt;i&gt;AddNewStudentCommand&lt;br /&gt;&lt;/i&gt; for the button's &lt;i&gt;Command &lt;/i&gt;property. Clicking this button should add the student's name as entered in the TextBox to Student's collection if it already doesn't exist. The ListBox and TextBlock showing this are automatically expected be updated as a new student is added to the collection. &lt;i&gt;Students&lt;/i&gt; collection to be bound to &lt;i&gt;ListBox&lt;/i&gt;'s &lt;i&gt;ItemSource &lt;/i&gt;and &lt;i&gt;TextBlock&lt;/i&gt;'s &lt;i&gt;Text &lt;/i&gt;properties. &lt;br /&gt;&lt;br /&gt;We need the Student's list in the TextBlock to be comma separated names of all students. The view is using a converter for this purpose. It is a simple &lt;i&gt;IValueConverter&lt;/i&gt;. Let's see the definition of this converter.&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;namespace AppBindingScalarPropertiesCollections.Converters&lt;br /&gt;{&lt;br /&gt;    using System.Windows.Data;&lt;br /&gt;    using System.Collections.ObjectModel;&lt;br /&gt;    using System.Linq;&lt;br /&gt;&lt;br /&gt;    class StudentsListToStringConverter : IValueConverter&lt;br /&gt;    {&lt;br /&gt;        public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)&lt;br /&gt;        {&lt;br /&gt;            string studentCommaSeparatedList = string.Empty;&lt;br /&gt;            ObservableCollection&amp;lt;string&amp;gt; studentList = value as ObservableCollection&amp;lt;string&amp;gt;;&lt;br /&gt;&lt;br /&gt;            if (studentList != null)&lt;br /&gt;            {&lt;br /&gt;                studentCommaSeparatedList = string.Join(", ",&lt;br /&gt;                                            (from string studentName&lt;br /&gt;                                                 in studentList&lt;br /&gt;                                             select studentName).ToArray&amp;lt;string&amp;gt;());&lt;br /&gt;            }           &lt;br /&gt;&lt;br /&gt;            return studentCommaSeparatedList;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)&lt;br /&gt;        {&lt;br /&gt;            throw new System.NotImplementedException();&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;In the &lt;i&gt;Convert &lt;/i&gt;method of this &lt;i&gt;IValueConverter&lt;/i&gt;, we are simple joining the elements of the collection with comma separation and returning it. &lt;br /&gt;&lt;br /&gt;Let's run the application now. It appears as follows...&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/-_OUoVPc4dc4/TjpjZ5ACDmI/AAAAAAAAA_U/RHmtjyQ4RFc/s1600/2.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="300" width="400" src="http://2.bp.blogspot.com/-_OUoVPc4dc4/TjpjZ5ACDmI/AAAAAAAAA_U/RHmtjyQ4RFc/s400/2.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;As we enter new student's name and hit &lt;b&gt;Add&lt;/b&gt; button, the new student is added to &lt;i&gt;Students &lt;/i&gt;collection. Since this collection is bound to the &lt;i&gt;ItemsSource &lt;/i&gt;of the ListBox, it appears in the list box. But the same does not appear in the TextBlock's comma separated list. This is weird!!!&lt;br /&gt;&lt;br /&gt;Basically, the reason is very simple. When we bind to the Text property of TextBlock, it is just interested in the &lt;i&gt;PropertyChanged &lt;/i&gt;events. It handles this event to update its contents. But it seems that it doesn't handle CollectionChanged event of &lt;i&gt;ObservableCollection&lt;/i&gt;. That is why it is not able to update itself. Now since we know the problem how we can resolve this. Basically there might be two different solutions to this problem.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Solution # 1: [Raise PropertyChanged Event when collection is updated for items]&lt;br /&gt;&lt;/b&gt;&lt;br /&gt;This is very simple. Since we are just adding items in the &lt;i&gt;Execute &lt;/i&gt;method of the &lt;i&gt;ICommand &lt;/i&gt;bound to the Add button, we can simply do it there. Let's update the &lt;i&gt;ICommand &lt;/i&gt;definition in the view model as follows:&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;public ICommand AddNewStudentCommand&lt;br /&gt;{&lt;br /&gt;    get &lt;br /&gt;    {&lt;br /&gt;        if (_addNewStudentCommand == null)&lt;br /&gt;        {&lt;br /&gt;            _addNewStudentCommand = new RelayCommand(&lt;br /&gt;                () =&gt;&lt;br /&gt;                {&lt;br /&gt;                    if (!Students.Contains(NewStudentName))&lt;br /&gt;                    {&lt;br /&gt;                        Students.Add(NewStudentName);&lt;br /&gt;                        RaisePropertyChanged("Students");&lt;br /&gt;                    }&lt;br /&gt;                });&lt;br /&gt;        }&lt;br /&gt;        &lt;br /&gt;        return _addNewStudentCommand;&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;Here &lt;i&gt;RaisePropertyChanged &lt;/i&gt;method raises &lt;i&gt;PropertyChanged &lt;/i&gt;event for the name of property provided as argument. This is available due to inheritence of this view model by &lt;i&gt;ViewModelBase &lt;/i&gt;from &lt;i&gt;MVVM Light&lt;/i&gt;. Let's run the application again.&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://1.bp.blogspot.com/-UDoyiAcYXmo/TjqV5pxqFkI/AAAAAAAAA_c/zS-0B1MuCIQ/s1600/3.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="300" width="400" src="http://1.bp.blogspot.com/-UDoyiAcYXmo/TjqV5pxqFkI/AAAAAAAAA_c/zS-0B1MuCIQ/s400/3.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;As we entered &lt;i&gt;Sekhar&lt;/i&gt; and hit the button, it appears both in the ListBox and TextBlock. This is exactly what we desired. &lt;i&gt;Zindabad!!!&lt;/i&gt;&lt;br /&gt;&lt;br /&gt;&lt;b&gt;2nd Solution: [Use MultiBinding, adding binding for ObservableCollection.Count]&lt;/b&gt;&lt;br /&gt;In this solution, we can simply add binding for Count property from the same collection. We can change the binding of TextBlock as follows:&lt;br /&gt;&lt;pre class="brush: xml; gutter: false;"&gt;&amp;lt;Window x:Class="AppBindingScalarPropertiesCollections.MainWindow"&lt;br /&gt;        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"&lt;br /&gt;        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&lt;br /&gt;        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"&lt;br /&gt;        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"&lt;br /&gt;        xmlns:converters="clr-namespace:AppBindingScalarPropertiesCollections.Converters"&lt;br /&gt;        mc:Ignorable="d"&lt;br /&gt;        Height="386"&lt;br /&gt;        Width="514"&lt;br /&gt;        Title="MVVM Light Application"&lt;br /&gt;        DataContext="{Binding Main, Source={StaticResource Locator}}"&amp;gt;&lt;br /&gt;    &lt;br /&gt;    &amp;lt;Window.Resources&amp;gt;&lt;br /&gt;        &amp;lt;ResourceDictionary&amp;gt;&lt;br /&gt;            &amp;lt;ResourceDictionary.MergedDictionaries&amp;gt;&lt;br /&gt;                &amp;lt;ResourceDictionary Source="Skins/MainSkin.xaml" /&amp;gt;&lt;br /&gt;            &amp;lt;/ResourceDictionary.MergedDictionaries&amp;gt;&lt;br /&gt;        &amp;lt;/ResourceDictionary&amp;gt;&lt;br /&gt;    &amp;lt;/Window.Resources&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;Grid x:Name="LayoutRoot"&amp;gt;&lt;br /&gt;        &amp;lt;Grid.Resources&amp;gt;&lt;br /&gt;            &amp;lt;converters:StudentListToStringMultiConverter x:Key="studentMultiConverter" /&amp;gt;&lt;br /&gt;        &amp;lt;/Grid.Resources&amp;gt;&lt;br /&gt;        &amp;lt;Grid.RowDefinitions&amp;gt;&lt;br /&gt;            &amp;lt;RowDefinition Height="42*" /&amp;gt;&lt;br /&gt;            &amp;lt;RowDefinition Height="37*" /&amp;gt;&lt;br /&gt;            &amp;lt;RowDefinition Height="189*" /&amp;gt;&lt;br /&gt;            &amp;lt;RowDefinition Height="79*" /&amp;gt;&lt;br /&gt;        &amp;lt;/Grid.RowDefinitions&amp;gt;&lt;br /&gt;        &amp;lt;TextBlock FontSize="36"&lt;br /&gt;                   FontWeight="Bold"&lt;br /&gt;                   Foreground="Purple"&lt;br /&gt;                   Text="{Binding Welcome}"&lt;br /&gt;                   VerticalAlignment="Center"&lt;br /&gt;                   HorizontalAlignment="Center"&lt;br /&gt;                   TextWrapping="Wrap" Margin="246,104,246,71" Grid.Row="2" /&amp;gt;&lt;br /&gt;        &amp;lt;Label Content="New Student" Height="23" HorizontalAlignment="Left"&lt;br /&gt;               Margin="6,15,0,0" Name="label1" VerticalAlignment="Top" Width="97" /&amp;gt;&lt;br /&gt;        &amp;lt;TextBox Height="25" HorizontalAlignment="Right" Margin="0,13,12,0"  &lt;br /&gt;                 VerticalAlignment="Top" Width="370"&lt;br /&gt;                 Text="{Binding NewStudentName, UpdateSourceTrigger=PropertyChanged}" /&amp;gt;&lt;br /&gt;        &amp;lt;GroupBox Header="Students List" Height="179" HorizontalAlignment="Left" Margin="6,2,0,0" &lt;br /&gt;                  Name="groupBox1" VerticalAlignment="Top" Width="476" Grid.Row="2"&amp;gt;&lt;br /&gt;            &amp;lt;Grid&amp;gt;&lt;br /&gt;                &amp;lt;ListBox ItemsSource="{Binding Students}"  /&amp;gt;&lt;br /&gt;            &amp;lt;/Grid&amp;gt;&lt;br /&gt;        &amp;lt;/GroupBox&amp;gt;&lt;br /&gt;        &amp;lt;GroupBox Header="Comma Separated Students List" Height="57" HorizontalAlignment="Left"&lt;br /&gt;                   VerticalAlignment="Top" Width="476" Grid.Row="3" Margin="0,8,0,0"&amp;gt;&lt;br /&gt;&lt;br /&gt;            &amp;lt;TextBlock                 &lt;br /&gt;                Height="21" &amp;gt;&lt;br /&gt;                &amp;lt;TextBlock.Text&amp;gt;&lt;br /&gt;                    &amp;lt;MultiBinding  Converter="{StaticResource studentMultiConverter}" &amp;gt;&lt;br /&gt;                        &amp;lt;Binding Path ="Students"/&amp;gt;&lt;br /&gt;                        &amp;lt;Binding Path ="Students.Count" /&amp;gt;&lt;br /&gt;                    &amp;lt;/MultiBinding&amp;gt;&lt;br /&gt;                &amp;lt;/TextBlock.Text&amp;gt;&lt;br /&gt;            &amp;lt;/TextBlock&amp;gt;&lt;br /&gt;        &amp;lt;/GroupBox&amp;gt;&lt;br /&gt;        &amp;lt;Button Content="Add" Grid.Row="1" Height="26" HorizontalAlignment="Left" &lt;br /&gt;                Margin="382,7,0,0" VerticalAlignment="Top" Width="99"&lt;br /&gt;                Command="{Binding AddNewStudentCommand}" /&amp;gt;&lt;br /&gt;    &amp;lt;/Grid&amp;gt;&lt;br /&gt;&amp;lt;/Window&amp;gt;&lt;/pre&gt;In addition of Binding update, we also need to update the converter to IMultiValueConverter. Let's see the definition of StudentListToStringMultiConverter used above.&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;class StudentListToStringMultiConverter : IMultiValueConverter&lt;br /&gt;{&lt;br /&gt;&lt;br /&gt;    public object Convert(object[] values, System.Type targetType, object parameter, &lt;br /&gt;        System.Globalization.CultureInfo culture)&lt;br /&gt;    {&lt;br /&gt;        string studentCommaSeparatedList = string.Empty;&lt;br /&gt;        ObservableCollection&amp;lt;string&amp;gt; studentList = values[0] as ObservableCollection&amp;lt;string&amp;gt;;&lt;br /&gt;&lt;br /&gt;        if (studentList != null)&lt;br /&gt;        {&lt;br /&gt;            studentCommaSeparatedList = string.Join(", ",&lt;br /&gt;                                        (from string studentName&lt;br /&gt;                                             in studentList&lt;br /&gt;                                         select studentName).ToArray&amp;lt;string&amp;gt;());&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        return studentCommaSeparatedList;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public object[] ConvertBack(object value, System.Type[] targetTypes, object parameter,&lt;br /&gt;        System.Globalization.CultureInfo culture)&lt;br /&gt;    {&lt;br /&gt;        throw new System.NotImplementedException();&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;Running the application should have the same result as the first option.&lt;br /&gt;&lt;br /&gt;Any Questions??? Comments...&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Download:&lt;/b&gt;&lt;br /&gt;The sameple project can be downloaded from SkyDrive here:&lt;br /&gt;&lt;br /&gt;&lt;iframe title ="Preview" scrolling="no" marginheight="0" marginwidth="0" frameborder="0" style="width:98px;height:115px;padding:0;background-color:#fcfcfc;" src="https://skydrive.live.com/embedicon.aspx/.Public?cid=6f3051ef13f3137e&amp;sc=documents"&gt;&lt;/iframe&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8085117242240449595-1330405382009838947?l=www.shujaat.net' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.shujaat.net/feeds/1330405382009838947/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8085117242240449595&amp;postID=1330405382009838947&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/1330405382009838947'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/1330405382009838947'/><link rel='alternate' type='text/html' href='http://www.shujaat.net/2011/08/binding-observablecollection-to-text.html' title='Binding ObservableCollection to Text Properties'/><author><name>Muhammad Shujaat Siddiqi</name><uri>http://www.blogger.com/profile/02519138704633566929</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://2.bp.blogspot.com/-QHqJRM2AySY/Tjcx84ThdVI/AAAAAAAAA_M/OFAtQKJPxqE/s72-c/1.jpg' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8085117242240449595.post-1280845783134999128</id><published>2011-07-25T20:34:00.000-05:00</published><updated>2011-07-25T20:34:03.677-05:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='wpf'/><category scheme='http://www.blogger.com/atom/ns#' term='XAML'/><category scheme='http://www.blogger.com/atom/ns#' term='Magic String'/><category scheme='http://www.blogger.com/atom/ns#' term='INotifyPropertyChanged'/><category scheme='http://www.blogger.com/atom/ns#' term='Silverlight'/><category scheme='http://www.blogger.com/atom/ns#' term='wpf binding'/><title type='text'>INotifyPropertyChanged and Magic Strings</title><content type='html'>One of the argument against &lt;i&gt;INotifyPropertyChanged &lt;/i&gt;is the magic strings based notification. Although this is not as big an issue as many people think it is but I have seen people finding it difficult to explain to their fellow developers about this. As an alternate they make their View Models a &lt;i&gt;DependencyObject &lt;/i&gt;and provide Dependency Properties for all properties that should be supporting change notifications.&lt;br /&gt;&lt;br /&gt;In this post we are going to discuss how we can avoid the use of magic strings and still be able to use INotifyPropertyChanged. For those who needs some glimpse of the problem, &lt;i&gt;INotifyPropertyChanged &lt;/i&gt;based properties appear something like this in general.&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;private string _firstName;&lt;br /&gt;public string FirstName&lt;br /&gt;{&lt;br /&gt;    get { return _firstName; }&lt;br /&gt;    set&lt;br /&gt;    {&lt;br /&gt;       _firstName = value;&lt;br /&gt;       OnPropertyChanged("FirstName");&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;And that is what we want to avoid. &lt;i&gt;We don’t want an OnPropertyChanged with a magic string.&lt;/i&gt;&lt;br /&gt;&lt;br /&gt;Let’s create a simple view with a simple &lt;i&gt;TextBox &lt;/i&gt;for entering user information (&lt;i&gt;First Name&lt;/i&gt;). In order to prove that the property change notifications are working, we add one &lt;i&gt;TextBlock&lt;/i&gt;. This &lt;i&gt;TextBlock &lt;/i&gt;is bound to the same property. This is a &lt;i&gt;OneWay &lt;/i&gt;binding which is one-way from Source to &lt;i&gt;Target &lt;/i&gt;property. We have set the &lt;i&gt;UpdateSourceTrigger &lt;/i&gt;on TextBox’s binding to &lt;i&gt;PropertyChanged &lt;/i&gt;so that we don’t have to lose focus from the TextBox in order to trigger the copying of text to the view model’s property.&lt;br /&gt;&lt;pre class="brush: xml; gutter: false;"&gt;&amp;lt;Window x:Class="WpfApp_INotifyWithoutMagicString.MainWindow"&lt;br /&gt;       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"&lt;br /&gt;       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&lt;br /&gt;       xmlns:local="clr-namespace:WpfApp_INotifyWithoutMagicString"&lt;br /&gt;       Title="MainWindow" Height="350" Width="525"&amp;gt;&lt;br /&gt;    &amp;lt;Window.DataContext&amp;gt;&lt;br /&gt;       &amp;lt;local:MainWindowViewModel /&amp;gt;&lt;br /&gt;    &amp;lt;/Window.DataContext&amp;gt;&lt;br /&gt;    &amp;lt;Grid&amp;gt;&lt;br /&gt;       &amp;lt;Label Content="First Name" Height="28" HorizontalAlignment="Left"&lt;br /&gt;              Margin="22,54,0,0" Name="label1" VerticalAlignment="Top" Width="80" /&amp;gt;&lt;br /&gt;       &amp;lt;TextBox Height="28" HorizontalAlignment="Left" Margin="108,54,0,0"&lt;br /&gt;                Name="textBox1" VerticalAlignment="Top" Width="356"&lt;br /&gt;                Text="{Binding FirstName, UpdateSourceTrigger=PropertyChanged}" /&amp;gt;&lt;br /&gt;       &amp;lt;TextBlock Height="121" HorizontalAlignment="Left" Margin="108,101,0,0"&lt;br /&gt;                  Name="textBlock1" Text="{Binding FirstName, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}"&lt;br /&gt;                  Background ="Thistle" VerticalAlignment="Top" Width="356" /&amp;gt;        &lt;br /&gt;   &amp;lt;/Grid&amp;gt;&lt;br /&gt;&amp;lt;/Window&amp;gt;&lt;/pre&gt;We are instantiating &lt;i&gt;MainWindowViewModel &lt;/i&gt;and using it as DataContext of the Window. The view model is assumed to have a property, named &lt;i&gt;FirstName&lt;/i&gt;. You can find the definition of &lt;i&gt;MainWindowViewModel &lt;/i&gt;as follows:&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&amp;class MainWindowViewModel : BaseViewModel&amp;lt;MainWindowViewModel&amp;gt;&lt;br /&gt;{&lt;br /&gt;    private string _firstName;&lt;br /&gt;    public string FirstName&lt;br /&gt;    {&lt;br /&gt;       get { return _firstName; }&lt;br /&gt;       set&lt;br /&gt;       {&lt;br /&gt;           _firstName = value;&lt;br /&gt;           OnPropertyChanged(viewModel =&amp;gt; viewModel.FirstName);&lt;br /&gt;       }&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;As expected, the above view model has a public property &lt;i&gt;FirstName&lt;/i&gt;. The difference is how we have called &lt;i&gt;OnPropertyChanged&lt;/i&gt;. As we mentioned in the start of this post, there is no magic string. The definition of &lt;i&gt;OnPropertyChanged &lt;/i&gt;is inherited from &lt;i&gt;ViewModelBase&lt;/i&gt;. But one thing is apparent, the definition of the method should be dealing with the handling of the &lt;i&gt;lambda expression&lt;/i&gt; provided as method argument.&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;class MainWindowViewModel : ViewModelBase&amp;lt;MainWindowViewModel&amp;gt;&lt;br /&gt;{&lt;br /&gt;    private string _firstName;&lt;br /&gt;    public string FirstName&lt;br /&gt;    {&lt;br /&gt;       get { return _firstName; }&lt;br /&gt;       set&lt;br /&gt;       {&lt;br /&gt;           _firstName = value;&lt;br /&gt;           OnPropertyChanged(viewModel =&amp;gt; viewModel.FirstName);&lt;br /&gt;       }&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;The definition of &lt;i&gt;ViewModelBase &lt;/i&gt;is as follows:&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;class ViewModelBase&amp;lt;T&amp;gt; : INotifyPropertyChanged where T : class&lt;br /&gt;{&lt;br /&gt;    #region Implementation INotifyPropertyChanged&lt;br /&gt;&lt;br /&gt;    public event PropertyChangedEventHandler PropertyChanged = delegate { };&lt;br /&gt;&lt;br /&gt;    protected void OnPropertyChanged(Expression&amp;lt;Func&amp;lt;T, object&amp;gt;&amp;gt; expression)&lt;br /&gt;    {&lt;br /&gt;       if (expression == null || !(expression.Body is MemberExpression))&lt;br /&gt;       {&lt;br /&gt;           return;&lt;br /&gt;       }&lt;br /&gt;&lt;br /&gt;       PropertyChanged(this, new PropertyChangedEventArgs(((MemberExpression)expression.Body).Member.Name));&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    #endregion Implementation INotifyPropertyChanged&lt;br /&gt;}&lt;/pre&gt;&lt;i&gt;ViewModelBase &lt;/i&gt;is implemented as generic type. This is to allow the user to avoid casting. The other implementation might have been as follows:&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;class ViewModelBase : INotifyPropertyChanged&lt;br /&gt;{&lt;br /&gt;    #region Implementation INotifyPropertyChanged&lt;br /&gt;&lt;br /&gt;    public event PropertyChangedEventHandler PropertyChanged = delegate { };&lt;br /&gt;&lt;br /&gt;    protected void OnPropertyChanged(Expression&amp;lt;Func&amp;lt;object, object&amp;gt;&amp;gt; expression)&lt;br /&gt;    {&lt;br /&gt;       if (expression == null || !(expression.Body is MemberExpression))&lt;br /&gt;       {&lt;br /&gt;           return;&lt;br /&gt;       }&lt;br /&gt;&lt;br /&gt;       PropertyChanged(this, new PropertyChangedEventArgs(((MemberExpression)expression.Body).Member.Name));&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    #endregion Implementation INotifyPropertyChanged&lt;br /&gt;}&lt;/pre&gt;But since this is based on object type of argument for &lt;i&gt;lambda expression&lt;/i&gt;. In order to access the &lt;i&gt;FirstName &lt;/i&gt;property from the argument, the developer need to typecast. Wrong typecasting might result in runtime exceptions if the object being type casted doesn’t have the property with same name.&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;public string FirstName&lt;br /&gt;{&lt;br /&gt;    get { return _firstName; }&lt;br /&gt;    set&lt;br /&gt;    {&lt;br /&gt;       _firstName = value;&lt;br /&gt;       OnPropertyChanged(viewModel =&amp;gt; ((MainWindowViewModel)viewModel).FirstName);&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;The developer might be just using the code similar to the following code. But this must be remembered that we are not passing the current instance of View Model. We are just passing the lambda expression as argument to &lt;i&gt;OnPropertyChanged&lt;/i&gt;. Its evaluation would result in raising &lt;i&gt;PropertyChanged &lt;/i&gt;event for the same property.&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;public string FirstName&lt;br /&gt;{&lt;br /&gt;    get { return _firstName; }&lt;br /&gt;    set&lt;br /&gt;    {&lt;br /&gt;       _firstName = value;&lt;br /&gt;       OnPropertyChanged(viewModel =&amp;gt; FirstName);&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;Which leads us to third implementation of &lt;i&gt;ViewModelBase &lt;/i&gt;without even specifying the type of view model as the argument for lambda. I think this would be the simplest and easiest implementation of the Base View Model.&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;class ViewModelBase : INotifyPropertyChanged &lt;br /&gt;{&lt;br /&gt;    #region Implementation INotifyPropertyChanged&lt;br /&gt;&lt;br /&gt;    public event PropertyChangedEventHandler PropertyChanged = delegate { };&lt;br /&gt;&lt;br /&gt;    protected void OnPropertyChanged(Expression&amp;lt;Func&amp;lt;object&amp;gt;&amp;gt; expression)&lt;br /&gt;    {&lt;br /&gt;       if (expression == null || !(expression.Body is MemberExpression))&lt;br /&gt;       {&lt;br /&gt;           return;&lt;br /&gt;       }&lt;br /&gt;&lt;br /&gt;       PropertyChanged(this, new PropertyChangedEventArgs(((MemberExpression)expression.Body).Member.Name));&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    #endregion Implementation INotifyPropertyChanged&lt;br /&gt;}&lt;/pre&gt;If we implement our ViewModel as above then it might result in simplest &lt;i&gt;OnPropertyChanged &lt;/i&gt;as follows:&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;public string FirstName&lt;br /&gt;{&lt;br /&gt;    get { return _firstName; }&lt;br /&gt;    set&lt;br /&gt;    {&lt;br /&gt;       _firstName = value;&lt;br /&gt;       OnPropertyChanged(() =&amp;gt; FirstName);&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;No matter what implementation of &lt;i&gt;ViewModelBase &lt;/i&gt;you are using, when you would run the application and enter text in the &lt;i&gt;TextBox&lt;/i&gt;, it would update the FirstName property in the &lt;i&gt;DataContext &lt;/i&gt;(&lt;i&gt;MainWindowViewModel’s &lt;/i&gt;instance). This is proved through the same data being displayed in the &lt;i&gt;TextBlock &lt;/i&gt;below.&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://3.bp.blogspot.com/-7hC6fs54hOI/Ti4Y3w9vNTI/AAAAAAAAA_E/xXTElheK7qA/s1600/1.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="267" width="400" src="http://3.bp.blogspot.com/-7hC6fs54hOI/Ti4Y3w9vNTI/AAAAAAAAA_E/xXTElheK7qA/s400/1.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8085117242240449595-1280845783134999128?l=www.shujaat.net' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.shujaat.net/feeds/1280845783134999128/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8085117242240449595&amp;postID=1280845783134999128&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/1280845783134999128'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/1280845783134999128'/><link rel='alternate' type='text/html' href='http://www.shujaat.net/2011/07/inotifypropertychanged-and-magic.html' title='INotifyPropertyChanged and Magic Strings'/><author><name>Muhammad Shujaat Siddiqi</name><uri>http://www.blogger.com/profile/02519138704633566929</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://3.bp.blogspot.com/-7hC6fs54hOI/Ti4Y3w9vNTI/AAAAAAAAA_E/xXTElheK7qA/s72-c/1.jpg' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8085117242240449595.post-1888570773612559381</id><published>2011-04-23T00:26:00.001-05:00</published><updated>2011-04-23T00:41:38.700-05:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='wpf'/><category scheme='http://www.blogger.com/atom/ns#' term='.net'/><category scheme='http://www.blogger.com/atom/ns#' term='XAML'/><category scheme='http://www.blogger.com/atom/ns#' term='mosue capture'/><category scheme='http://www.blogger.com/atom/ns#' term='PreviewMouseDownOutsideCapturedElement'/><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><category scheme='http://www.blogger.com/atom/ns#' term='Window_PreviewMouseDownOutsideCapturedElement'/><title type='text'>Clicking away from FrameworkElement when mouse is still captured</title><content type='html'>This post is about a very specific problem about mouse capturing. There are certain situations in which we need to be notified when mouse is clicked outside the bounds of an element. As all of you know that this is classical mouse capturing situation used for various tasks including Drag &amp; Drop. When we search around for a solution for this then we find out an attached event &lt;i&gt;Mouse.PreviewMouseDownOutsideCapturedElement&lt;/i&gt;. This is documented in msdn as follows:&lt;br /&gt;&lt;br /&gt;&lt;i&gt;“Occurs when the primary mouse button is pressed outside the element that is capturing mouse events.”&lt;/i&gt;&lt;br /&gt;&lt;pre class="brush: xml; gutter: false;"&gt;&amp;lt;Window x:Class="WpfApplication3.Window1"&lt;br /&gt;        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"&lt;br /&gt;        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&lt;br /&gt;        Title="Window1" Height="483" Width="553"      &lt;br /&gt;Mouse.PreviewMouseDownOutsideCapturedElement="Window_PreviewMouseDownOutsideCapturedElement" &amp;gt;&lt;br /&gt;    &amp;lt;StackPanel&amp;gt;&lt;br /&gt;        &amp;lt;StackPanel Height="33"&amp;gt;&lt;br /&gt;            &amp;lt;TextBox Name="textBox1" /&amp;gt;&lt;br /&gt;        &amp;lt;/StackPanel&amp;gt;&lt;br /&gt;        &amp;lt;StackPanel  &amp;gt;           &lt;br /&gt;            &amp;lt;Button Content="Button" Height="32" HorizontalAlignment="Left"&lt;br /&gt;                    Margin="126,209,0,0" Name="button1" VerticalAlignment="Top"&lt;br /&gt;                    Width="297" Click="button1_Click" /&amp;gt;&lt;br /&gt;        &amp;lt;/StackPanel&amp;gt;&lt;br /&gt;    &amp;lt;/StackPanel&amp;gt;&lt;br /&gt;&amp;lt;/Window&amp;gt;&lt;br /&gt;&lt;/pre&gt;This definitely does what it is supposed to do. In order to get this to work we must have a captured element. Let’s capture mouse on textBox1. So, clicking a mouse outside textBox1 (captured element) should result in causing this handler to get called.&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;public partial class Window1 : Window&lt;br /&gt;{&lt;br /&gt;    public Window1()&lt;br /&gt;    {&lt;br /&gt;        InitializeComponent();       &lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private void Window_PreviewMouseDownOutsideCapturedElement(object sender, MouseButtonEventArgs e)&lt;br /&gt;    {&lt;br /&gt;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private void button1_Click(object sender, RoutedEventArgs e)&lt;br /&gt;    {&lt;br /&gt;        Mouse.Capture(this.textBox1);&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;Let’s run this. We have the display as presented in XAML. It has a TextBox and a Button. When we click the button textBox1 captures the mouse using static Capture method on Mouse. We have subscribed  &lt;i&gt;PreviewMouseDownOutsideCapturedElement&lt;/i&gt; event in &lt;i&gt;XAML&lt;/i&gt;. We could have easily done that in code behind as well. Obviously we would need &lt;i&gt;AddHandler…&lt;/i&gt; mechanism for registering with an attached event. This is similar to &lt;i&gt;XAML&lt;/i&gt; attached properties. When implemented in WPF, they work as Dependency properties. Similarly Attached events from XAML are implemented as routed events in &lt;i&gt;WPF&lt;/i&gt;.&lt;br /&gt;&lt;br /&gt;Now the issue is that this event gets fired even when we click inside textBox1. This seems awkwardly strange as this is purely not expected behavior when we read the msdn description. Now we know the behavior. How can we fix this? We just need to find out where the mouse was clicked and we should be good to go. You might be wondering we can get around that we can do that either through the sender parameter or Source / OriginalSource from &lt;i&gt;MouseButtonEventArgs&lt;/i&gt;. But the strange thing is that sender is always the element on which the event is registered. So if were registering it on textBox1, it would be textBox1. Currently this would always be the Window object no matter where we click on the Window after capturing the mouse by clicking the button. On top of that, Source and &lt;i&gt;OriginalSource&lt;/i&gt; are always the captured element. The other properties which could inform us if the mouse is directly over the &lt;i&gt;textBox1&lt;/i&gt; are always true.&lt;br /&gt;&lt;br /&gt;The only way to fix it seems to be to do it ourselves. We can find out the position of mouse. If the position of mouse is within the bounds of captured element then we can just ignore this. Otherwise, we can execute the same logic as we were supposed to execute. We might need to register the event again.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;private void Window_PreviewMouseDownOutsideCapturedElement(object sender, MouseButtonEventArgs e)&lt;br /&gt;{&lt;br /&gt;    bool isClickedWithin =  IsMouseClickWithin(this.textBox1, e.MouseDevice.GetPosition(this.textBox1));&lt;br /&gt;&lt;br /&gt;    if(isClickedWithin)&lt;br /&gt;    {&lt;br /&gt;        //execute some logic&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;private bool IsMouseClickWithin(FrameworkElement element, Point point)&lt;br /&gt;{&lt;br /&gt;    return (element.ActualWidth &gt; point.X &amp;&amp; element.ActualHeight &gt; point.Y) || point.X &lt; 0 || point.Y &lt; 0;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;In the above example, it is checking if the mouse position is within the actual bounds of textBox1. &lt;i&gt;IsMouseClickWithin&lt;/i&gt; returns true for this. It returns false otherwise.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8085117242240449595-1888570773612559381?l=www.shujaat.net' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.shujaat.net/feeds/1888570773612559381/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8085117242240449595&amp;postID=1888570773612559381&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/1888570773612559381'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/1888570773612559381'/><link rel='alternate' type='text/html' href='http://www.shujaat.net/2011/04/clicking-away-from-framework-element.html' title='Clicking away from FrameworkElement when mouse is still captured'/><author><name>Muhammad Shujaat Siddiqi</name><uri>http://www.blogger.com/profile/02519138704633566929</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8085117242240449595.post-5335218023233101760</id><published>2011-04-13T21:42:00.000-05:00</published><updated>2011-04-13T21:42:15.437-05:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='WCFDataService'/><category scheme='http://www.blogger.com/atom/ns#' term='SQLServerCompactEditionUnderWebHosting'/><category scheme='http://www.blogger.com/atom/ns#' term='.net framework 4.0'/><category scheme='http://www.blogger.com/atom/ns#' term='.net'/><category scheme='http://www.blogger.com/atom/ns#' term='asp.net'/><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><category scheme='http://www.blogger.com/atom/ns#' term='ServiceBehavior'/><category scheme='http://www.blogger.com/atom/ns#' term='IncludeExceptionDetailInFaults'/><category scheme='http://www.blogger.com/atom/ns#' term='AppDomain'/><category scheme='http://www.blogger.com/atom/ns#' term='appdomain slots'/><title type='text'>Hosting SQL CE based Entity Models in WCF Data Service</title><content type='html'>&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;While developing an application in ASP.net for my friend I realized that we can not SQL Compact Edition with ASP.net. When you try to do that you would get this error page. &lt;br /&gt;&lt;br /&gt;&lt;table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td style="text-align: center;"&gt;&lt;a href="http://4.bp.blogspot.com/-jkYZZMFmlHo/TaZYnNKRCLI/AAAAAAAAA-0/RjR0amKqBHY/s1600/1.jpg" imageanchor="1" style="margin-left: auto; margin-right: auto;"&gt;&lt;img border="0" height="104" src="http://4.bp.blogspot.com/-jkYZZMFmlHo/TaZYnNKRCLI/AAAAAAAAA-0/RjR0amKqBHY/s640/1.jpg" width="640" /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td class="tr-caption" style="text-align: center;"&gt;SQL Compact Edition error when used with ASP.net&lt;/td&gt;&lt;td class="tr-caption" style="text-align: center;"&gt;&lt;/td&gt;&lt;td class="tr-caption" style="text-align: center;"&gt;&lt;/td&gt;&lt;td class="tr-caption" style="text-align: center;"&gt;&lt;/td&gt;&lt;td class="tr-caption" style="text-align: center;"&gt;&lt;/td&gt;&lt;td class="tr-caption" style="text-align: center;"&gt;&lt;/td&gt;&lt;td class="tr-caption" style="text-align: center;"&gt;&lt;/td&gt;&lt;td class="tr-caption" style="text-align: center;"&gt;&lt;/td&gt;&lt;td class="tr-caption" style="text-align: center;"&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;pre&gt;The server encountered an error processing the request. The exception message is 'SQL Server Compact is not intended for ASP.NET development.'. See server logs for more details. The exception stack trace is: &lt;br /&gt;&lt;br /&gt;at System.Data.SqlServerCe.SqlCeRestriction.CheckExplicitWebHosting() at System.Data.SqlServerCe.SqlCeConnection..ctor() at System.Data.SqlServerCe.SqlCeProviderFactory.CreateConnection() at System.Data.EntityClient.EntityConnection.GetStoreConnection(DbProviderFactory factory) at System.Data.EntityClient.EntityConnection.ChangeConnectionString(String newConnectionString) at System.Data.EntityClient.EntityConnection..ctor(String connectionString) at System.Data.Objects.ObjectContext.CreateEntityConnection(String connectionString) at System.Data.Objects.ObjectContext..ctor&lt;br /&gt;&lt;/pre&gt;I got this when I was hosting WCF DataService in the ASP.net application exposing my Entity Model. The entities were based on a SQL CE database. To see this message, we need to set the behavior of service to allow the exception details to be shown to the user by this setting on the WCF Data Service.&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;[ServiceBehavior(IncludeExceptionDetailInFaults = true)]&lt;br /&gt;public class MyDataService : DataService&amp;lt;App.ModelEntities&amp;gt;&lt;br /&gt;{&lt;br /&gt;    ...&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;pre style="background: none repeat scroll 0% 0% white; color: black; font-family: Consolas; font-size: 13px;"&gt;&lt;/pre&gt;&lt;pre style="background: none repeat scroll 0% 0% white; color: black; font-family: Consolas; font-size: 13px;"&gt;&lt;/pre&gt;&lt;pre style="background: none repeat scroll 0% 0% white; color: black; font-family: Consolas; font-size: 13px;"&gt;&lt;/pre&gt;&lt;/div&gt;Otherwise we see the following message when we run the application:&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://4.bp.blogspot.com/-SqwK8Thz6Kc/TaZawIaPkKI/AAAAAAAAA-4/lGe6k4LhpgA/s1600/2.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="123" src="http://4.bp.blogspot.com/-SqwK8Thz6Kc/TaZawIaPkKI/AAAAAAAAA-4/lGe6k4LhpgA/s640/2.jpg" width="640" /&gt;&lt;/a&gt;&lt;/div&gt;Although this is more secure message as we are not showing the stack trace to the user but during development this message seems very irritating. In order to avoid this and to get the detailed message set the above specified Service Behavior for the WCF Data Service.&lt;/div&gt;&lt;br /&gt;This must be remembered that this limitation seems more like a suggestion by Microsoft so as to discourage the use of SQL Server Compact Edition for public facing systems because of its security limitations. But there might be valid reasons to still use SQL CE for ASP.net applications for demo applications or in-house developed applications. In order to get around that we can use AppDomain slots to set &lt;i&gt;SQLServerCompactEditionUnderWebHosting&lt;/i&gt; to true. This results in allowing the use of SQL Server Compact edition by the runtime. We can set that during application startup in &lt;i&gt;Global.asax&lt;/i&gt;.&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;public class Global : System.Web.HttpApplication&lt;br /&gt;{&lt;br /&gt;    void Application_Start(object sender, EventArgs e)&lt;br /&gt;    {&lt;br /&gt;        // Code that runs on application startup&lt;br /&gt;        AppDomain.CurrentDomain.SetData("SQLServerCompactEditionUnderWebHosting", true);&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;Now when we run the application we can see the service successfully giving XML data. We have discussed about AppDomain slots here:&lt;br /&gt;&lt;br /&gt;&lt;a href="http://shujaatsiddiqi.blogspot.com/2011/01/in-this-post-we-will-discuss-named-slot.html"&gt;http://shujaatsiddiqi.blogspot.com/2011/01/in-this-post-we-will-discuss-named-slot.html&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8085117242240449595-5335218023233101760?l=www.shujaat.net' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.shujaat.net/feeds/5335218023233101760/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8085117242240449595&amp;postID=5335218023233101760&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/5335218023233101760'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/5335218023233101760'/><link rel='alternate' type='text/html' href='http://www.shujaat.net/2011/04/hosting-sql-ce-based-entity-models-in.html' title='Hosting SQL CE based Entity Models in WCF Data Service'/><author><name>Muhammad Shujaat Siddiqi</name><uri>http://www.blogger.com/profile/02519138704633566929</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://4.bp.blogspot.com/-jkYZZMFmlHo/TaZYnNKRCLI/AAAAAAAAA-0/RjR0amKqBHY/s72-c/1.jpg' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8085117242240449595.post-2524554967053548196</id><published>2011-03-25T02:25:00.000-05:00</published><updated>2011-03-25T02:25:07.878-05:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='NamedCaches'/><category scheme='http://www.blogger.com/atom/ns#' term='MVVM'/><category scheme='http://www.blogger.com/atom/ns#' term='wpf 4'/><category scheme='http://www.blogger.com/atom/ns#' term='wpf'/><category scheme='http://www.blogger.com/atom/ns#' term='.net framework 4.0'/><category scheme='http://www.blogger.com/atom/ns#' term='.net'/><category scheme='http://www.blogger.com/atom/ns#' term='MemoryCacheSection'/><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><category scheme='http://www.blogger.com/atom/ns#' term='MemoryCacheElement'/><title type='text'>WPF: Configuring System.Runtime.Caching.MemoryCache for an MVVM based App</title><content type='html'>This is a continuation of our post here:&lt;br /&gt;&lt;br /&gt;&lt;a href="http://shujaatsiddiqi.blogspot.com/2011/03/wpf-performance-improvement-for-mvvm.html"&gt;http://shujaatsiddiqi.blogspot.com/2011/03/wpf-performance-improvement-for-mvvm.html&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;In the above post we discussed how we can use the new caching feature available in &lt;i&gt;.net framework 4.0&lt;/i&gt; to improve the performance of a &lt;i&gt;WPF&lt;/i&gt; application. As an example we used an application implementing &lt;i&gt;MVVM&lt;/i&gt; pattern. In this example we would extend the example by discussing how we can use configuration option provided with this caching feature. We would also look at the underlying architecture provided by the framework to support this.&lt;br /&gt;&lt;br /&gt;As we discussed in the previous example, the framework has provided &lt;i&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.runtime.caching.memorycache.aspx"&gt;MemoryCache&lt;/a&gt;&lt;/i&gt;. This is an implementation of &lt;i&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.runtime.caching.objectcache.aspx"&gt;ObjectCache&lt;/a&gt;&lt;/i&gt; providing an in-memory caching mechanism. Let us create a simple view showing the fields from this cache.&lt;br /&gt;&lt;br /&gt;In order to use this you need to add a reference of System.Runtime.Caching assembly from the framework.&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://1.bp.blogspot.com/-Td_NBm7vWgs/TYrwhrZWm8I/AAAAAAAAA90/W4fT6CxdKhc/s1600/11.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="230" width="400" src="http://1.bp.blogspot.com/-Td_NBm7vWgs/TYrwhrZWm8I/AAAAAAAAA90/W4fT6CxdKhc/s400/11.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;Yes I have Power Tools installed :).&lt;br /&gt;&lt;pre class="brush: xml; gutter: false;"&gt;&amp;lt;Window x:Class="WPF_MVVM_Caching.MainWindow"&lt;br /&gt;        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"&lt;br /&gt;        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&lt;br /&gt;        xmlns:local="clr-namespace:WPF_MVVM_Caching"&lt;br /&gt;        Title="MainWindow" Height="350" Width="525"&amp;gt;&lt;br /&gt;    &amp;lt;Window.DataContext&amp;gt;&lt;br /&gt;        &amp;lt;local:MainWindowViewModel /&amp;gt;&lt;br /&gt;    &amp;lt;/Window.DataContext&amp;gt;&lt;br /&gt;    &amp;lt;Grid&amp;gt;&lt;br /&gt;        &amp;lt;Label Content="PollingInterval" Height="26" HorizontalAlignment="Left" &lt;br /&gt;               Margin="10,21,0,0" Name="label1" VerticalAlignment="Top" Width="141" /&amp;gt;&lt;br /&gt;        &amp;lt;TextBlock Height="26" HorizontalAlignment="Left" Margin="157,21,0,0" Name="txtPollingInterval"&lt;br /&gt;                   Background="LightGoldenrodYellow"&lt;br /&gt;                   Text="{Binding PollingInterval, Mode=OneTime}" VerticalAlignment="Top" Width="302" /&amp;gt;&lt;br /&gt;        &amp;lt;Label Content="PhysicalMemoryLimit" Height="26" HorizontalAlignment="Left" &lt;br /&gt;               Margin="10,53,0,0" Name="label2" VerticalAlignment="Top" Width="141" /&amp;gt;&lt;br /&gt;        &amp;lt;TextBlock Background="LightGoldenrodYellow" Height="26" HorizontalAlignment="Left" &lt;br /&gt;                   Margin="157,53,0,0" Name="txtPhysicalMemoryLimit" Text="{Binding PhysicalMemoryLimit, Mode=OneTime}" &lt;br /&gt;                   VerticalAlignment="Top" Width="302" /&amp;gt;&lt;br /&gt;        &amp;lt;Label Content="Name" Height="26" HorizontalAlignment="Left" &lt;br /&gt;               Margin="11,85,0,0" Name="label3" VerticalAlignment="Top" Width="140" /&amp;gt;&lt;br /&gt;        &amp;lt;TextBlock Background="LightGoldenrodYellow" Height="26" HorizontalAlignment="Left" &lt;br /&gt;                   Margin="157,85,0,0" Name="txtName" Text="{Binding Name, Mode=OneTime}" &lt;br /&gt;                   VerticalAlignment="Top" Width="302" /&amp;gt;&lt;br /&gt;        &amp;lt;Label Content="CacheMemoryLimit" Height="26" HorizontalAlignment="Left" &lt;br /&gt;               Margin="10,116,0,0" Name="label4" VerticalAlignment="Top" Width="141" /&amp;gt;&lt;br /&gt;        &amp;lt;TextBlock Background="LightGoldenrodYellow" Height="26" HorizontalAlignment="Left" &lt;br /&gt;                   Margin="157,116,0,0" Name="txtCacheMemoryLimit" Text="{Binding CacheMemoryLimit, Mode=OneTime}" &lt;br /&gt;                   VerticalAlignment="Top" Width="302" /&amp;gt;&lt;br /&gt;    &amp;lt;/Grid&amp;gt;&lt;br /&gt;&amp;lt;/Window&amp;gt;&lt;/pre&gt;&lt;br /&gt;The view is expecting certain properties from &lt;i&gt;MainWindowViewModel&lt;/i&gt; which is used as its &lt;i&gt;DataContext&lt;/i&gt;. They are bound with Text properties of TextBlocks. The definition of MainWindowViewModel is as follows:&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;namespace WPF_MVVM_Caching&lt;br /&gt;{&lt;br /&gt;    using System.ComponentModel;&lt;br /&gt;    using System.Runtime.Caching;&lt;br /&gt;&lt;br /&gt;    class MainWindowViewModel : INotifyPropertyChanged&lt;br /&gt;    {&lt;br /&gt;        public string CacheMemoryLimit&lt;br /&gt;        {&lt;br /&gt;            get { return string.Format("{0}", MemoryCache.Default.CacheMemoryLimit); }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public string PollingInterval&lt;br /&gt;        {&lt;br /&gt;            get { return string.Format("{0}", MemoryCache.Default.PollingInterval); }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public string PhysicalMemoryLimit&lt;br /&gt;        {&lt;br /&gt;            get { return string.Format("{0}", MemoryCache.Default.PhysicalMemoryLimit); }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public string Name&lt;br /&gt;        {&lt;br /&gt;            get { return MemoryCache.Default.Name; }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        #region INotifyPropertyChanged Implementation&lt;br /&gt;        &lt;br /&gt;        public event PropertyChangedEventHandler PropertyChanged = delegate { };&lt;br /&gt;        private void onPropertyChanged(string propertyName)&lt;br /&gt;        {&lt;br /&gt;            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        #endregion INotifyPropertyChanged Implementation&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://3.bp.blogspot.com/-3Um4SzRDSPA/TYr5M6eTtAI/AAAAAAAAA98/DAZqoeENdrQ/s1600/12.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="267" width="400" src="http://3.bp.blogspot.com/-3Um4SzRDSPA/TYr5M6eTtAI/AAAAAAAAA98/DAZqoeENdrQ/s400/12.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;b&gt;Loading Default Memory Cache with Configuration Options:&lt;/b&gt;&lt;br /&gt;The configuration of default MemoryCache is easy. We just need to provide the following code in the app.config file and the framework automatically loads the MemoryCache with the specified values as in the configuration file.&lt;br /&gt;&lt;pre class="brush: xml; gutter: false;"&gt;&amp;lt;?xml version="1.0"?&amp;gt;&lt;br /&gt;&amp;lt;configuration&amp;gt;&lt;br /&gt;  &amp;lt;system.runtime.caching&amp;gt;&lt;br /&gt;    &amp;lt;memoryCache&amp;gt;&lt;br /&gt;      &amp;lt;namedCaches&amp;gt;&lt;br /&gt;        &amp;lt;add name="Default"&lt;br /&gt;             cacheMemoryLimitMegabytes="52"&lt;br /&gt;             physicalMemoryLimitPercentage="40"&lt;br /&gt;             pollingInterval="00:04:01" /&amp;gt;&lt;br /&gt;      &amp;lt;/namedCaches&amp;gt;&lt;br /&gt;    &amp;lt;/memoryCache&amp;gt;&lt;br /&gt;  &amp;lt;/system.runtime.caching&amp;gt;&lt;br /&gt;  &amp;lt;startup&amp;gt;&lt;br /&gt;    &amp;lt;supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/&amp;gt;&lt;br /&gt;  &amp;lt;/startup&amp;gt;&lt;br /&gt;&amp;lt;/configuration&amp;gt;&lt;/pre&gt;Now run the application. We can see that the MemoryCache.Default is constructed with the values that we specified in the configuration file. The view would appear as follows:&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/-5kubLEK9zxw/TYtRLyltCvI/AAAAAAAAA-E/X3-WjSN2wFQ/s1600/13.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="267" width="400" src="http://2.bp.blogspot.com/-5kubLEK9zxw/TYtRLyltCvI/AAAAAAAAA-E/X3-WjSN2wFQ/s400/13.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;So in order to provide the definition of the Default &lt;i&gt;MemoryCache&lt;/i&gt; configuration, we just need to make sure that we use name &lt;i&gt;Default&lt;/i&gt; and provide the values for the properties that we want to change. The properties not specified in configuration would be kept with default values.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Configuring Non-Default Caches:&lt;/b&gt;&lt;br /&gt;In the above example we have seen how we can configure the &lt;i&gt;Default MemoryCache&lt;/i&gt;. We can use the same technique to configure a non-default cache. We might be needing it when we want to define a local cache. In order to instantiate a non-default cache, whose properties expected to be loaded from a configuration file, MemoryCache provides a constructor. We need to provide the name of cache configuration to use to construct the cache instance as follows:&lt;br /&gt;&lt;pre class="brush: xml; gutter: false;"&gt;&amp;lt;?xml version="1.0"?&amp;gt;&lt;br /&gt;&amp;lt;configuration&amp;gt;&lt;br /&gt;  &amp;lt;system.runtime.caching&amp;gt;&lt;br /&gt;    &amp;lt;memoryCache&amp;gt;&lt;br /&gt;      &amp;lt;namedCaches&amp;gt;&lt;br /&gt;        &amp;lt;add name="TestCache"&lt;br /&gt;             cacheMemoryLimitMegabytes="52"&lt;br /&gt;             physicalMemoryLimitPercentage="40"&lt;br /&gt;             pollingInterval="00:04:01" /&amp;gt;&lt;br /&gt;      &amp;lt;/namedCaches&amp;gt;&lt;br /&gt;    &amp;lt;/memoryCache&amp;gt;&lt;br /&gt;  &amp;lt;/system.runtime.caching&amp;gt;&lt;br /&gt;  &amp;lt;startup&amp;gt;&lt;br /&gt;    &amp;lt;supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/&amp;gt;&lt;br /&gt;  &amp;lt;/startup&amp;gt;&lt;br /&gt;&amp;lt;/configuration&amp;gt;&lt;/pre&gt;We can use this cache as follows:&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;class MainWindowViewModel : INotifyPropertyChanged&lt;br /&gt;{&lt;br /&gt;    MemoryCache cache;&lt;br /&gt;&lt;br /&gt;    public MainWindowViewModel()&lt;br /&gt;    {&lt;br /&gt;        cache = new MemoryCache("TestCache");&lt;br /&gt;        //string s = "";&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public string CacheMemoryLimit&lt;br /&gt;    {&lt;br /&gt;        get { return string.Format("{0}", cache.CacheMemoryLimit); }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public string PollingInterval&lt;br /&gt;    {&lt;br /&gt;        get { return string.Format("{0}", cache.PollingInterval); }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public string PhysicalMemoryLimit&lt;br /&gt;    {&lt;br /&gt;        get { return string.Format("{0}", cache.PhysicalMemoryLimit); }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public string Name&lt;br /&gt;    {&lt;br /&gt;        get { return cache.Name; }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    #region INotifyPropertyChanged Implementation&lt;br /&gt;    &lt;br /&gt;    public event PropertyChangedEventHandler PropertyChanged = delegate { };&lt;br /&gt;    private void onPropertyChanged(string propertyName)&lt;br /&gt;    {&lt;br /&gt;        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    #endregion INotifyPropertyChanged Implementation&lt;br /&gt;}&lt;/pre&gt;When we run the application we can see that the properties are successfully loaded from the configuration and the view is shown as follows:&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://4.bp.blogspot.com/--qKV3_2OOq0/TYwvnJ_BmII/AAAAAAAAA-c/WiSMbw1gbLo/s1600/14.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="267" width="400" src="http://4.bp.blogspot.com/--qKV3_2OOq0/TYwvnJ_BmII/AAAAAAAAA-c/WiSMbw1gbLo/s400/14.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;b&gt;System.Runtime.Caching.Configuration in Details&lt;/b&gt;&lt;br /&gt;Now let us look at the underlying architecture used by the above logic. The configuration classes for run-time caching is provided in &lt;i&gt;System.Runtime.Caching.Configuration&lt;/i&gt; namespace in &lt;i&gt;System.Runtime.Caching&lt;/i&gt; assembly. They are based on the same logic we implement when we want configuration option for some classes i.e. We have to define classes inheriting from the following classes:&lt;br /&gt;&lt;br /&gt;- &lt;i&gt;ConfigurationElement&lt;/i&gt;&lt;br /&gt;- &lt;i&gt;ConfigurationElementCollection&lt;/i&gt;&lt;br /&gt;- &lt;i&gt;ConfigurationSection&lt;/i&gt; &lt;br /&gt;- &lt;i&gt;ConfigurationSectionGroup&lt;/i&gt;&lt;br /&gt;&lt;br /&gt;For &lt;i&gt;System.Runtime.Caching&lt;/i&gt;, these classes are as follows:&lt;br /&gt;- MemoryCacheElement&lt;br /&gt;- MemoryCacheSettingsCollection&lt;br /&gt;- MemoryCacheSection&lt;br /&gt;- CachingSectionGroup&lt;br /&gt;&lt;br /&gt;They can be shown in the class diagram as follows:&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://1.bp.blogspot.com/-d6pud7NTkEU/TYwrgSEJV0I/AAAAAAAAA-M/zYv26vmy1Rc/s1600/ConfigurationAPI1.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="208" width="400" src="http://1.bp.blogspot.com/-d6pud7NTkEU/TYwrgSEJV0I/AAAAAAAAA-M/zYv26vmy1Rc/s400/ConfigurationAPI1.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://3.bp.blogspot.com/-_NGSuFQrReI/TYwtCNHII-I/AAAAAAAAA-U/8d-UiuQOv8o/s1600/ConfigurationAPI2.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="230" width="266" src="http://3.bp.blogspot.com/-_NGSuFQrReI/TYwtCNHII-I/AAAAAAAAA-U/8d-UiuQOv8o/s400/ConfigurationAPI2.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;Now in order to go further with this example we need to add a reference of System.Configuration assembly as follows:&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://3.bp.blogspot.com/-ZfHVSey3sqc/TYw2E9u9EsI/AAAAAAAAA-k/ZrYDh6Z8uXQ/s1600/15.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="230" width="400" src="http://3.bp.blogspot.com/-ZfHVSey3sqc/TYw2E9u9EsI/AAAAAAAAA-k/ZrYDh6Z8uXQ/s400/15.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;Let us update the configuration file as follows:&lt;br /&gt;&lt;pre class="brush: xml; gutter: false;"&gt;&amp;lt;?xml version="1.0"?&amp;gt;&lt;br /&gt;&amp;lt;configuration&amp;gt;&lt;br /&gt;  &amp;lt;configSections&amp;gt;&lt;br /&gt;    &amp;lt;section name="MemoryCacheConfiguration"&lt;br /&gt;                  type="System.Runtime.Caching.Configuration.MemoryCacheSection, System.Runtime.Caching, Version= 4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" /&amp;gt;&lt;br /&gt;  &amp;lt;/configSections&amp;gt;&lt;br /&gt;  &amp;lt;MemoryCacheConfiguration&amp;gt;&lt;br /&gt;    &amp;lt;namedCaches&amp;gt;&lt;br /&gt;      &amp;lt;add name="MyMemoryCache" physicalMemoryLimitPercentage="23"&lt;br /&gt;            pollingInterval="00:04:43" cacheMemoryLimitMegabytes="123" /&amp;gt;&lt;br /&gt;    &amp;lt;/namedCaches&amp;gt;&lt;br /&gt;  &amp;lt;/MemoryCacheConfiguration&amp;gt;&lt;br /&gt;&amp;lt;/configuration&amp;gt;&lt;br /&gt;&lt;/pre&gt;Here we have defined a section named &lt;i&gt;MemoryCacheConfiguration&lt;/i&gt; for &lt;i&gt;System.Runtime.Caching.MemoryCacheSection&lt;/i&gt; type. Later we have provided the details about &lt;i&gt;MemoryCacheConfiguration&lt;/i&gt; with details about runtime cache. &lt;br /&gt;&lt;br /&gt;Now we instantiate a memory cache based on the information provided here in the configuration file. We can update the view model's constructor as follows:&lt;br /&gt;&lt;pre  class="brush: csharp; gutter: false;"&gt;public MainWindowViewModel()&lt;br /&gt;{&lt;br /&gt;    //Get Configuration section info from Configuration&lt;br /&gt;    MemoryCacheSection section = (MemoryCacheSection)ConfigurationManager.GetSection("MemoryCacheConfiguration");&lt;br /&gt;&lt;br /&gt;    //Create a name / value pair for properties&lt;br /&gt;    NameValueCollection configurationNameValueCollection = new NameValueCollection();&lt;br /&gt;    configurationNameValueCollection.Add("pollingInterval", &lt;br /&gt;        string.Format("{0}", section.NamedCaches[0].PollingInterval));&lt;br /&gt;    configurationNameValueCollection.Add("physicalMemoryLimitPercentage", &lt;br /&gt;        string.Format("{0}", section.NamedCaches[0].PhysicalMemoryLimitPercentage));&lt;br /&gt;    configurationNameValueCollection.Add("cacheMemoryLimitMegabytes", &lt;br /&gt;        string.Format("{0}", section.NamedCaches[0].CacheMemoryLimitMegabytes));&lt;br /&gt;    &lt;br /&gt;    //instantiate cache&lt;br /&gt;    cache = new MemoryCache(section.NamedCaches[0].Name, configurationNameValueCollection);&lt;br /&gt;}&lt;/pre&gt;Now let us run the application. The view should appear as follows:&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://1.bp.blogspot.com/-fjgFUBppXcw/TYxBUkOM5bI/AAAAAAAAA-s/6rFFKFHZBcs/s1600/16.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="267" width="400" src="http://1.bp.blogspot.com/-fjgFUBppXcw/TYxBUkOM5bI/AAAAAAAAA-s/6rFFKFHZBcs/s400/16.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;b&gt;Download Code:&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;&lt;iframe title ="Preview" scrolling="no" marginheight="0" marginwidth="0" frameborder="0" style="width:98px;height:115px;padding:0;background-color:#fcfcfc;" src="http://cid-b5fee7d7acde5072.office.live.com/embedicon.aspx/WPF%20Caching%202/WPF%20Caching.zip"&gt;&lt;/iframe&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8085117242240449595-2524554967053548196?l=www.shujaat.net' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.shujaat.net/feeds/2524554967053548196/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8085117242240449595&amp;postID=2524554967053548196&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/2524554967053548196'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/2524554967053548196'/><link rel='alternate' type='text/html' href='http://www.shujaat.net/2011/03/wpf-configuring-systemruntimecachingmem.html' title='WPF: Configuring System.Runtime.Caching.MemoryCache for an MVVM based App'/><author><name>Muhammad Shujaat Siddiqi</name><uri>http://www.blogger.com/profile/02519138704633566929</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://1.bp.blogspot.com/-Td_NBm7vWgs/TYrwhrZWm8I/AAAAAAAAA90/W4fT6CxdKhc/s72-c/11.jpg' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8085117242240449595.post-8526381864817717407</id><published>2011-03-17T01:17:00.005-05:00</published><updated>2011-03-17T09:18:11.705-05:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='MVVM'/><category scheme='http://www.blogger.com/atom/ns#' term='caching'/><category scheme='http://www.blogger.com/atom/ns#' term='objectcache'/><category scheme='http://www.blogger.com/atom/ns#' term='cacheitempolicy'/><category scheme='http://www.blogger.com/atom/ns#' term='.net 4.0'/><category scheme='http://www.blogger.com/atom/ns#' term='.net'/><category scheme='http://www.blogger.com/atom/ns#' term='System.Runtime.Caching'/><category scheme='http://www.blogger.com/atom/ns#' term='memorycache'/><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><category scheme='http://www.blogger.com/atom/ns#' term='changemonitor'/><category scheme='http://www.blogger.com/atom/ns#' term='performance improvement'/><title type='text'>WPF - Performance Improvement for MVVM Based Applications - Part # 3</title><content type='html'>This is third part of our discussion about .net features and techniques to improve the performance of MVVM based applications. The other part of this discussion are:&lt;br /&gt;&lt;br /&gt;Part 1: &lt;a href="http://shujaatsiddiqi.blogspot.com/2011/01/wpf-performance-improvement-for-mvvm.html"&gt;http://shujaatsiddiqi.blogspot.com/2011/01/wpf-performance-improvement-for-mvvm.html&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Part 2: &lt;a href="http://shujaatsiddiqi.blogspot.com/2011/02/wpf-performance-improvement-for-mvvm.html"&gt;http://shujaatsiddiqi.blogspot.com/2011/02/wpf-performance-improvement-for-mvvm.html&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;In this post we will be discussing how we can use Caching to improve the performance of an application. Support of Caching in desktop application is a new feature of .net framework 4.0. &lt;br /&gt;&lt;br /&gt;&lt;b&gt;Assembly and Namespace:&lt;/b&gt;&lt;br /&gt;Most of the classes used for caching feature are available in &lt;i&gt;System.Runtime.Caching&lt;/i&gt; namespace available in &lt;i&gt;System.Runtime.Caching assembly&lt;/i&gt;. We need to add an assembly reference of this assembly in order to use these types. &lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/-nENeXTwWP-E/TXhOTh3RSmI/AAAAAAAAA8k/hSTin9NqIYY/s1600/1.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="217" width="400" src="http://2.bp.blogspot.com/-nENeXTwWP-E/TXhOTh3RSmI/AAAAAAAAA8k/hSTin9NqIYY/s400/1.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;b&gt;Extensible Caching Implementation:&lt;/b&gt;&lt;br /&gt;The cache system available in .net 4.0 has been implemented from ground up to be an extensible concept. A Cache provider must inherit from &lt;i&gt;ObjectCache&lt;/i&gt; available in &lt;i&gt;System.Runtime.Caching&lt;/i&gt; namespace. The cache provider available with .net is &lt;i&gt;MemoryCache&lt;/i&gt;. It represents an in-memory cache. This is similar to ASP.net cache but you don't need to use System.Web.Caching as it is available in the same &lt;i&gt;System.Runtime.Caching&lt;/i&gt; namespace in &lt;i&gt;System.Runtime.Caching&lt;/i&gt; assembly. The other benefit is that we can create multiple instances of &lt;i&gt;MemoryCache&lt;/i&gt; in the same &lt;i&gt;AppDomain&lt;/i&gt;.&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://3.bp.blogspot.com/-8CEfvJT-390/TXhPRyPBSuI/AAAAAAAAA8s/kOXii2UOLVA/s1600/2.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="335" width="400" src="http://3.bp.blogspot.com/-8CEfvJT-390/TXhPRyPBSuI/AAAAAAAAA8s/kOXii2UOLVA/s400/2.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;b&gt;Simple Caching Usage for temporal locality of reference:&lt;/b&gt;&lt;br /&gt;Let's consider an example of a WPF application using this. In this example we would be utilizing the idea of temporal locality of reference. We would be reading the contents of a File. Since I/O is a time consuming operation, we will be caching the contents of the file. We will be using this cached content from other window, where we would be showing it in a &lt;i&gt;TextBlock&lt;/i&gt;. The definition of MainWindow is as follows:&lt;br /&gt;&lt;pre class="brush: xml; gutter: false;"&gt;&amp;lt;Window x:Class="WpfApp_MVVM_Caching.MainWindow"&lt;br /&gt;        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"&lt;br /&gt;        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&lt;br /&gt;        xmlns:local="clr-namespace:WpfApp_MVVM_Caching"&lt;br /&gt;        Title="MainWindow" Height="350" Width="525"&amp;gt;&lt;br /&gt;    &amp;lt;Window.DataContext&amp;gt;&lt;br /&gt;        &amp;lt;local:MainWindowViewModel /&amp;gt;&lt;br /&gt;    &amp;lt;/Window.DataContext&amp;gt;&lt;br /&gt;    &amp;lt;Grid&amp;gt;&lt;br /&gt;        &amp;lt;TextBlock Height="81" HorizontalAlignment="Left" Margin="12,17,0,0" &lt;br /&gt;                   Name="textBlock1" Text="{Binding FileContents}" VerticalAlignment="Top" Width="468" /&amp;gt;&lt;br /&gt;        &amp;lt;Button Content="Open Child Window" Height="26" HorizontalAlignment="Left" Margin="12,273,0,0" Name="btnOpenChildWindow" &lt;br /&gt;                VerticalAlignment="Top" Width="134" Click="btnOpenChildWindow_Click" /&amp;gt;&lt;br /&gt;    &amp;lt;/Grid&amp;gt;&lt;br /&gt;&amp;lt;/Window&amp;gt;&lt;/pre&gt;This window has a &lt;i&gt;TextBlock &lt;/i&gt;to display the contents of the file. The &lt;i&gt;Text &lt;/i&gt;property of this TextBlock is bound to &lt;i&gt;FileContents&lt;/i&gt; property of &lt;i&gt;DataContext&lt;/i&gt;. The window also has a button. The definition of click event handler [&lt;i&gt;btnOpenChildWindow_Click&lt;/i&gt;] from the code behind is as follows:&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;private void btnOpenChildWindow_Click(object sender, RoutedEventArgs e)&lt;br /&gt;{&lt;br /&gt;    new ChildWindow().Show();&lt;br /&gt;}&lt;/pre&gt;This is just opening the &lt;i&gt;ChildWindow &lt;/i&gt;as a modeless window using its &lt;i&gt;Show &lt;/i&gt;method. &lt;i&gt;MainWindow &lt;/i&gt;is using &lt;i&gt;MainWindowViewModel &lt;/i&gt;instance as its &lt;i&gt;DataContext&lt;/i&gt;. It is constructing its instance as part of its initialization code. The definition of &lt;i&gt;MainWindowViewModel &lt;/i&gt;is as follows:&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;class MainWindowViewModel : INotifyPropertyChanged&lt;br /&gt;{&lt;br /&gt;&lt;br /&gt;    public MainWindowViewModel()&lt;br /&gt;    {&lt;br /&gt;        string localfileContents = File.ReadAllText(@"C:\Users\shujaat\Desktop\s.txt");&lt;br /&gt;        FileContents = localfileContents;&lt;br /&gt;&lt;br /&gt;        MemoryCache.Default.Set("filecontents", localfileContents, DateTimeOffset.MaxValue);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    #region Properties&lt;br /&gt;    &lt;br /&gt;    private string _fileContents;&lt;br /&gt;    public string FileContents&lt;br /&gt;    {&lt;br /&gt;        get { return _fileContents; }&lt;br /&gt;        set&lt;br /&gt;        {&lt;br /&gt;            _fileContents = value;&lt;br /&gt;            OnPropertyChanged("FileContents");&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    #endregion&lt;br /&gt;&lt;br /&gt;    #region INotifyPropertyChanged implementation&lt;br /&gt;&lt;br /&gt;    public event PropertyChangedEventHandler PropertyChanged = delegate { };&lt;br /&gt;    private void OnPropertyChanged(string propertyName)&lt;br /&gt;    {&lt;br /&gt;        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    #endregion INotifyPropertyChanged implementation&lt;br /&gt;&lt;br /&gt;}&lt;/pre&gt;As expected by the view, It just has a property &lt;i&gt;FileContents&lt;/i&gt;. In the constructor, the contents of a file is read and assigned to this property. Since this is based on INotifyPropertyChanged, the changes are propagated to the view using &lt;i&gt;PropertyChanged &lt;/i&gt;event. Additionally, we are copying the data read from the file to &lt;i&gt;MemoryCache.Default&lt;/i&gt; with Key '&lt;i&gt;fileconents&lt;/i&gt;'.&lt;br /&gt;&lt;br /&gt;The definition of &lt;i&gt;ChildWindow&lt;/i&gt; is as follows:&lt;br /&gt;&lt;pre class="brush: xml; gutter: false;"&gt;&amp;lt;Window x:Class="WpfApp_MVVM_Caching.ChildWindow"&lt;br /&gt;        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"&lt;br /&gt;        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&lt;br /&gt;        xmlns:local="clr-namespace:WpfApp_MVVM_Caching"&lt;br /&gt;        Title="Child Window" Height="300" Width="300"&amp;gt;&lt;br /&gt;    &amp;lt;Window.DataContext&amp;gt;&lt;br /&gt;        &amp;lt;local:ChildWindowViewModel /&amp;gt;&lt;br /&gt;    &amp;lt;/Window.DataContext&amp;gt;&lt;br /&gt;    &amp;lt;Grid&amp;gt;&lt;br /&gt;        &amp;lt;TextBlock Height="61" HorizontalAlignment="Left" Margin="36,49,0,0" Name="textBlock1" &lt;br /&gt;                   VerticalAlignment="Top" Width="206" Text="{Binding CacheEntryValue}" /&amp;gt;&lt;br /&gt;    &amp;lt;/Grid&amp;gt;&lt;br /&gt;&amp;lt;/Window&amp;gt;&lt;/pre&gt;It has a &lt;i&gt;TextBlock &lt;/i&gt;whose Text property is bound to &lt;i&gt;CacheEntryValue &lt;/i&gt;property from the &lt;i&gt;DataContext&lt;/i&gt;. The DataContext is an instance of &lt;i&gt;ChildWindowViewModel&lt;/i&gt;. Its definition is as follows:&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;class ChildWindowViewModel : INotifyPropertyChanged&lt;br /&gt;{&lt;br /&gt;    private string _cacheEntryValue;&lt;br /&gt;    public string CacheEntryValue&lt;br /&gt;    {&lt;br /&gt;        get { return _cacheEntryValue; }&lt;br /&gt;        set&lt;br /&gt;        {&lt;br /&gt;            _cacheEntryValue = value;&lt;br /&gt;            OnPropertyChanged("CacheEntryValue");&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public ChildWindowViewModel()&lt;br /&gt;    {&lt;br /&gt;        CacheEntryValue = MemoryCache.Default["filecontents"] as string;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    #region INotifyPropertyChanged implementation&lt;br /&gt;&lt;br /&gt;    public event PropertyChangedEventHandler PropertyChanged = delegate { };&lt;br /&gt;    private void OnPropertyChanged(string propertyName)&lt;br /&gt;    {&lt;br /&gt;        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    #endregion INotifyPropertyChanged implementation&lt;br /&gt;}&lt;/pre&gt;We are just copying the contents of the cache entry defined in the MainWindow to the Text property of the TextBlock. Using the value is achieved using the idea of temporal locality of Caching technology. Let's run the application and open child window.&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://4.bp.blogspot.com/-DeLkYFnNQ7s/TX2SLHLsFEI/AAAAAAAAA88/iEHV6QPZAug/s1600/4.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="173" width="400" src="http://4.bp.blogspot.com/-DeLkYFnNQ7s/TX2SLHLsFEI/AAAAAAAAA88/iEHV6QPZAug/s400/4.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;As you might already have guessed, the contents of the file are: "Muhammad Shujaat Siddiqi".&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Changes in Underlying DataSource:&lt;/b&gt;&lt;br /&gt;Cache keeps the data available in an application for faster data access when it is needed. The user of this cache might or might not know about the actual data source. The caching feature available in &lt;i&gt;.net framework 4.0&lt;/i&gt; keeps track of this is through the provision of &lt;i&gt;ChangeMonitor&lt;/i&gt;. This is basically kind of implementation of &lt;i&gt;Observer&lt;/i&gt; design pattern. So when underlying datasource is changed, the &lt;i&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.runtime.caching.changemonitor.aspx"&gt;ChangeMonitor&lt;/a&gt;&lt;/i&gt; notifies the &lt;i&gt;ObjectCache&lt;/i&gt; implemenation [&lt;a href="http://msdn.microsoft.com/en-us/library/system.runtime.caching.memorycache.aspx"&gt;&lt;i&gt;MemoryCache&lt;/i&gt;&lt;/a&gt;] about this change. ObjectCache implementation then takes any action about this change. It might even nullify the Cache entry as it is invalid now [Like the case of &lt;i&gt;MemoryCache&lt;/i&gt;]. &lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://4.bp.blogspot.com/-srFTz6ueCc0/TXhS83KmeYI/AAAAAAAAA80/aPZgdcgjKo4/s1600/3.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="228" width="400" src="http://4.bp.blogspot.com/-srFTz6ueCc0/TXhS83KmeYI/AAAAAAAAA80/aPZgdcgjKo4/s400/3.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;Let us create a new Window to present an example of a WPF application using &lt;i&gt;ChangeMonitor&lt;/i&gt;. The Window below is a similar window as the above example. It just has an extra &lt;i&gt;TextBox&lt;/i&gt; and a &lt;i&gt;Button&lt;/i&gt;. &lt;br /&gt;&lt;pre class="brush: xml; gutter: false;"&gt;&amp;lt;Window x:Class="WpfApp_MVVM_Caching.MainWindowChangeMonitorExample"&lt;br /&gt;         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"&lt;br /&gt;        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&lt;br /&gt;        xmlns:local="clr-namespace:WpfApp_MVVM_Caching"&lt;br /&gt;        Title="MainWindow" Height="350" Width="525"&amp;gt;&lt;br /&gt;    &amp;lt;Window.DataContext&amp;gt;&lt;br /&gt;        &amp;lt;local:MainWindowChangeMonitorExampleViewModel /&amp;gt;&lt;br /&gt;    &amp;lt;/Window.DataContext&amp;gt;&lt;br /&gt;    &amp;lt;Grid&amp;gt;&lt;br /&gt;        &amp;lt;TextBlock Height="81" HorizontalAlignment="Left" Margin="12,17,0,0" &lt;br /&gt;                   Name="textBlock1" Text="{Binding FileContents}" VerticalAlignment="Top" Width="468" /&amp;gt;&lt;br /&gt;        &amp;lt;TextBox Height="138" HorizontalAlignment="Left" Margin="279,125,0,0" Name="textBoxCachedFileContents"&lt;br /&gt;                 VerticalAlignment="Top" Width="212" Text="{Binding Path=MessageToDataSource, UpdateSourceTrigger=PropertyChanged}" /&amp;gt;&lt;br /&gt;        &amp;lt;Button Content="Update Data Source" Height="30" HorizontalAlignment="Left" &lt;br /&gt;                Margin="314,269,0,0" Name="btnUpdateDataSource" VerticalAlignment="Top" &lt;br /&gt;                Width="177" Command="{Binding UpdateDataSourceCommand}" /&amp;gt;&lt;br /&gt;        &amp;lt;Button Content="Open Child Window" Height="26" HorizontalAlignment="Left" Margin="12,273,0,0" Name="btnOpenChildWindow" &lt;br /&gt;                VerticalAlignment="Top" Width="134" Click="btnOpenChildWindow_Click" /&amp;gt;&lt;br /&gt;    &amp;lt;/Grid&amp;gt;&lt;br /&gt;&amp;lt;/Window&amp;gt;&lt;/pre&gt;The above view is using a new instance of &lt;i&gt;MainWindowChangeMonitorExampleViewModel&lt;/i&gt; as its DataContext. It is expecting a string property FileContents to bind to the Text property of the &lt;i&gt;TextBlock&lt;/i&gt;. Additionally, it is also expecting the &lt;i&gt;DataContext&lt;/i&gt; to have &lt;i&gt;MessageToDataSource&lt;/i&gt; property to bind to the Text property of the only TextBox. When a user clicks the Update button the contents of TextBox should be updated to the &lt;i&gt;DataSource&lt;/i&gt; (File). Since &lt;i&gt;FileContents&lt;/i&gt; are invalid now, it should be updated to the latest contents. For that, the view model should use &lt;i&gt;ChangeMonitor&lt;/i&gt;. But first look at the code behind of this view.&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;public partial class MainWindowChangeMonitorExample : Window&lt;br /&gt;{&lt;br /&gt;    public MainWindowChangeMonitorExample()&lt;br /&gt;    {&lt;br /&gt;        InitializeComponent();&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private void btnOpenChildWindow_Click(object sender, RoutedEventArgs e)&lt;br /&gt;    {&lt;br /&gt;        new ChildWindow().Show();&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;This is similar to the view in the previous examples. When user clicks &lt;i&gt;"Open Child Window"&lt;/i&gt;, a new instance of &lt;i&gt;ChildWindow&lt;/i&gt; is shown in a &lt;i&gt;modeless&lt;/i&gt; fashion. Now we have a look at the View Model. Get ready to see Change Monitors in action...&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;class MainWindowChangeMonitorExampleViewModel : INotifyPropertyChanged&lt;br /&gt;{&lt;br /&gt;    #region Fields&lt;br /&gt;&lt;br /&gt;    List&amp;lt;string&amp;gt; filePaths = new List&amp;lt;string&amp;gt;();&lt;br /&gt;&lt;br /&gt;    #endregion Fields&lt;br /&gt;&lt;br /&gt;    #region Constructors&lt;br /&gt;&lt;br /&gt;    public MainWindowChangeMonitorExampleViewModel()&lt;br /&gt;    {&lt;br /&gt;        filePaths.Add(@"C:\Users\shujaat\Desktop\s.txt");&lt;br /&gt;        &lt;br /&gt;        string localfileContents = File.ReadAllText(@"C:\Users\shujaat\Desktop\s.txt");&lt;br /&gt;        FileContents = localfileContents;&lt;br /&gt;&lt;br /&gt;        var changeMonitor = new HostFileChangeMonitor(filePaths);&lt;br /&gt;        var policy = new CacheItemPolicy();&lt;br /&gt;&lt;br /&gt;        MemoryCache.Default.Set("filecontents", localfileContents, policy);&lt;br /&gt;                                 &lt;br /&gt;        policy.ChangeMonitors.Add(changeMonitor);            &lt;br /&gt;        changeMonitor.NotifyOnChanged(OnDataSourceUpdated);&lt;br /&gt;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    #endregion Constructors&lt;br /&gt;&lt;br /&gt;    #region Change Monitor Callback&lt;br /&gt;&lt;br /&gt;    private void OnDataSourceUpdated(Object State)&lt;br /&gt;    {&lt;br /&gt;        //Get file contents&lt;br /&gt;        FileInfo file = new FileInfo(@"C:\Users\shujaat\Desktop\s.txt");&lt;br /&gt;        using (FileStream stream = file.OpenRead())&lt;br /&gt;        {&lt;br /&gt;            using (StreamReader reader = new StreamReader(stream))&lt;br /&gt;            {&lt;br /&gt;                string updatedFileContents = reader.ReadToEnd();&lt;br /&gt;                reader.Close();&lt;br /&gt;                FileContents = updatedFileContents;&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        //Update Cache Entry&lt;br /&gt;        MemoryCache.Default["filecontents"] = FileContents;&lt;br /&gt;&lt;br /&gt;        //Update change monitor for further changes in file contents&lt;br /&gt;        var policy = new CacheItemPolicy();&lt;br /&gt;        var changeMonitor = new HostFileChangeMonitor(filePaths);&lt;br /&gt;        policy.ChangeMonitors.Add(changeMonitor);&lt;br /&gt;        changeMonitor.NotifyOnChanged(OnDataSourceUpdated);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    #endregion Change Monitor Callback&lt;br /&gt;&lt;br /&gt;    #region Properties&lt;br /&gt;&lt;br /&gt;    private string _fileContents;&lt;br /&gt;    public string FileContents&lt;br /&gt;    {&lt;br /&gt;        get { return _fileContents; }&lt;br /&gt;        set&lt;br /&gt;        {&lt;br /&gt;            _fileContents = value;&lt;br /&gt;            OnPropertyChanged("FileContents");&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private string _messageToDataSource;&lt;br /&gt;    public string MessageToDataSource&lt;br /&gt;    {&lt;br /&gt;        get { return _messageToDataSource; }&lt;br /&gt;        set&lt;br /&gt;        {&lt;br /&gt;            _messageToDataSource = value;&lt;br /&gt;            OnPropertyChanged("MessageToDataSource");&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    #endregion&lt;br /&gt;&lt;br /&gt;    #region INotifyPropertyChanged implementation&lt;br /&gt;&lt;br /&gt;    public event PropertyChangedEventHandler PropertyChanged = delegate { };&lt;br /&gt;    private void OnPropertyChanged(string propertyName)&lt;br /&gt;    {&lt;br /&gt;        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    #endregion INotifyPropertyChanged implementation&lt;br /&gt;&lt;br /&gt;    #region Commands&lt;br /&gt;&lt;br /&gt;    ICommand _updateDataSourceCommand;&lt;br /&gt;    public ICommand UpdateDataSourceCommand&lt;br /&gt;    {&lt;br /&gt;        get&lt;br /&gt;        {&lt;br /&gt;            if (_updateDataSourceCommand == null)&lt;br /&gt;            {&lt;br /&gt;                _updateDataSourceCommand = new RelayCommand(&lt;br /&gt;                    param =&amp;gt; this.UpdateDataSource(),&lt;br /&gt;                    param =&amp;gt; this.CanUpdateDataSource&lt;br /&gt;                    );&lt;br /&gt;            }&lt;br /&gt;            return _updateDataSourceCommand;&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public void UpdateDataSource()&lt;br /&gt;    {&lt;br /&gt;        FileInfo file = new FileInfo(@"C:\Users\shujaat\Desktop\s.txt");&lt;br /&gt;        using (FileStream stream = file.OpenWrite())&lt;br /&gt;        {&lt;br /&gt;            using (StreamWriter writer = new StreamWriter(stream) { AutoFlush = true })&lt;br /&gt;            {&lt;br /&gt;                writer.Write(MessageToDataSource);&lt;br /&gt;                writer.Close();&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    bool CanUpdateDataSource&lt;br /&gt;    {&lt;br /&gt;        get { return true; }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    #endregion Commands&lt;br /&gt;}&lt;/pre&gt;In the constructor, like in the previous example, it is reading the contents of a text file and adding it to the cache. Additionally, it is creating a &lt;i&gt;HostFileChangeMonitor&lt;/i&gt; and adds it the &lt;i&gt;CacheItemPolicy&lt;/i&gt;'s list of &lt;i&gt;ChangeMonitors&lt;/i&gt;. This policy is being used for keeping a watch on the contents of the files specified by the &lt;i&gt;ChangeMonitors&lt;/i&gt;. If there is an update, it executes the callback as specified by the &lt;i&gt;ChangeMonitor&lt;/i&gt;. &lt;i&gt;HostFileChangeMonitor&lt;/i&gt; is a descendent of &lt;i&gt;ChangeMonitor&lt;/i&gt; through &lt;i&gt;FileChangeMonitor&lt;/i&gt;. In non ASP.net applications, it uses internally &lt;a href="http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx"&gt;FileSystemWatcher&lt;/a&gt; to monitor files. It must be remembered that it does not support relative paths.&lt;br /&gt;&lt;br /&gt;As expected by the view, it has two string properties &lt;i&gt;FileContents&lt;/i&gt; and &lt;i&gt;MessageToDataSource&lt;/i&gt;. It also has a &lt;i&gt;RelayCommand&lt;/i&gt; object &lt;i&gt;UpdateDataSourceCommand&lt;/i&gt;. This command is executed when user clicks &lt;i&gt;Update Data Source&lt;/i&gt; button. In the execute method &lt;i&gt;[UpdateDataSource]&lt;/i&gt; of this command, we are just updating the contents of the file using &lt;i&gt;StreamWriter&lt;/i&gt;.&lt;br /&gt;&lt;br /&gt;The soul of this example is &lt;i&gt;OnDataSourceUpdated&lt;/i&gt; method specified as the callback for change notification in the monitored data sources by &lt;i&gt;HostFileChangeMonitor&lt;/i&gt;. When the contents of the file are updated, this method gets called. In this method we are updating the &lt;i&gt;Cache Entry&lt;/i&gt; and the string property bound to the text block in the view showing the contents of the file. &lt;br /&gt;&lt;br /&gt;Now specify the new view as startup view of the project in App.xaml and run the application. The view appears as follows:&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://4.bp.blogspot.com/-Gh5PbP8Imhs/TYGCKgJSvII/AAAAAAAAA9M/Tor_ff7QJwQ/s1600/6.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="267" width="400" src="http://4.bp.blogspot.com/-Gh5PbP8Imhs/TYGCKgJSvII/AAAAAAAAA9M/Tor_ff7QJwQ/s400/6.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;Now let us update the contents of the &lt;i&gt;TextBox&lt;/i&gt; and click &lt;i&gt;"Update Data Source"&lt;/i&gt; button. As the contents of the file are updated, the callback is called by the &lt;i&gt;ChangeMonitor&lt;/i&gt; which updates the cache entry and the &lt;i&gt;FileContent&lt;/i&gt; property with updated contents of the file. Since this is bound to a &lt;i&gt;TextBlock.TextProperty&lt;/i&gt; in the view, the view shows this update.&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://1.bp.blogspot.com/-E_nqA1ERoQM/TYGZz4zqyHI/AAAAAAAAA9U/4YwBmQPmpTI/s1600/7.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="267" width="400" src="http://1.bp.blogspot.com/-E_nqA1ERoQM/TYGZz4zqyHI/AAAAAAAAA9U/4YwBmQPmpTI/s400/7.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;Now we open the child window using &lt;i&gt;"Open Child Window"&lt;/i&gt; button. The child window uses the same cache entry. The child window appears as follows:&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://1.bp.blogspot.com/-1KgJn6yqnSg/TYGatxU-R5I/AAAAAAAAA9c/zkbdxZxt4J8/s1600/8.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="178" width="400" src="http://1.bp.blogspot.com/-1KgJn6yqnSg/TYGatxU-R5I/AAAAAAAAA9c/zkbdxZxt4J8/s400/8.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;Now update the contents of file again by updating the contents of the &lt;i&gt;TextBox&lt;/i&gt; and hitting &lt;i&gt;"Update Data Source"&lt;/i&gt; button. This should be done when the &lt;i&gt;ChildWindow&lt;/i&gt; is still shown. We are updating the contents with one of &lt;i&gt;Jalal Uddin Rumi&lt;/i&gt;'s great quote.&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://3.bp.blogspot.com/-VCrnLK8WXaA/TYGdL8Q8aGI/AAAAAAAAA9k/G_LiKBMx818/s1600/9.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="175" width="400" src="http://3.bp.blogspot.com/-VCrnLK8WXaA/TYGdL8Q8aGI/AAAAAAAAA9k/G_LiKBMx818/s400/9.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;u&gt;Cache Entry Change Monitor:&lt;/u&gt;&lt;br /&gt;&lt;br /&gt;As you can see that clicking Update Source button after updating the contents of the &lt;i&gt;TextBox&lt;/i&gt; updates the &lt;i&gt;TextBlock&lt;/i&gt; on the main window but it does not appear to update the contents of second window. This is because the &lt;i&gt;ChildWindow&lt;/i&gt; does not know that the cache entry value it used for its &lt;i&gt;TextBlock&lt;/i&gt;  has been updated. If &lt;i&gt;ChildWindow&lt;/i&gt; has some means to get notification for this cache entry update then it could update its logic. For this purpose we can use another &lt;i&gt;ChangeMonitor&lt;/i&gt;, called &lt;i&gt;CacheEntryChangeMonitor&lt;/i&gt;. &lt;br /&gt;&lt;br /&gt;Let's update the constructor of &lt;i&gt;ChildWindowViewModel&lt;/i&gt; as follows:&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;public ChildWindowViewModel()&lt;br /&gt;{&lt;br /&gt;    CacheEntryValue = MemoryCache.Default["filecontents"] as string;&lt;br /&gt;    MemoryCache.Default.CreateCacheEntryChangeMonitor(&lt;br /&gt;        new string[] { "filecontents" }.AsEnumerable&amp;lt;string&amp;gt;()).NotifyOnChanged((a) =&amp;gt;&lt;br /&gt;        {&lt;br /&gt;            CacheEntryValue = MemoryCache.Default["filecontents"] as string;&lt;br /&gt;        }&lt;br /&gt;    );&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;Here we have just added an instane &lt;i&gt;CacheEntryChangeMonitor&lt;/i&gt; to the code. Again we are using the same cache entry but the only difference we have added a NotifyOnChanged callback for this. As the entry gets updated this callback is called and it updates the property bound to the TextBlock.Text property in the view refreshing this.&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/-yhB3Kbb3cHc/TYGg8v48UWI/AAAAAAAAA9s/1FFmy6zD-fg/s1600/10.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="171" width="400" src="http://2.bp.blogspot.com/-yhB3Kbb3cHc/TYGg8v48UWI/AAAAAAAAA9s/1FFmy6zD-fg/s400/10.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;b&gt;Download Code:&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;&lt;iframe title ="Preview" scrolling="no" marginheight="0" marginwidth="0" frameborder="0" style="width:98px;height:115px;padding:0;background-color:#fcfcfc;" src="http://cid-b5fee7d7acde5072.office.live.com/embedicon.aspx/WPF%20Caching/WpfApp^_MVVM^_Caching.zip"&gt;&lt;/iframe&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8085117242240449595-8526381864817717407?l=www.shujaat.net' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.shujaat.net/feeds/8526381864817717407/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8085117242240449595&amp;postID=8526381864817717407&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/8526381864817717407'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/8526381864817717407'/><link rel='alternate' type='text/html' href='http://www.shujaat.net/2011/03/wpf-performance-improvement-for-mvvm.html' title='WPF - Performance Improvement for MVVM Based Applications - Part # 3'/><author><name>Muhammad Shujaat Siddiqi</name><uri>http://www.blogger.com/profile/02519138704633566929</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://2.bp.blogspot.com/-nENeXTwWP-E/TXhOTh3RSmI/AAAAAAAAA8k/hSTin9NqIYY/s72-c/1.jpg' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8085117242240449595.post-1064024948082765762</id><published>2011-03-05T17:31:00.011-06:00</published><updated>2011-03-09T22:19:02.104-06:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='MVVM'/><category scheme='http://www.blogger.com/atom/ns#' term='Command RoutedCommand'/><category scheme='http://www.blogger.com/atom/ns#' term='wpf 4'/><category scheme='http://www.blogger.com/atom/ns#' term='wpf'/><category scheme='http://www.blogger.com/atom/ns#' term='Relay Command'/><category scheme='http://www.blogger.com/atom/ns#' term='.net 4.0'/><category scheme='http://www.blogger.com/atom/ns#' term='Input Binding'/><title type='text'>WPF - Binding InputBindings to View Model Commands using MVVM</title><content type='html'>In this post we will be discussing about how we can bind mouse and key gestures directly with Commands in the view model. Generally when we talk about this type of binding we end up using &lt;i&gt;RoutedCommand&lt;/i&gt; directly in the view having &lt;i&gt;Execute&lt;/i&gt; and &lt;i&gt;CanExecute&lt;/i&gt; methods in the view itself. This is a new feature of WPF 4.&lt;br /&gt;&lt;br /&gt;In order to understand this, let's consider a sample application with some input bindings. When the particular key combination are received by WPF runtime, it should update properties in view model. These properties supports change notifications by implementing &lt;i&gt;INotifyPropertyChanged&lt;/i&gt; interface.&lt;br /&gt;&lt;pre class="brush: xml; gutter: false;"&gt;&amp;lt;Window x:Class="WpfApplication_InputBindings_MVVM.MainWindow"&lt;br /&gt;        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"&lt;br /&gt;        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&lt;br /&gt;        xmlns:local="clr-namespace:WpfApplication_InputBindings_MVVM"&lt;br /&gt;        Title="MainWindow" Height="350" Width="525"&amp;gt;&lt;br /&gt;    &amp;lt;Window.DataContext&amp;gt;&lt;br /&gt;        &amp;lt;local:MainWindowViewModel /&amp;gt;&lt;br /&gt;    &amp;lt;/Window.DataContext&amp;gt;&lt;br /&gt;    &amp;lt;Window.InputBindings&amp;gt;&lt;br /&gt;        &amp;lt;KeyBinding Key="F2" Modifiers="Control" Command="{Binding OperationCommand}" /&amp;gt;&lt;br /&gt;    &amp;lt;/Window.InputBindings&amp;gt;    &lt;br /&gt;    &amp;lt;Grid&amp;gt;&lt;br /&gt;        &amp;lt;Label Content="Message" Height="26" HorizontalAlignment="Left" Margin="12,47,0,0" &lt;br /&gt;               Name="label1" VerticalAlignment="Top" Width="67" FontWeight="Bold" /&amp;gt;&lt;br /&gt;        &amp;lt;TextBlock Height="27" HorizontalAlignment="Left" Margin="86,53,0,0" &lt;br /&gt;                   Name="textBlockMessage" Text="{Binding Message}" VerticalAlignment="Top" Width="405" /&amp;gt;&lt;br /&gt;    &amp;lt;/Grid&amp;gt;&lt;br /&gt;&amp;lt;/Window&amp;gt;&lt;br /&gt;&lt;/pre&gt;In the above view we have added KeyBinding for "Ctrl + F2" key combination. The view model should have a command &lt;i&gt;OperationCommand&lt;/i&gt;. When user presses the specified key combination, it should execute the command methods on the view model. The view is using a new instance of &lt;i&gt;MainWindowViewModel&lt;/i&gt; as its &lt;i&gt;DataContext&lt;/i&gt;. It is also binding Text property of the only TextBlock to a property Message from the &lt;i&gt;DataContext&lt;/i&gt;.&lt;br /&gt;&lt;br /&gt;Let's look at the definition of &lt;i&gt;MainWindowViewModel&lt;/i&gt;. Since it needs to support Property change notification to the view, it is using one of the available change notification system. It is using this mechanism for its &lt;i&gt;Message&lt;/i&gt; property. As part of its contract for &lt;i&gt;INotifyPropertyChanged&lt;/i&gt;, it provides an event &lt;i&gt;PropertyChanged&lt;/i&gt;. We have used RelayCommand for supporting command execution from view model [&lt;a href="http://msdn.microsoft.com/en-us/magazine/dd419663.aspx"&gt;http://msdn.microsoft.com/en-us/magazine/dd419663.aspx&lt;/a&gt;]. &lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;class MainWindowViewModel : INotifyPropertyChanged&lt;br /&gt;{&lt;br /&gt;    #region Operation Command&lt;br /&gt;    &lt;br /&gt;    RelayCommand _operationCommand;&lt;br /&gt;    public ICommand OperationCommand&lt;br /&gt;    {&lt;br /&gt;        get&lt;br /&gt;        {&lt;br /&gt;            if (_operationCommand == null)&lt;br /&gt;            {&lt;br /&gt;                _operationCommand = new RelayCommand(param =&amp;gt; this.ExecuteCommand(),&lt;br /&gt;                    param =&amp;gt; this.CanExecuteCommand);&lt;br /&gt;            }&lt;br /&gt;            return _operationCommand;&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public void ExecuteCommand()&lt;br /&gt;    {&lt;br /&gt;        Message = "Command Executed";&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    bool CanExecuteCommand&lt;br /&gt;    {&lt;br /&gt;        get { return true; }&lt;br /&gt;    }&lt;br /&gt;    &lt;br /&gt;    #endregion Operation Command&lt;br /&gt;&lt;br /&gt;    #region Properties&lt;br /&gt;&lt;br /&gt;    private string _message;&lt;br /&gt;    public string Message&lt;br /&gt;    {&lt;br /&gt;        get { return _message; }&lt;br /&gt;        set&lt;br /&gt;        {&lt;br /&gt;            _message = value;&lt;br /&gt;            OnPropertyChanged("Message");&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    #endregion Properties&lt;br /&gt;&lt;br /&gt;    #region INotifyPropertyChanged implementation&lt;br /&gt;&lt;br /&gt;    public event PropertyChangedEventHandler PropertyChanged = delegate { };&lt;br /&gt;    private void OnPropertyChanged(string propertyName)&lt;br /&gt;    {&lt;br /&gt;        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    #endregion INotifyPropertyChanged implementation&lt;br /&gt;}&lt;/pre&gt;When we run the application and hit the specified key combination, it first checks if the command is eligible for execution from &lt;i&gt;CanExecuteCommand&lt;/i&gt; property. If it returns true then it executes &lt;i&gt;ExecuteCommand&lt;/i&gt; method. In this method we are setting Message property to &lt;i&gt;"Command Executed"&lt;/i&gt;. Since this property supports change notification so the same changes are updated on the view.&lt;br /&gt;&lt;br /&gt;Let us run this now. The application is displayed as follows:&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://1.bp.blogspot.com/-V-3e3wpUfBE/TXLGiuXWElI/AAAAAAAAA8E/NEOsfaHbsJg/s1600/1.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="267" width="400" src="http://1.bp.blogspot.com/-V-3e3wpUfBE/TXLGiuXWElI/AAAAAAAAA8E/NEOsfaHbsJg/s400/1.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;As expected, When we press Ctrl + F2 key combination the view is updated as follows:&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/-Mp50BDGHCqs/TXLGiwbenNI/AAAAAAAAA8M/LEuoT1-mF3c/s1600/2.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="267" width="400" src="http://2.bp.blogspot.com/-Mp50BDGHCqs/TXLGiwbenNI/AAAAAAAAA8M/LEuoT1-mF3c/s400/2.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;b&gt;Stealing Key Gestures from Application Commands:&lt;/b&gt;&lt;br /&gt;Still we have simple command bound to the Window. What if we have a command with key gestures from default Commands available by the framework including &lt;i&gt;ApplicationCommands&lt;/i&gt;? Now let's progress this example into a little complex one. Let's change the input bindings to a key gestures &lt;i&gt;Ctrl + V&lt;/i&gt;. &lt;br /&gt;&lt;pre class="brush: xml; gutter: false;"&gt;&amp;lt;Window x:Class="WpfApplication_InputBindings_MVVM.MainWindow"&lt;br /&gt;        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"&lt;br /&gt;        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&lt;br /&gt;        xmlns:local="clr-namespace:WpfApplication_InputBindings_MVVM"&lt;br /&gt;        Title="MainWindow" Height="350" Width="525"&amp;gt;&lt;br /&gt;    &amp;lt;Window.DataContext&amp;gt;&lt;br /&gt;        &amp;lt;local:MainWindowViewModel /&amp;gt;&lt;br /&gt;    &amp;lt;/Window.DataContext&amp;gt;&lt;br /&gt;    &amp;lt;Window.InputBindings&amp;gt;&lt;br /&gt;        &amp;lt;KeyBinding Key="V" Modifiers="Control" Command="{Binding OperationCommand}" /&amp;gt;&lt;br /&gt;    &amp;lt;/Window.InputBindings&amp;gt;    &lt;br /&gt;    &amp;lt;Grid&amp;gt;&lt;br /&gt;        &amp;lt;Label Content="Message" Height="26" HorizontalAlignment="Left" Margin="12,47,0,0" &lt;br /&gt;               Name="label1" VerticalAlignment="Top" Width="67" FontWeight="Bold" /&amp;gt;&lt;br /&gt;        &amp;lt;TextBlock Height="27" HorizontalAlignment="Left" Margin="86,53,0,0" &lt;br /&gt;                   Name="textBlockMessage" Text="{Binding Message}" VerticalAlignment="Top" Width="405" /&amp;gt;&lt;br /&gt;        &amp;lt;TextBox Height="29" HorizontalAlignment="Left" Margin="82,152,0,0" Name="textBox1" &lt;br /&gt;                 VerticalAlignment="Top" Width="409" /&amp;gt;&lt;br /&gt;    &amp;lt;/Grid&amp;gt;&lt;br /&gt;&amp;lt;/Window&amp;gt;&lt;/pre&gt;In the above XAML, we have updated the key gestures to &lt;i&gt;Ctrl + V&lt;/i&gt;. We move focus to the new &lt;i&gt;TextBox&lt;/i&gt; and hit &lt;i&gt;Ctrl + V&lt;/i&gt; [I have text "Muhammad Siddiqi" copied to clip board].&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://1.bp.blogspot.com/-wL51gocOJzY/TXcZnIWjVWI/AAAAAAAAA8U/y_TioLaMA2M/s1600/3.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="267" width="400" src="http://1.bp.blogspot.com/-wL51gocOJzY/TXcZnIWjVWI/AAAAAAAAA8U/y_TioLaMA2M/s400/3.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;You can see that &lt;i&gt;TextBox&lt;/i&gt; has stolen the key gestures. This has resulted in the text on the clip board being pasted to the Text Box. This is because of default paste command using this key gesture for the text box.&lt;br /&gt;&lt;br /&gt;&lt;u&gt;Binding Key Gesture of un-wanted command to ApplicationCommands.NotACommand:&lt;/u&gt;&lt;br /&gt;The first solution is very simple. We can just assign those key gestures to &lt;i&gt;ApplicationCommands.NotACommand&lt;/i&gt;. We can achieve the same using &lt;i&gt;CommandManager&lt;/i&gt; available in &lt;i&gt;System.Windows.Input&lt;/i&gt; namespace. Let's update the constructor of the view as follows:&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;public MainWindow()&lt;br /&gt;{&lt;br /&gt;    InitializeComponent();&lt;br /&gt;&lt;br /&gt;    CommandManager.RegisterClassInputBinding(typeof(UIElement),&lt;br /&gt;        new InputBinding(ApplicationCommands.NotACommand, &lt;br /&gt;            new KeyGesture(Key.V, ModifierKeys.Control)));&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;Now let's run the application again. When we hit &lt;i&gt;Ctrl + V&lt;/i&gt; the command actually executes and key gestures are not stolen by &lt;i&gt;Paste Command&lt;/i&gt; for the text box.&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://3.bp.blogspot.com/-hHm04_F6D8E/TXcnjNxZi_I/AAAAAAAAA8c/DBGeQAKwxHw/s1600/4.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="267" width="400" src="http://3.bp.blogspot.com/-hHm04_F6D8E/TXcnjNxZi_I/AAAAAAAAA8c/DBGeQAKwxHw/s400/4.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;This approach seems to be working but it has a few limitations. First this is application wide i.e. this gesture is stolen for the whole application. The other thing is that we can not un-register this. &lt;br /&gt;&lt;br /&gt;&lt;i&gt;Vote:&lt;/i&gt; &lt;a href="http://connect.microsoft.com/VisualStudio/feedback/details/481627/no-way-to-unregister-a-commandmanager-registerclasscommandbinding"&gt;http://connect.microsoft.com/VisualStudio/feedback/details/481627/no-way-to-unregister-a-commandmanager-registerclasscommandbinding&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;u&gt;Handling CanExecute Tunneling Event&lt;/u&gt;:&lt;br /&gt;The other solution is to handle PreviewCanExecute event of the command causing the key gesture conflict. In the following example we are using CommandBinding to provide tunneling event handler for CanExecute for Paste Command. Since CommandBindings, unlike InputBindings, is a DependencyProperty if this command is handled above in the logical hierarchy this wouldn't be propagating down. Let's update XAML as follows:&lt;br /&gt;&lt;pre class="brush: xml; gutter: false;"&gt;&amp;lt;Window x:Class="WpfApplication_InputBindings_MVVM.MainWindow"&lt;br /&gt;        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"&lt;br /&gt;        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&lt;br /&gt;        xmlns:local="clr-namespace:WpfApplication_InputBindings_MVVM"&lt;br /&gt;        Title="MainWindow" Height="350" Width="525"&amp;gt;&lt;br /&gt;    &amp;lt;Window.DataContext&amp;gt;&lt;br /&gt;        &amp;lt;local:MainWindowViewModel /&amp;gt;&lt;br /&gt;    &amp;lt;/Window.DataContext&amp;gt;&lt;br /&gt;    &amp;lt;Window.InputBindings&amp;gt;&lt;br /&gt;        &amp;lt;KeyBinding Key="V" Modifiers="Control" Command="{Binding OperationCommand}" /&amp;gt;&lt;br /&gt;    &amp;lt;/Window.InputBindings&amp;gt;    &lt;br /&gt;    &amp;lt;Window.CommandBindings&amp;gt;&lt;br /&gt;        &amp;lt;CommandBinding Command="Paste" PreviewCanExecute="CommandBinding_PreviewCanExecute" /&amp;gt;&lt;br /&gt;    &amp;lt;/Window.CommandBindings&amp;gt;&lt;br /&gt;    &amp;lt;Grid&amp;gt;&lt;br /&gt;        &amp;lt;Label Content="Message" Height="26" HorizontalAlignment="Left" Margin="12,47,0,0" &lt;br /&gt;               Name="label1" VerticalAlignment="Top" Width="67" FontWeight="Bold" /&amp;gt;&lt;br /&gt;        &amp;lt;TextBlock Height="27" HorizontalAlignment="Left" Margin="86,53,0,0" &lt;br /&gt;                   Name="textBlockMessage" Text="{Binding Message}" VerticalAlignment="Top" Width="405" /&amp;gt;&lt;br /&gt;        &amp;lt;TextBox Height="29" HorizontalAlignment="Left" Margin="82,152,0,0" Name="textBox1" &lt;br /&gt;                 VerticalAlignment="Top" Width="409" /&amp;gt;&lt;br /&gt;    &amp;lt;/Grid&amp;gt;&lt;br /&gt;&amp;lt;/Window&amp;gt;&lt;/pre&gt;Let's see the definition of &lt;i&gt;CommandBinding_PreviewCanExecute&lt;/i&gt;:&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;private void CommandBinding_PreviewCanExecute(object sender, CanExecuteRoutedEventArgs e)&lt;br /&gt;{&lt;br /&gt;    e.Handled = true;&lt;br /&gt;}&lt;/pre&gt;If we run this now and hit &lt;i&gt;Ctrl + V&lt;/i&gt; by setting focus on the text box, this event handler is executed. Since this is handled here this would not be propagated to the text box. The view is updated as follows:&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://3.bp.blogspot.com/-hHm04_F6D8E/TXcnjNxZi_I/AAAAAAAAA8c/DBGeQAKwxHw/s1600/4.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="267" width="400" src="http://3.bp.blogspot.com/-hHm04_F6D8E/TXcnjNxZi_I/AAAAAAAAA8c/DBGeQAKwxHw/s400/4.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;b&gt;Download Code:&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;&lt;iframe title ="Preview" scrolling="no" marginheight="0" marginwidth="0" frameborder="0" style="width:98px;height:115px;padding:0;background-color:#fcfcfc;" src="http://cid-b5fee7d7acde5072.office.live.com/embedicon.aspx/MVVM%20Input%20Bindings/WpfApplication^_InputBindings^_MVVM.zip"&gt;&lt;/iframe&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8085117242240449595-1064024948082765762?l=www.shujaat.net' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.shujaat.net/feeds/1064024948082765762/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8085117242240449595&amp;postID=1064024948082765762&amp;isPopup=true' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/1064024948082765762'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/1064024948082765762'/><link rel='alternate' type='text/html' href='http://www.shujaat.net/2011/03/wpf-binding-inputbindings-to-view-model.html' title='WPF - Binding InputBindings to View Model Commands using MVVM'/><author><name>Muhammad Shujaat Siddiqi</name><uri>http://www.blogger.com/profile/02519138704633566929</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://1.bp.blogspot.com/-V-3e3wpUfBE/TXLGiuXWElI/AAAAAAAAA8E/NEOsfaHbsJg/s72-c/1.jpg' height='72' width='72'/><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8085117242240449595.post-1822676335772449485</id><published>2011-03-02T00:57:00.002-06:00</published><updated>2011-03-02T01:07:33.689-06:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='OnCompleted'/><category scheme='http://www.blogger.com/atom/ns#' term='ThreadPool'/><category scheme='http://www.blogger.com/atom/ns#' term='Subscribe'/><category scheme='http://www.blogger.com/atom/ns#' term='.net'/><category scheme='http://www.blogger.com/atom/ns#' term='asynch wpf'/><category scheme='http://www.blogger.com/atom/ns#' term='OnNext'/><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><category scheme='http://www.blogger.com/atom/ns#' term='OnError'/><category scheme='http://www.blogger.com/atom/ns#' term='Observable.ToAsync'/><category scheme='http://www.blogger.com/atom/ns#' term='wpf'/><category scheme='http://www.blogger.com/atom/ns#' term='Observable.Start'/><category scheme='http://www.blogger.com/atom/ns#' term='Observable. Observable.ForkJoin'/><category scheme='http://www.blogger.com/atom/ns#' term='IObservable'/><title type='text'>Rx - Executing IObservable in Parallel in a WPF application</title><content type='html'>In this post we are going to take the asynchronous code execution using Reactive extension a bit further. We would see how we can have multiple &lt;i&gt;IObservable&lt;/i&gt; (s) are executed in parallel. Rx supports this using &lt;i&gt;Observable.ForkJoin&lt;/i&gt;. We can have code executed in parallel which doesn't return any data, return same or different data.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;It's not blocking rather still asynchronous:&lt;/b&gt;&lt;br /&gt;Let's create a simple view with a single message and a button. We need to execute the IObservable in parallel when button is clicked. &lt;br /&gt;&lt;pre class="brush: xml; gutter: false;"&gt;&amp;lt;Window x:Class="WpfApp_Reactive_ForkJoin.MainWindow"&lt;br /&gt;        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"&lt;br /&gt;        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&lt;br /&gt;        xmlns:local="clr-namespace:WpfApp_Reactive_ForkJoin"&lt;br /&gt;        Title="MainWindow" Height="350" Width="525"&amp;gt;&lt;br /&gt;    &amp;lt;Window.DataContext&amp;gt;&lt;br /&gt;        &amp;lt;local:MainWindowViewModel /&amp;gt;&lt;br /&gt;    &amp;lt;/Window.DataContext&amp;gt;&lt;br /&gt;    &amp;lt;Grid&amp;gt;&lt;br /&gt;        &amp;lt;TextBlock Height="47" HorizontalAlignment="Left" Margin="70,63,0,0" &lt;br /&gt;                   Name="textBlock1" Text="{Binding Message}" VerticalAlignment="Top" Width="384" /&amp;gt;&lt;br /&gt;        &amp;lt;Button Content="Start Operations" Height="38" HorizontalAlignment="Left" Margin="68,134,0,0"&lt;br /&gt;                Name="btnStartOperations" VerticalAlignment="Top" Width="143" &lt;br /&gt;                Command="{Binding OperationCommand}"/&amp;gt;&lt;br /&gt;    &amp;lt;/Grid&amp;gt;&lt;br /&gt;&amp;lt;/Window&amp;gt;&lt;/pre&gt;The view is assigning an instance of &lt;i&gt;MainWindowViewModel&lt;/i&gt; as the &lt;i&gt;DataContext&lt;/i&gt; of the Window. The view expects Message property from the view model to bind it to the &lt;i&gt;Text&lt;/i&gt; property of the &lt;i&gt;TextBlock&lt;/i&gt;. It also expects an ICommand &lt;i&gt;OperationCommand&lt;/i&gt; in the view model. We are implementing &lt;i&gt;INotifyPropertyChanged&lt;/i&gt; so we need to provide &lt;i&gt;PropertyChanged&lt;/i&gt; event in this view model. It has &lt;i&gt;Message&lt;/i&gt; property which is bound to the Text property of the &lt;i&gt;TextBlock&lt;/i&gt; in the view.&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;class MainWindowViewModel : INotifyPropertyChanged&lt;br /&gt;{&lt;br /&gt;    #region Constructor&lt;br /&gt;    public MainWindowViewModel()&lt;br /&gt;    {&lt;br /&gt;&lt;br /&gt;    }&lt;br /&gt;    #endregion Constructor&lt;br /&gt;&lt;br /&gt;    #region Public Properties&lt;br /&gt;&lt;br /&gt;    string _message = "Operation not started yet...";&lt;br /&gt;    public string Message&lt;br /&gt;    {&lt;br /&gt;        get { return _message; }&lt;br /&gt;        set&lt;br /&gt;        {&lt;br /&gt;            _message = value;&lt;br /&gt;            OnPropertyChanged("Message");&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    #endregion Properties&lt;br /&gt;&lt;br /&gt;    #region INotifyPropertyChanged implementation&lt;br /&gt;&lt;br /&gt;    public event PropertyChangedEventHandler PropertyChanged = delegate { };&lt;br /&gt;    private void OnPropertyChanged(string propertyName)&lt;br /&gt;    {&lt;br /&gt;        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    #endregion INotifyPropertyChanged implementation&lt;br /&gt;&lt;br /&gt;    #region Operation Command&lt;br /&gt;&lt;br /&gt;    RelayCommand _operationCommand;&lt;br /&gt;    public ICommand OperationCommand&lt;br /&gt;    {&lt;br /&gt;        get&lt;br /&gt;        {&lt;br /&gt;            if (_operationCommand == null)&lt;br /&gt;            {&lt;br /&gt;                _operationCommand = new RelayCommand(param =&amp;gt; this.StartOperation(),&lt;br /&gt;                    param =&amp;gt; this.CanStartOperation);&lt;br /&gt;            }&lt;br /&gt;            return _operationCommand;&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    bool CanStartOperation&lt;br /&gt;    {&lt;br /&gt;        get&lt;br /&gt;        {&lt;br /&gt;            return true;&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    [DebuggerHidden]&lt;br /&gt;    public void StartOperation()&lt;br /&gt;    {&lt;br /&gt;        Message = "Operation running";&lt;br /&gt;&lt;br /&gt;        Observable.ForkJoin(&lt;br /&gt;            Observable.Start(() =&amp;gt; { &lt;br /&gt;                                       Message = "In 1st Observable.Start";&lt;br /&gt;                                       Debug.WriteLine("Executing 1st on Thread: {0}", Thread.CurrentThread.ManagedThreadId);&lt;br /&gt;                                       Thread.Sleep(2000);&lt;br /&gt;                                   }),&lt;br /&gt;            Observable.Start(() =&amp;gt; { &lt;br /&gt;                                       Message = "In 2nd Observable.Start";&lt;br /&gt;                                       Debug.WriteLine("Executing 2nd on Thread: {0}", Thread.CurrentThread.ManagedThreadId);&lt;br /&gt;                                       Thread.Sleep(2000);&lt;br /&gt;                                   }),&lt;br /&gt;            Observable.Start(() =&amp;gt; { &lt;br /&gt;                                       Message = "In 3rd Observable.Start";&lt;br /&gt;                                       Debug.WriteLine("Executing 3rd on Thread: {0}", Thread.CurrentThread.ManagedThreadId);&lt;br /&gt;                                       Thread.Sleep(10000);&lt;br /&gt;                                       throw new System.Exception("exception");&lt;br /&gt;                                   })&lt;br /&gt;            )&lt;br /&gt;            .Subscribe(&lt;br /&gt;                        (result) =&amp;gt; { &lt;br /&gt;                                        Message = result.ToString();&lt;br /&gt;                                        Debug.WriteLine("OnNext: Executing 1st on Thread: {0}", Thread.CurrentThread.ManagedThreadId);&lt;br /&gt;                                        Thread.Sleep(2000); &lt;br /&gt;                                    },&lt;br /&gt;                        (ex) =&amp;gt; &lt;br /&gt;                                { &lt;br /&gt;                                    Message = ex.Message;&lt;br /&gt;                                    Debug.WriteLine("OnError: Executing 1st on Thread: {0}", Thread.CurrentThread.ManagedThreadId);&lt;br /&gt;                                    Thread.Sleep(2000); &lt;br /&gt;                                },&lt;br /&gt;                        () =&amp;gt; { &lt;br /&gt;                                Message = "Completed";&lt;br /&gt;                                Debug.WriteLine("Completed: Executing 1st on Thread: {0}", Thread.CurrentThread.ManagedThreadId);&lt;br /&gt;                                Thread.Sleep(2000);&lt;br /&gt;                              });            &lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    #endregion Operation Command&lt;br /&gt;}&lt;/pre&gt;You can see that we have used an instance of &lt;i&gt;RelayCommand&lt;/i&gt; for &lt;i&gt;OperationCommand&lt;/i&gt;. Yes, this is the same &lt;i&gt;RelayCommand&lt;/i&gt; which is from Josh Smith's MVVM article. Since we want the button always to be enabled so &lt;i&gt;CanStartOperation&lt;/i&gt; always returns true. We have used &lt;i&gt;StartOperation&lt;/i&gt; as Execute method for &lt;i&gt;OperationCommand&lt;/i&gt;.&lt;br /&gt;&lt;br /&gt;&lt;a href="http://msdn.microsoft.com/en-us/magazine/dd419663.aspx"&gt;http://msdn.microsoft.com/en-us/magazine/dd419663.aspx&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;The following marble diagram might be used to represent the behavior of Fork.Join when all asynchronous operations actually return data. All this data is combined to generate a single &lt;i&gt;OnNext&lt;/i&gt; with combined data. Since there is no exception so OnCompleted is generated when all data streams are completed.&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://4.bp.blogspot.com/-GuIbhTTM9oA/TWx1Fys23NI/AAAAAAAAA7c/1KvI0yhruuk/s1600/1.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="213" width="400" src="http://4.bp.blogspot.com/-GuIbhTTM9oA/TWx1Fys23NI/AAAAAAAAA7c/1KvI0yhruuk/s400/1.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;b&gt;Can Only Observable.Start be used?&lt;/b&gt;&lt;br /&gt;In the above example we have used &lt;i&gt;Observable.Start&lt;/i&gt;. We can use any IObservable no matter how it is created. We can even use &lt;i&gt;IObservable&lt;/i&gt; (s) resulting from &lt;i&gt;Observable.ToAsync&lt;/i&gt; from methods we want to execute asynchronously.&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;Observable.ForkJoin(&lt;br /&gt;    Observable.Start(() =&amp;gt; { &lt;br /&gt;                               Message = "In 1st Observable.Start";&lt;br /&gt;                               Debug.WriteLine("Executing 1st on Thread: {0}", Thread.CurrentThread.ManagedThreadId);&lt;br /&gt;                               Thread.Sleep(2000);&lt;br /&gt;                           }),&lt;br /&gt;    Observable.Start(() =&amp;gt; { &lt;br /&gt;                               Message = "In 2nd Observable.Start";&lt;br /&gt;                               Debug.WriteLine("Executing 2nd on Thread: {0}", Thread.CurrentThread.ManagedThreadId);&lt;br /&gt;                               Thread.Sleep(2000);&lt;br /&gt;                           }),&lt;br /&gt;    Observable.ToAsync(myMethod)()&lt;br /&gt;    )&lt;br /&gt;    .Subscribe(&lt;br /&gt;                (result) =&amp;gt; { &lt;br /&gt;                                Message = result.ToString();&lt;br /&gt;                                Debug.WriteLine("OnNext: Executing 1st on Thread: {0}", Thread.CurrentThread.ManagedThreadId);&lt;br /&gt;                                Thread.Sleep(2000); &lt;br /&gt;                            },&lt;br /&gt;                (ex) =&amp;gt; &lt;br /&gt;                        { &lt;br /&gt;                            Message = ex.Message;&lt;br /&gt;                            Debug.WriteLine("OnError: Executing 1st on Thread: {0}", Thread.CurrentThread.ManagedThreadId);&lt;br /&gt;                            Thread.Sleep(2000); &lt;br /&gt;                        },&lt;br /&gt;                () =&amp;gt; { &lt;br /&gt;                        Message = "Completed";&lt;br /&gt;                        Debug.WriteLine("Completed: Executing 1st on Thread: {0}", Thread.CurrentThread.ManagedThreadId);&lt;br /&gt;                        Thread.Sleep(2000);&lt;br /&gt;                      });            &lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;b&gt;Observable.ForkJoin and Exception Handling:&lt;/b&gt;&lt;br /&gt;If any of the &lt;i&gt;IObservable&lt;/i&gt; results in an exception the no OnNext message is generated from the resulting &lt;i&gt;IObservable&lt;/i&gt; but a single &lt;i&gt;OnError&lt;/i&gt; is generated. We can show this on a marble diagram as follows:&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://3.bp.blogspot.com/-AkV8dJ3VtA8/TWyEBCjg8uI/AAAAAAAAA7s/1IFbRzDjkSc/s1600/2.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="213" width="400" src="http://3.bp.blogspot.com/-AkV8dJ3VtA8/TWyEBCjg8uI/AAAAAAAAA7s/1IFbRzDjkSc/s400/2.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;b&gt;Operations returning different Data:&lt;/b&gt;&lt;br /&gt;For &lt;i&gt;Observable.ForkJoin&lt;/i&gt;, we can combine &lt;i&gt;IObservable&lt;/i&gt;(s) which return no data or same / different data. Yes, it is possible that we have IObservable resulting in different data. We can use a different Overload of &lt;i&gt;Observable.ForkJoin&lt;/i&gt; for this.&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;public void StartOperation()&lt;br /&gt;{&lt;br /&gt;    Observable.ForkJoin&amp;lt;int, string, string&amp;gt;(&lt;br /&gt;        Observable.Start&amp;lt;int&amp;gt;(() =&amp;gt;&lt;br /&gt;            {&lt;br /&gt;                Thread.Sleep(2000);&lt;br /&gt;                return 1;&lt;br /&gt;            }),&lt;br /&gt;        Observable.ToAsync&amp;lt;string&amp;gt;(myMethod)(),&lt;br /&gt;        (StudentId, StudentName) =&amp;gt; { return string.Format("Student- Id: {0}, Name: {1}", StudentId, StudentName); }&lt;br /&gt;    ).Subscribe(&lt;br /&gt;            (result) =&amp;gt; { Message = result; },&lt;br /&gt;            (ex) =&amp;gt; { Message = ex.Message; });&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;private string myMethod()&lt;br /&gt;{&lt;br /&gt;    Thread.Sleep(5000);&lt;br /&gt;    return "Muhammad";&lt;br /&gt;}&lt;/pre&gt;When we run the application and click StartOperation. After some delay(simulated operational delay in parallel streams using Thread.Sleep) the window is updated. We can also use IObservables directly created using Observable.Create() method&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;public void StartOperation()&lt;br /&gt;{&lt;br /&gt;    Observable.ForkJoin&amp;lt;int, string, string&amp;gt;(&lt;br /&gt;        Observable.Create&amp;lt;int&amp;gt;(&lt;br /&gt;            (o) =&amp;gt;&lt;br /&gt;            {&lt;br /&gt;                Thread.Sleep(2000);&lt;br /&gt;                o.OnNext(1);&lt;br /&gt;                o.OnCompleted();&lt;br /&gt;&lt;br /&gt;                return () =&amp;gt; { };&lt;br /&gt;            }),&lt;br /&gt;            Observable.CreateWithDisposable&amp;lt;string&amp;gt;(&lt;br /&gt;            (o) =&amp;gt;&lt;br /&gt;            {&lt;br /&gt;                Thread.Sleep(2000);&lt;br /&gt;                o.OnNext("Muhammad");&lt;br /&gt;                o.OnCompleted();&lt;br /&gt;&lt;br /&gt;                return Disposable.Empty;&lt;br /&gt;            }),&lt;br /&gt;            (StudentId, StudentName) =&amp;gt; { return string.Format("Student- Id: {0}, Name: {1}", StudentId, StudentName); }&lt;br /&gt;    ).Subscribe(&lt;br /&gt;            (result) =&amp;gt; { Message = result; },&lt;br /&gt;            (ex) =&amp;gt; { Message = ex.Message; });&lt;br /&gt;&lt;br /&gt;}&lt;/pre&gt;Let's run this. When we click the button the view updates as follows:&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/-UbcHvHqc6NM/TWz-lLLDJqI/AAAAAAAAA70/6RSnsmYXnRY/s1600/3.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="267" width="400" src="http://2.bp.blogspot.com/-UbcHvHqc6NM/TWz-lLLDJqI/AAAAAAAAA70/6RSnsmYXnRY/s400/3.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;b&gt;Many OnNext messages on Individual IObservable (s)&lt;/b&gt;&lt;br /&gt;&lt;i&gt;Observable.ForkJoin&lt;/i&gt; combines the last values of each Observable stream, combines them and generates &lt;i&gt;OnNext&lt;/i&gt; message on the resulting &lt;i&gt;IObservable&lt;/i&gt;.&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;public void StartOperation()&lt;br /&gt;{&lt;br /&gt;    Observable.ForkJoin&amp;lt;int, string, string&amp;gt;(&lt;br /&gt;        Observable.Create&amp;lt;int&amp;gt;(&lt;br /&gt;            (o) =&amp;gt;&lt;br /&gt;            {&lt;br /&gt;                Thread.Sleep(2000);&lt;br /&gt;                o.OnNext(1);&lt;br /&gt;                o.OnNext(2);&lt;br /&gt;                o.OnCompleted();&lt;br /&gt;&lt;br /&gt;                return () =&amp;gt; { };&lt;br /&gt;            }),&lt;br /&gt;            Observable.Create&amp;lt;string&amp;gt;(&lt;br /&gt;            (o) =&amp;gt;&lt;br /&gt;            {&lt;br /&gt;                Thread.Sleep(2000);&lt;br /&gt;                o.OnNext("Muhammad");&lt;br /&gt;                o.OnCompleted();&lt;br /&gt;&lt;br /&gt;                return () =&amp;gt; { };&lt;br /&gt;            }),&lt;br /&gt;            (StudentId, StudentName) =&amp;gt; { return string.Format("Student- Id: {0}, Name: {1}", StudentId, StudentName); }&lt;br /&gt;    ).Subscribe(&lt;br /&gt;            (result) =&amp;gt; { Message = result; },&lt;br /&gt;            (ex) =&amp;gt; { Message = ex.Message; });&lt;br /&gt;&lt;br /&gt;}&lt;/pre&gt;When we run this, the first IObservable places two OnNext with data 1 and 2 sequentially. The second IObservable results in data "Muhammad". Let's run this:&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://4.bp.blogspot.com/-JapbaBUJo-c/TW0D0ItgWvI/AAAAAAAAA78/lh48W3tTxwM/s1600/4.jpg" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="267" width="400" src="http://4.bp.blogspot.com/-JapbaBUJo-c/TW0D0ItgWvI/AAAAAAAAA78/lh48W3tTxwM/s400/4.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;It is because the third argument from this overload of &lt;i&gt;Observable.ForkJoin&lt;/i&gt; has been used as a selector function. It has combined &lt;i&gt;StudentId (int)&lt;/i&gt; and &lt;i&gt;StudentName (string)&lt;/i&gt; into a string and placed OnNext on the resulting &lt;i&gt;Observable.ForkJoin&lt;/i&gt; IObservable. When &lt;i&gt;OnNext&lt;/i&gt; is received from the resulting &lt;i&gt;IObservable&lt;/i&gt;, it has updated the &lt;i&gt;Message&lt;/i&gt; property with the same message. Since this is bound to the view using WPF Binding System, the view is updated with this message.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Cleanup after Parallel Operations:&lt;/b&gt;&lt;br /&gt;If we need to do some cleanup after these parallel operations are completed then we can do that in the Finally block executed after &lt;i&gt;IObservable&lt;/i&gt; from &lt;i&gt;Observable.ForkJoin&lt;/i&gt; finishes. As we know this gets executed no matter if these parallel operations were successful resulting in &lt;i&gt;OnCompleted&lt;/i&gt; or there was some exception from any of the operations. In the latter case this gets executed after &lt;i&gt;OnError&lt;/i&gt; is executed.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Observable.ForkJoin and Thread Management:&lt;/b&gt;&lt;br /&gt;All the &lt;i&gt;IObservable&lt;/i&gt; (s) in &lt;i&gt;ForkJoin&lt;/i&gt; would be executing on different ThreadPool threads. The resulting &lt;i&gt;IObservable&lt;/i&gt; would also be running on a TheredPool thread. Since ThreadPool threads might be recycled, it is possible that the same thread seems to be used for OnNext and OnCompleted as one of the threads used for executing one of the IObservable code. It must be remembered that &lt;i&gt;OnNext&lt;/i&gt;, &lt;i&gt;OnCompleted&lt;/i&gt; will always be executing on the same thread.&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;public void StartOperation()&lt;br /&gt;{&lt;br /&gt;    Message = "Operation running";&lt;br /&gt;&lt;br /&gt;    Observable.ForkJoin(&lt;br /&gt;        Observable.Start(() =&amp;gt;&lt;br /&gt;        {&lt;br /&gt;            Message = "In 1st Observable.Start";&lt;br /&gt;            Debug.WriteLine("Executing 1st on Thread: {0}, IsThreadPoolThread: {1} ", &lt;br /&gt;                Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);&lt;br /&gt;            Thread.Sleep(2000);&lt;br /&gt;        }),&lt;br /&gt;        Observable.Start(() =&amp;gt;&lt;br /&gt;        {&lt;br /&gt;            Message = "In 2nd Observable.Start";&lt;br /&gt;            Debug.WriteLine("Executing 2nd on Thread: {0}, IsThreadPoolThread: {1}",&lt;br /&gt;                Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);&lt;br /&gt;            Thread.Sleep(2000);&lt;br /&gt;        }),                &lt;br /&gt;        Observable.Start(() =&amp;gt; &lt;br /&gt;        { &lt;br /&gt;            Message = "In 3rd Observable.Start";&lt;br /&gt;            Debug.WriteLine("Executing 3rd on Thread: {0}, IsThreadPoolThread: {1}", &lt;br /&gt;                Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);&lt;br /&gt;            Thread.Sleep(2000);                                           &lt;br /&gt;        }))&lt;br /&gt;        .Subscribe(&lt;br /&gt;                    (result) =&amp;gt;&lt;br /&gt;                    {&lt;br /&gt;                        Message = result.ToString();&lt;br /&gt;                        Debug.WriteLine("OnNext: Executing on Thread: {0}, IsThreadPoolThread: {1}", &lt;br /&gt;                            Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);&lt;br /&gt;                        Thread.Sleep(2000);&lt;br /&gt;                    },&lt;br /&gt;                    (ex) =&amp;gt;&lt;br /&gt;                    {&lt;br /&gt;                        Message = ex.Message;&lt;br /&gt;                        Debug.WriteLine("OnError: Executing on Thread: {0}, IsThreadPoolThread: {1}", &lt;br /&gt;                            Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);&lt;br /&gt;                        Thread.Sleep(2000);&lt;br /&gt;                    },&lt;br /&gt;                    () =&amp;gt;&lt;br /&gt;                    {&lt;br /&gt;                        Message = "Completed";&lt;br /&gt;                        Debug.WriteLine("Completed: Executing on Thread: {0}, IsThreadPoolThread: {1}", &lt;br /&gt;                            Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);&lt;br /&gt;                        Thread.Sleep(2000);&lt;br /&gt;                    });&lt;br /&gt;}&lt;/pre&gt;&lt;i&gt;&lt;br /&gt;Executing 1st on Thread: 3, IsThreadPoolThread: True &lt;br /&gt;Executing 2nd on Thread: 12, IsThreadPoolThread: True&lt;br /&gt;Executing 3rd on Thread: 11, IsThreadPoolThread: True&lt;br /&gt;OnNext: Executing on Thread: 11, IsThreadPoolThread: True&lt;br /&gt;Completed: Executing on Thread: 11, IsThreadPoolThread: True&lt;br /&gt;&lt;br /&gt;Executing 1st on Thread: 11, IsThreadPoolThread: True &lt;br /&gt;Executing 2nd on Thread: 10, IsThreadPoolThread: True&lt;br /&gt;Executing 3rd on Thread: 12, IsThreadPoolThread: True&lt;br /&gt;OnNext: Executing on Thread: 12, IsThreadPoolThread: True&lt;br /&gt;Completed: Executing on Thread: 12, IsThreadPoolThread: True&lt;br /&gt;&lt;br /&gt;Executing 1st on Thread: 11, IsThreadPoolThread: True &lt;br /&gt;Executing 2nd on Thread: 10, IsThreadPoolThread: True&lt;br /&gt;Executing 3rd on Thread: 12, IsThreadPoolThread: True&lt;br /&gt;OnNext: Executing on Thread: 3, IsThreadPoolThread: True&lt;br /&gt;Completed: Executing on Thread: 3, IsThreadPoolThread: True&lt;/i&gt;&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Download Code:&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;&lt;iframe title ="Preview" scrolling="no" marginheight="0" marginwidth="0" frameborder="0" style="width:98px;height:115px;padding:0;background-color:#fcfcfc;" src="http://cid-b5fee7d7acde5072.office.live.com/embedicon.aspx/Observable%20ForkJoin/WpfApp^_Reactive^_ForkJoin.zip"&gt;&lt;/iframe&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8085117242240449595-1822676335772449485?l=www.shujaat.net' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.shujaat.net/feeds/1822676335772449485/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8085117242240449595&amp;postID=1822676335772449485&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/1822676335772449485'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/1822676335772449485'/><link rel='alternate' type='text/html' href='http://www.shujaat.net/2011/03/rx-executing-iobservable-in-parallel-in.html' title='Rx - Executing IObservable in Parallel in a WPF application'/><author><name>Muhammad Shujaat Siddiqi</name><uri>http://www.blogger.com/profile/02519138704633566929</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://4.bp.blogspot.com/-GuIbhTTM9oA/TWx1Fys23NI/AAAAAAAAA7c/1KvI0yhruuk/s72-c/1.jpg' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8085117242240449595.post-7204436226642065447</id><published>2011-02-25T22:38:00.027-06:00</published><updated>2011-03-17T01:43:05.712-05:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='performance'/><category scheme='http://www.blogger.com/atom/ns#' term='MVVM'/><category scheme='http://www.blogger.com/atom/ns#' term='Lazy initialization'/><category scheme='http://www.blogger.com/atom/ns#' term='Lazy'/><category scheme='http://www.blogger.com/atom/ns#' term='functional'/><category scheme='http://www.blogger.com/atom/ns#' term='.net 4.0'/><category scheme='http://www.blogger.com/atom/ns#' term='asynch wpf'/><category scheme='http://www.blogger.com/atom/ns#' term='performance improvement'/><category scheme='http://www.blogger.com/atom/ns#' term='Func'/><title type='text'>WPF - Performance Improvement for MVVM Applications - Part # 2</title><content type='html'>This is the second part of our discussion about performance improvement of an &lt;span style="font-style:italic;"&gt;MVVM &lt;/span&gt;based application. You can find the other part of this discussion here:&lt;br /&gt;&lt;br /&gt;- Part - 1: &lt;a href="http://shujaatsiddiqi.blogspot.com/2011/01/wpf-performance-improvement-for-mvvm.html"&gt;http://shujaatsiddiqi.blogspot.com/2011/01/wpf-performance-improvement-for-mvvm.html&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;- Part - 3: &lt;a href="http://shujaatsiddiqi.blogspot.com/2011/03/wpf-performance-improvement-for-mvvm.html"&gt;http://shujaatsiddiqi.blogspot.com/2011/03/wpf-performance-improvement-for-mvvm.html&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;In this example we would see how we can utilize &lt;span style="font-style:italic;"&gt;Lazy Initialization&lt;/span&gt; to improve the performance of &lt;span style="font-style:italic;"&gt;MVVM &lt;/span&gt; based application. Lazy initialization is a newly available features of &lt;span style="font-style:italic;"&gt;.net framework 4.0&lt;/span&gt;. As I remember this is based on &lt;span style="font-style:italic;"&gt;Tomas Petricek&lt;/span&gt;'s suggestion which has been incorporated in .net framework recently. This is a part of effort to incorporate lazy execution in c# code. You might already know that LINQ queries support lazy evaulation already. They are only evaluated when the first time they are enumerated. If they are never enumerated then never such evaluation takes place. With new Lazy initialization feature, the framework now also supports&lt;span style="font-style:italic;"&gt; lazy initialization&lt;/span&gt;.&lt;br /&gt;&lt;br /&gt;&lt;a href="http://msdn.microsoft.com/en-us/vcsharp/bb870976"&gt;http://msdn.microsoft.com/en-us/vcsharp/bb870976&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;In this example we would base our discussion on a hierarchical view model. The main view is consisted of some collection based controls. Each of these control also needs to define its template to specify how different items in the collection would be displayed on the screen. &lt;br /&gt;&lt;br /&gt;Let's consider a view for a Course with just two students. The data of students should be displayed in tab items in a &lt;span style="font-style:italic;"&gt;TabControl&lt;/span&gt;. The student information should only have two fields, their first and last names. Student's First name should be displayed as header of its &lt;span style="font-style:italic;"&gt;TabItem&lt;/span&gt;. If the data is not entered yet then it should display &lt;span style="font-style:italic;"&gt;"Default"&lt;/span&gt; in the header. The XAML definition of the view is as follows:&lt;br /&gt;&lt;pre class="brush: xml; gutter: false;"&gt;&amp;lt;Window x:Class="WpfApp_MVVM_LazyInitialize.MainWindow"&lt;br /&gt;xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"&lt;br /&gt;xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&lt;br /&gt;xmlns:local="clr-namespace:WpfApp_MVVM_LazyInitialize"&lt;br /&gt;Title="MainWindow" Height="350" Width="525"&amp;gt;&lt;br /&gt;&amp;lt;Window.DataContext&amp;gt;&lt;br /&gt;&amp;lt;local:MainWindowViewModel /&amp;gt;&lt;br /&gt;&amp;lt;/Window.DataContext&amp;gt;&lt;br /&gt;&amp;lt;Grid&amp;gt;        &lt;br /&gt;&amp;lt;TabControl Height="288" HorizontalAlignment="Left" Margin="12,12,0,0" Name="tabControl1" VerticalAlignment="Top" Width="480"&lt;br /&gt;ItemsSource="{Binding StudentViewModels}" &amp;gt;&lt;br /&gt;&amp;lt;TabControl.ItemTemplate&amp;gt;&lt;br /&gt;&amp;lt;DataTemplate&amp;gt;&lt;br /&gt;&amp;lt;TextBlock Text="{Binding StudentFirstName}" /&amp;gt;&lt;br /&gt;&amp;lt;/DataTemplate&amp;gt;&lt;br /&gt;&amp;lt;/TabControl.ItemTemplate&amp;gt;&lt;br /&gt;&amp;lt;TabControl.ContentTemplate&amp;gt;                &lt;br /&gt;&amp;lt;DataTemplate&amp;gt;&lt;br /&gt;&amp;lt;Grid&amp;gt;&lt;br /&gt;&amp;lt;Label Content="First Name" Height="27" HorizontalAlignment="Left" &lt;br /&gt;Margin="12,29,0,0" Name="label1" VerticalAlignment="Top" Width="105" /&amp;gt;&lt;br /&gt;&amp;lt;TextBox Height="30" HorizontalAlignment="Left" Margin="123,29,0,0" &lt;br /&gt;Name="textBoxFirstName" VerticalAlignment="Top" Width="345" &lt;br /&gt;Text="{Binding Path=StudentFirstName}" /&amp;gt;&lt;br /&gt;&amp;lt;Label Content="Last Name" Height="27" HorizontalAlignment="Left" Margin="12,65,0,0" &lt;br /&gt;Name="label2" VerticalAlignment="Top" Width="105" /&amp;gt;&lt;br /&gt;&amp;lt;TextBox Height="30" HorizontalAlignment="Left" Margin="123,65,0,0" &lt;br /&gt;Name="textBoxLastName" VerticalAlignment="Top" Width="345" &lt;br /&gt;Text ="{Binding StudentLastName}" /&amp;gt;&lt;br /&gt;&amp;lt;/Grid&amp;gt;                    &lt;br /&gt;&amp;lt;/DataTemplate&amp;gt;&lt;br /&gt;&amp;lt;/TabControl.ContentTemplate&amp;gt;&lt;br /&gt;&amp;lt;/TabControl&amp;gt;&lt;br /&gt;&amp;lt;/Grid&amp;gt;&lt;br /&gt;&amp;lt;/Window&amp;gt;&lt;/pre&gt;&lt;br /&gt;We would be needing two DataTemplates for TabControl. One is for Header i.e. &lt;span style="font-style:italic;"&gt;ItemTemplate &lt;/span&gt;and the other is for the content of each TabItem i.e. &lt;span style="font-style:italic;"&gt;ContentTemplate&lt;/span&gt;. The &lt;span style="font-style:italic;"&gt;ItemsSource&lt;/span&gt; of this &lt;span style="font-style:italic;"&gt;TabControl &lt;/span&gt;is bound to &lt;span style="font-style:italic;"&gt;StudentViewModels&lt;/span&gt; collection. Each member of this collection should have atleast two properties &lt;span style="font-style:italic;"&gt;StudentFirstName&lt;/span&gt; and &lt;span style="font-style:italic;"&gt;StudentLastName&lt;/span&gt;. The ItemTemplate is just a &lt;span style="font-style:italic;"&gt;TextBlock&lt;/span&gt;. The &lt;span style="font-style:italic;"&gt;Text &lt;/span&gt;property of this &lt;span style="font-style:italic;"&gt;TextBlock&lt;/span&gt; is bound to item's &lt;span style="font-style:italic;"&gt;StudentFirstName &lt;/span&gt;property. The &lt;span style="font-style:italic;"&gt;ContentTemplate&lt;/span&gt; has two &lt;span style="font-style:italic;"&gt;TextBox&lt;/span&gt;(es). One of them is bound to &lt;span style="font-style:italic;"&gt;StudentFirstName &lt;/span&gt;and the other is  &lt;span style="font-style:italic;"&gt;StudentLastName &lt;/span&gt;properties. We have kept the code behind of the view as default.&lt;br /&gt;&lt;br /&gt;The DataContext of the above view is set as a new instance of &lt;span style="font-style:italic;"&gt;MainWindowViewModel&lt;/span&gt;. It implements &lt;span style="font-style:italic;"&gt;INotifyPropertyChanged&lt;/span&gt; so it needs to provide definition of &lt;span style="font-style:italic;"&gt;PropertyChanged &lt;/span&gt;event as part of its contract. As required by the view, it provides a collection &lt;span style="font-style:italic;"&gt;StudentViewModels&lt;/span&gt;. It is provided as an &lt;span style="font-style:italic;"&gt;ObservableCollection&lt;/span&gt;. Each member of this generic collection is specified as of the type &lt;span style="font-style:italic;"&gt;StudentViewModel&lt;/span&gt;.&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;class MainWindowViewModel : INotifyPropertyChanged&lt;br /&gt;{&lt;br /&gt;ObservableCollection&amp;lt;StudentViewModel&amp;gt; _studentViewModels = &lt;br /&gt;new ObservableCollection&amp;lt;StudentViewModel&amp;gt;();&lt;br /&gt;&lt;br /&gt;public ObservableCollection&amp;lt;StudentViewModel&amp;gt; StudentViewModels&lt;br /&gt;{&lt;br /&gt;get&lt;br /&gt;{&lt;br /&gt;return _studentViewModels;&lt;br /&gt;}&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public MainWindowViewModel()&lt;br /&gt;{&lt;br /&gt;_studentViewModels.Add(new StudentViewModel());&lt;br /&gt;_studentViewModels.Add(new StudentViewModel());&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public event PropertyChangedEventHandler PropertyChanged;&lt;br /&gt;private void OnPropertyChanged(string propertyName)&lt;br /&gt;{&lt;br /&gt;if (PropertyChanged != null)&lt;br /&gt;{&lt;br /&gt;PropertyChanged(this, new PropertyChangedEventArgs(propertyName));&lt;br /&gt;}&lt;br /&gt;}&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;In the constructor of the above view model we have added two members to the collection. As expected they are of type &lt;span style="font-style:italic;"&gt;StudentViewModel&lt;/span&gt;. They would be displayed as Tab items in the view. The definition of StudentViewModel is as follows:&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;class StudentViewModel : INotifyPropertyChanged&lt;br /&gt;{&lt;br /&gt;Lazy&amp;lt;Student&amp;gt; _model = new Lazy&amp;lt;Student&amp;gt;();&lt;br /&gt;&lt;br /&gt;string _studentFirstName;&lt;br /&gt;public string StudentFirstName&lt;br /&gt;{&lt;br /&gt;get { return _studentFirstName; }&lt;br /&gt;set&lt;br /&gt;{&lt;br /&gt;if (_studentFirstName != value)&lt;br /&gt;{&lt;br /&gt;_studentFirstName = value;&lt;br /&gt;_model.Value.StudentFirstName = value;&lt;br /&gt;OnPropertyChanged("StudentFirstName");&lt;br /&gt;}&lt;br /&gt;}&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;string _studentLastName;&lt;br /&gt;public string StudentLastName&lt;br /&gt;{&lt;br /&gt;get { return _studentLastName; }&lt;br /&gt;set&lt;br /&gt;{&lt;br /&gt;if (_studentLastName != value)&lt;br /&gt;{&lt;br /&gt;_studentLastName = value;&lt;br /&gt;_model.Value.StudentLastName = value;&lt;br /&gt;OnPropertyChanged("StudentLastName");&lt;br /&gt;}&lt;br /&gt;}&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public StudentViewModel()&lt;br /&gt;{&lt;br /&gt;_studentFirstName = "Default";&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public event PropertyChangedEventHandler PropertyChanged;&lt;br /&gt;private void OnPropertyChanged(string propertyName)&lt;br /&gt;{&lt;br /&gt;if (PropertyChanged != null)&lt;br /&gt;{&lt;br /&gt;PropertyChanged(this, new PropertyChangedEventArgs(propertyName));&lt;br /&gt;}&lt;br /&gt;}&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;As expected by the view it has two properties &lt;span style="font-style:italic;"&gt;StudentFirstName &lt;/span&gt;and &lt;span style="font-style:italic;"&gt;StudentLastName&lt;/span&gt;. It implements &lt;span style="font-style:italic;"&gt;INotifyPropertyChanged &lt;/span&gt;to support change notification. &lt;br /&gt;&lt;br /&gt;The above view model uses Student as model. When the view model receives updates in these properties through &lt;span style="font-style:italic;"&gt;WPF Biniding System&lt;/span&gt;, it just passes on those updates to the model. The instances initialized with Lazy initialization feature are accessed using Value property of the &lt;span style="font-style:italic;"&gt;Lazy &lt;/span&gt;object reference. We have accessed &lt;span style="font-style:italic;"&gt;StudentName &lt;/span&gt;and &lt;span style="font-style:italic;"&gt;StudentLastName &lt;/span&gt;properties using the same. Let us assume that it were a model which requires a heavy instantiation. We are just displaying a &lt;span style="font-style:italic;"&gt;MessageBox &lt;/span&gt;in the constructor. This would show a &lt;span style="font-style:italic;"&gt;MessageBox&lt;/span&gt; from the constructor. In this way we would realize exactly when the constructor is called. This is how are trying to understand Lazy initialization of &lt;span style="font-style:italic;"&gt;Student&lt;/span&gt;.&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;class Student&lt;br /&gt;{&lt;br /&gt;public string StudentFirstName { get; set; }&lt;br /&gt;public string StudentLastName { get; set; }&lt;br /&gt;&lt;br /&gt;public Student()&lt;br /&gt;{&lt;br /&gt;MessageBox.Show("Student constructor called");&lt;br /&gt;}&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;Now let us run this. The application is shown as follows:&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://1.bp.blogspot.com/-4u2DGIUBAXE/TWiFyVgVcJI/AAAAAAAAA7E/-n2ukrQ0Vfc/s1600/1.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 267px;" src="http://1.bp.blogspot.com/-4u2DGIUBAXE/TWiFyVgVcJI/AAAAAAAAA7E/-n2ukrQ0Vfc/s400/1.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5577855238311080082" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Enter some data in the &lt;span style="font-style:italic;"&gt;First Name&lt;/span&gt; field of the first Tab Item. As soon as the focus is changed to the other field, the default Binding of &lt;span style="font-style:italic;"&gt;Text &lt;/span&gt;property of &lt;span style="font-style:italic;"&gt;TextBox &lt;/span&gt;triggers the source updates on &lt;span style="font-style:italic;"&gt;LostFocus&lt;/span&gt;.&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://4.bp.blogspot.com/-USgmeJlfgdo/TWiGQ1OGaqI/AAAAAAAAA7M/v4AHGdlDGeE/s1600/2.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 267px;" src="http://4.bp.blogspot.com/-USgmeJlfgdo/TWiGQ1OGaqI/AAAAAAAAA7M/v4AHGdlDGeE/s400/2.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5577855762220608162" /&gt;&lt;/a&gt;&lt;br /&gt;When you close the message box you can see the header of the TabItem being updated with the &lt;span style="font-style:italic;"&gt;FirstName &lt;/span&gt;you entered.&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://3.bp.blogspot.com/-MjIMu5aY1Jo/TWiGRGIwZFI/AAAAAAAAA7U/XJ9RL9VvrBc/s1600/3.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 267px;" src="http://3.bp.blogspot.com/-MjIMu5aY1Jo/TWiGRGIwZFI/AAAAAAAAA7U/XJ9RL9VvrBc/s400/3.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5577855766761595986" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Deciding which Constructor to use for initialization:&lt;/span&gt;&lt;br /&gt;We can also decide which constructor of the type we want to use for initialization using the constructors of Lazy class. Lazy&amp;lt;T&amp;gt; allows Func&amp;lt;T&amp;gt; delegate as argument in some of its overloads.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;In a multithreaded scenario:&lt;/span&gt;&lt;br /&gt;In a multithreaded scenario the first thread using the lazy instance causes the initialization causes the initialization procedure and its value would be seen by the other threads. Although the other threads will also cause the initialization but their value will not be used. In a multithreaded scenario, like this, we can use any overload of &lt;span style="font-style:italic;"&gt;EnsureInitialized &lt;/span&gt;method of &lt;span style="font-style:italic;"&gt;Lazyintializer&lt;/span&gt; for even better performance. This can also use any of the default constructor or specialized constructor using &lt;span style="font-style:italic;"&gt;Func &lt;/span&gt;delegate.&lt;br /&gt;&lt;br /&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.threading.lazyinitializer.ensureinitialized.aspx"&gt;http://msdn.microsoft.com/en-us/library/system.threading.lazyinitializer.ensureinitialized.aspx&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Download Code:&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;iframe title ="Preview" scrolling="no" marginheight="0" marginwidth="0" frameborder="0" style="width:98px;height:115px;padding:0;background-color:#fcfcfc;" src="http://cid-b5fee7d7acde5072.office.live.com/embedicon.aspx/wpf^_mvvm^_performance1/WpfApp^_MVVM^_LazyInitialize.zip"&gt;&lt;/iframe&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8085117242240449595-7204436226642065447?l=www.shujaat.net' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.shujaat.net/feeds/7204436226642065447/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8085117242240449595&amp;postID=7204436226642065447&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/7204436226642065447'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/7204436226642065447'/><link rel='alternate' type='text/html' href='http://www.shujaat.net/2011/02/wpf-performance-improvement-for-mvvm.html' title='WPF - Performance Improvement for MVVM Applications - Part # 2'/><author><name>Muhammad Shujaat Siddiqi</name><uri>http://www.blogger.com/profile/02519138704633566929</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://1.bp.blogspot.com/-4u2DGIUBAXE/TWiFyVgVcJI/AAAAAAAAA7E/-n2ukrQ0Vfc/s72-c/1.jpg' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8085117242240449595.post-3900364787293972789</id><published>2011-02-24T22:03:00.016-06:00</published><updated>2011-02-25T02:33:20.920-06:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Rx'/><category scheme='http://www.blogger.com/atom/ns#' term='c#. .net'/><category scheme='http://www.blogger.com/atom/ns#' term='wpf'/><category scheme='http://www.blogger.com/atom/ns#' term='observable'/><category scheme='http://www.blogger.com/atom/ns#' term='Observable.Start'/><category scheme='http://www.blogger.com/atom/ns#' term='asynch wpf'/><category scheme='http://www.blogger.com/atom/ns#' term='reactive extensions'/><category scheme='http://www.blogger.com/atom/ns#' term='IObservable'/><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><category scheme='http://www.blogger.com/atom/ns#' term='Reactive extension'/><title type='text'>Rx - Executing anonymous code asynchronously</title><content type='html'>In the previous post we discuss about how we can execute a method asynchronously using Reactive Extensions. In this post we will discuss how we can execute anonymous code asynchronously using Reactive Extensions. Rx provides this support using &lt;span style="font-style:italic;"&gt;Observable.Start&lt;/span&gt;.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Invoking Actions (No data returned):&lt;/span&gt;&lt;br /&gt;Let us start with discussing how we can execute code asynchronously with no data to return. &lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://4.bp.blogspot.com/-4hTzaEpZiZ8/TWc2nSepsRI/AAAAAAAAA6o/ajeQgsdqB9s/s1600/6.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 267px;" src="http://4.bp.blogspot.com/-4hTzaEpZiZ8/TWc2nSepsRI/AAAAAAAAA6o/ajeQgsdqB9s/s400/6.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5577486712124846354" /&gt;&lt;/a&gt;&lt;br /&gt;The event handler of Click event of the button is as follows:&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;private void button2_Click(object sender, RoutedEventArgs e)&lt;br /&gt;{&lt;br /&gt;    Observable.Start(() =&amp;gt;&lt;br /&gt;        {&lt;br /&gt;            Thread.Sleep(2000);&lt;br /&gt;&lt;br /&gt;            return;&lt;br /&gt;        }&lt;br /&gt;    )&lt;br /&gt;    .ObserveOnDispatcher()&lt;br /&gt;    .Subscribe(&lt;br /&gt;                (result) =&amp;gt; { ;},&lt;br /&gt;                (ex) =&amp;gt; this.Background = Brushes.Red,&lt;br /&gt;                () =&amp;gt; this.Background = Brushes.Green);&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;This code just executes simple code asynchronously in a ThreadPool thread. It generates OnNext, OnCompleted and OnError messages on the Dispatcher thread as we are observing on Dispatcher. After atleast two seconds the background of window should turn green.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Invoking anonymous code (data returned from lambda) asynchronously:&lt;/span&gt;&lt;br /&gt;We can also execute anonymous asynchronous code using &lt;span style="font-style:italic;"&gt;Observable.Start&lt;/span&gt; which actually return a value. This code is in the form of lambda expressions or lambda statements which explicitly return data through return statement.  Let us add a button on the same window. When user clicks the button it should update the operand boxes with any random number. &lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;private void btnFillRandomOperands_Click(object sender, RoutedEventArgs e)&lt;br /&gt;{&lt;br /&gt;    Observable.Start&amp;lt;int&amp;gt;(&lt;br /&gt;        () =&amp;gt;&lt;br /&gt;        {&lt;br /&gt;            Thread.Sleep(2000);&lt;br /&gt;            return new Random().Next(1, 10);&lt;br /&gt;        }).ObserveOnDispatcher&amp;lt;int&amp;gt;()&lt;br /&gt;        .Subscribe(&lt;br /&gt;                       (result) =&amp;gt;&lt;br /&gt;                       {&lt;br /&gt;                           this.textBoxOperand1.Text = result.ToString();&lt;br /&gt;                           this.textBoxOperand2.Text = result.ToString();&lt;br /&gt;                       },&lt;br /&gt;                        (ex) =&amp;gt; this.Background = Brushes.Red,&lt;br /&gt;                        () =&amp;gt; this.Background = Brushes.Green&lt;br /&gt;                    );&lt;br /&gt;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;The above code uses Random class to generate a random number between 1 and 10. The returned number is provided to &lt;span style="font-style:italic;"&gt;OnNext &lt;/span&gt;handler by Rx runtime. This handler updates both operand text boxes with this number. After this, the runtime places &lt;span style="font-style:italic;"&gt;OnCompleted &lt;/span&gt;handler which turns the background of the window to green.&lt;br /&gt;&lt;br /&gt;When we run this and click this button, it results in the following window after atleast 2 seconds. Definitely, it might be a different random number generated and filled in the operands text boxes.&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://4.bp.blogspot.com/-cuhwAi3rWI4/TWdhYjm48EI/AAAAAAAAA6w/3sFenT1g3Ng/s1600/7.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 267px;" src="http://4.bp.blogspot.com/-cuhwAi3rWI4/TWdhYjm48EI/AAAAAAAAA6w/3sFenT1g3Ng/s400/7.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5577533738024759362" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Passing Arguments to Code executed by Observable.Start:&lt;/span&gt;&lt;br /&gt;It doesn’t seem that we can have any parameters to &lt;span style="font-style:italic;"&gt;Observable.Start&lt;/span&gt; directly. But we can use our old technique of using Captured Variables. As we know that lambdas can capture variables from the scope they are generated from. The variables used  by lambda like this are called Captured variables. Like a regular lambda statement executed asynchronously, these variables also have &lt;span style="font-style:italic;"&gt;Closure &lt;/span&gt;issues. I have discussed here how to avoid closure issues by assigning the value of captured variables to local variables inside lambdas.&lt;br /&gt;&lt;br /&gt;&lt;a href="http://shujaatsiddiqi.blogspot.com/2010/12/wpf-dispatcherbegininvoke-and-closures.html"&gt;http://shujaatsiddiqi.blogspot.com/2010/12/wpf-dispatcherbegininvoke-and-closures.html&lt;/a&gt;&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;private void button1_Click(object sender, RoutedEventArgs e)&lt;br /&gt;{&lt;br /&gt;    decimal operand1 = Decimal.Parse(this.textBoxOperand1.Text);&lt;br /&gt;    decimal operand2 = Decimal.Parse(this.textBoxOperand2.Text);&lt;br /&gt;&lt;br /&gt;    Observable.Start(() =&amp;gt;&lt;br /&gt;                         {&lt;br /&gt;                             Thread.Sleep(2000);&lt;br /&gt;&lt;br /&gt;                             return operand1 + operand2;&lt;br /&gt;                         })&lt;br /&gt;                         .ObserveOnDispatcher()&lt;br /&gt;                         .Subscribe(&lt;br /&gt;                                (result) =&amp;gt; { this.textBoxResult.Text = result.ToString(); });&lt;br /&gt;&lt;br /&gt;    operand1 = 3;&lt;br /&gt;    operand2 = 4;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;In the above case what do you guess would be shown in the result &lt;span style="font-style:italic;"&gt;textbox &lt;/span&gt;if we enter &lt;span style="font-style:italic;"&gt;2.1&lt;/span&gt; and &lt;span style="font-style:italic;"&gt;3.5&lt;/span&gt; in the two operand text boxes. If you guess &lt;span style="font-style:italic;"&gt;5.6&lt;/span&gt; then you would be surprised to see this result.&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://2.bp.blogspot.com/-tgc8_9otiGQ/TWcrAl36v3I/AAAAAAAAA6A/PyxHze17mGM/s1600/1.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 267px;" src="http://2.bp.blogspot.com/-tgc8_9otiGQ/TWcrAl36v3I/AAAAAAAAA6A/PyxHze17mGM/s400/1.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5577473952688291698" /&gt;&lt;/a&gt;&lt;br /&gt;This is the result of modified &lt;span style="font-style:italic;"&gt;captured variables&lt;/span&gt; as the modified value of those captured variables are used which are &lt;span style="font-style:italic;"&gt;3&lt;/span&gt; and &lt;span style="font-style:italic;"&gt;4&lt;/span&gt;. The result of addition of &lt;span style="font-style:italic;"&gt;3&lt;/span&gt; and &lt;span style="font-style:italic;"&gt;4&lt;/span&gt; is &lt;span style="font-style:italic;"&gt;7&lt;/span&gt;, which is displayed in the &lt;span style="font-style:italic;"&gt;Result text box&lt;/span&gt;. In order to fix this, we can define two new local variables &lt;span style="font-style:italic;"&gt;localOperand1 &lt;/span&gt;and &lt;span style="font-style:italic;"&gt;localOperand2 &lt;/span&gt;and initialize them with the values of captured variables. &lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;private void button1_Click(object sender, RoutedEventArgs e)&lt;br /&gt;{&lt;br /&gt;    decimal operand1 = Decimal.Parse(this.textBoxOperand1.Text);&lt;br /&gt;    decimal operand2 = Decimal.Parse(this.textBoxOperand2.Text);&lt;br /&gt;&lt;br /&gt;    Observable.Start(() =&amp;gt;&lt;br /&gt;                         {&lt;br /&gt;                             decimal localOperand1 = operand1;&lt;br /&gt;                             decimal localOperand2 = operand2;&lt;br /&gt;&lt;br /&gt;                             Thread.Sleep(2000);&lt;br /&gt; &lt;br /&gt;                             return localOperand1 + localOperand2;&lt;br /&gt;                         })&lt;br /&gt;                         .ObserveOnDispatcher()&lt;br /&gt;                         .Subscribe(&lt;br /&gt;                                (result) =&amp;gt; { this.textBoxResult.Text = result.ToString(); });&lt;br /&gt;&lt;br /&gt;    Thread.Sleep(2);&lt;br /&gt;&lt;br /&gt;    operand1 = 3;&lt;br /&gt;    operand2 = 4;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;When we run the application and enter data &lt;span style="font-style:italic;"&gt;2.1&lt;/span&gt; and &lt;span style="font-style:italic;"&gt;3.5&lt;/span&gt; then the correct result is displayed in the &lt;span style="font-style:italic;"&gt;Result text box&lt;/span&gt;.&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://4.bp.blogspot.com/-nNP1zQmY5AA/TWcr6GAGVgI/AAAAAAAAA6I/POl5kWnXNZE/s1600/2.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 267px;" src="http://4.bp.blogspot.com/-nNP1zQmY5AA/TWcr6GAGVgI/AAAAAAAAA6I/POl5kWnXNZE/s400/2.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5577474940565083650" /&gt;&lt;/a&gt;&lt;br /&gt;Although &lt;span style="font-style:italic;"&gt;Resharper &lt;/span&gt;still shows warning but it is just fine as we have seen the correct result being calculated.&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://4.bp.blogspot.com/-E8kLvHO1tck/TWcsQ9s7X6I/AAAAAAAAA6Q/yiAC4W6dUs4/s1600/3.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 125px;" src="http://4.bp.blogspot.com/-E8kLvHO1tck/TWcsQ9s7X6I/AAAAAAAAA6Q/yiAC4W6dUs4/s400/3.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5577475333474181026" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Observable.Start and Exceptions in the code executed:&lt;/span&gt;&lt;br /&gt;As a result of an exception &lt;span style="font-style:italic;"&gt;Observable.Start&lt;/span&gt; behaves same way as &lt;span style="font-style:italic;"&gt;Observable.ToAsync&lt;/span&gt;. We can represent the behavior in marble diagram as follows:&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://1.bp.blogspot.com/-gYfrQhyanLs/TWcv18nonmI/AAAAAAAAA6Y/Fk8BchqmJfc/s1600/4.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 393px; height: 148px;" src="http://1.bp.blogspot.com/-gYfrQhyanLs/TWcv18nonmI/AAAAAAAAA6Y/Fk8BchqmJfc/s400/4.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5577479267373588066" /&gt;&lt;/a&gt;&lt;br /&gt;Let us update the code executed asynchronously using &lt;span style="font-style:italic;"&gt;Observable.Start&lt;/span&gt; so that if the sum of number entered is either zero or lesser, it should throw an Exception. &lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;[DebuggerStepThrough]&lt;br /&gt;private void button1_Click(object sender, RoutedEventArgs e)&lt;br /&gt;{&lt;br /&gt;    decimal operand1 = Decimal.Parse(this.textBoxOperand1.Text);&lt;br /&gt;    decimal operand2 = Decimal.Parse(this.textBoxOperand2.Text);&lt;br /&gt;&lt;br /&gt;    Observable.Start(() =&amp;gt;&lt;br /&gt;    {&lt;br /&gt;        decimal localOperand1 = operand1;&lt;br /&gt;        decimal localOperand2 = operand2;&lt;br /&gt;        decimal sum = localOperand1 + localOperand2;&lt;br /&gt;&lt;br /&gt;        Thread.Sleep(2000);&lt;br /&gt;&lt;br /&gt;        if (sum &amp;lt;= 0)&lt;br /&gt;        {&lt;br /&gt;            throw new System.Exception("Error in computation");&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        return sum;&lt;br /&gt;    })&lt;br /&gt;    .ObserveOnDispatcher()&lt;br /&gt;    .Subscribe(&lt;br /&gt;        (result) =&amp;gt; { this.textBoxResult.Text = result.ToString(); },&lt;br /&gt;        (ex) =&amp;gt; this.Background = Brushes.Red,&lt;br /&gt;        () =&amp;gt; this.Background = Brushes.Green);&lt;br /&gt;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;You can notice that we are still subscribing on &lt;span style="font-style:italic;"&gt;Dispatcher&lt;/span&gt;. In addition to &lt;span style="font-style:italic;"&gt;OnNext&lt;/span&gt;, we have provided the code for &lt;span style="font-style:italic;"&gt;OnCompleted &lt;/span&gt;and &lt;span style="font-style:italic;"&gt;OrError&lt;/span&gt;. The window should turn &lt;span style="font-style:italic;"&gt;green &lt;/span&gt;when the operation completed successfully resulting in &lt;span style="font-style:italic;"&gt;OnCompleted&lt;/span&gt;. In case of exception, &lt;span style="font-style:italic;"&gt;OnError &lt;/span&gt;is executed. &lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://4.bp.blogspot.com/-OBi1v3Sh3yc/TWcxisaoYdI/AAAAAAAAA6g/o5dRLPPs4rM/s1600/5.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 130px;" src="http://4.bp.blogspot.com/-OBi1v3Sh3yc/TWcxisaoYdI/AAAAAAAAA6g/o5dRLPPs4rM/s400/5.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5577481135629820370" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Using &lt;span style="font-style:italic;"&gt;IScheduler &lt;/span&gt;to run Asynchronous code:&lt;/span&gt;&lt;br /&gt;Like &lt;span style="font-style:italic;"&gt;Observable.ToAsync&lt;/span&gt;, &lt;span style="font-style:italic;"&gt;Observable.Start&lt;/span&gt; also provides overloads to run the asynchronous code using different &lt;span style="font-style:italic;"&gt;IScheduler&lt;/span&gt;. We can run code which returns or does not return any data in the form of lambda and we can run it using the &lt;span style="font-style:italic;"&gt;IScheduler &lt;/span&gt;of our choice. You can see that just by providing Scheduler.Dispatcher info to Start we can turn this method to run on &lt;span style="font-style:italic;"&gt;UI thread&lt;/span&gt;:&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;Observable.Start(() =&amp;gt;&lt;br /&gt;    {&lt;br /&gt;        Thread.Sleep(2000);&lt;br /&gt;&lt;br /&gt;        return;&lt;br /&gt;    }, Scheduler.Dispatcher&lt;br /&gt;)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Note:&lt;/span&gt;&lt;br /&gt;There is one more overload of Observable.Start which returns ListObservable&amp;lt;TSource&amp;gt;. Since it is not about executing anonymous asynchronous code, we are discussing it here.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Download Code:&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;iframe title ="Preview" scrolling="no" marginheight="0" marginwidth="0" frameborder="0" style="width:98px;height:115px;padding:0;background-color:#fcfcfc;" src="http://cid-b5fee7d7acde5072.office.live.com/embedicon.aspx/Rx%20Anonymous%20Asynchronous/WpfApp^_AsynchObserver.zip"&gt;&lt;/iframe&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8085117242240449595-3900364787293972789?l=www.shujaat.net' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.shujaat.net/feeds/3900364787293972789/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8085117242240449595&amp;postID=3900364787293972789&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/3900364787293972789'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/3900364787293972789'/><link rel='alternate' type='text/html' href='http://www.shujaat.net/2011/02/rx-executing-anonymous-code.html' title='Rx - Executing anonymous code asynchronously'/><author><name>Muhammad Shujaat Siddiqi</name><uri>http://www.blogger.com/profile/02519138704633566929</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://4.bp.blogspot.com/-4hTzaEpZiZ8/TWc2nSepsRI/AAAAAAAAA6o/ajeQgsdqB9s/s72-c/6.jpg' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8085117242240449595.post-4319510231838887469</id><published>2011-02-23T22:45:00.011-06:00</published><updated>2011-02-24T00:10:17.778-06:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='wpf'/><category scheme='http://www.blogger.com/atom/ns#' term='observable'/><category scheme='http://www.blogger.com/atom/ns#' term='functional'/><category scheme='http://www.blogger.com/atom/ns#' term='.net'/><category scheme='http://www.blogger.com/atom/ns#' term='asynch wpf'/><category scheme='http://www.blogger.com/atom/ns#' term='ASynchDelegate'/><category scheme='http://www.blogger.com/atom/ns#' term='IObservable'/><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><category scheme='http://www.blogger.com/atom/ns#' term='Observable.ToAsync'/><title type='text'>WPF - ASynchronous Function using Observable.ToASync [Rx ASynchronous Delegate] - Part # 2</title><content type='html'>This is the second part of our discussion about how we can execute the similar functionality as provided by asynchronous anonymous delegates in .net. In previous post we discuss how we can mimic the functionality provided by &lt;span style="font-style:italic;"&gt;Func&amp;lt;...&amp;gt;&lt;/span&gt; delegate. &lt;br /&gt;&lt;br /&gt;&lt;a href="http://shujaatsiddiqi.blogspot.com/2011/02/wpf-asynchronous-function-using.html"&gt;http://shujaatsiddiqi.blogspot.com/2011/02/wpf-asynchronous-function-using.html&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;In this post we will discuss about &lt;span style="font-style:italic;"&gt;Action&amp;lt;...&amp;gt;&lt;/span&gt; delegate. As we know that we can not return any value from this compared to &lt;span style="font-style:italic;"&gt;Func&amp;lt;...&amp;gt;&lt;/span&gt; delegate. As we know that .net provides 16 different generic overloads of &lt;span style="font-style:italic;"&gt;Action&amp;lt;...&amp;gt;&lt;/span&gt; delegates in order to accommodate delegates for methods having up to 16 parameters. Similarly, 16 different overloads of &lt;span style="font-style:italic;"&gt;Observable.ToAsync&lt;/span&gt; have been provided.&lt;br /&gt;&lt;br /&gt;Let us add this method to our class:&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;[DebuggerStepThrough]&lt;br /&gt;private void ProcessOperandsFireAndForget(decimal operand1, decimal operand2)&lt;br /&gt;{&lt;br /&gt;    Thread.Sleep(5000);&lt;br /&gt;    if (operand1 &lt;= 0 || operand2 &lt;= 0)&lt;br /&gt;    {&lt;br /&gt;        throw new System.Exception("Exception generated");&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;Since it returns &lt;span style="font-style:italic;"&gt;void&lt;/span&gt;, we can use Action delegate for this. In Reactive Extension we can use &lt;span style="font-style:italic;"&gt;Observable.ToAsync&lt;/span&gt; for this method. It just producing a delay of 5 seconds. If any of the operands are zero or negative, it is resulting in an exception with message &lt;span style="font-style:italic;"&gt;"Exception generated"&lt;/span&gt;. &lt;br /&gt;&lt;br /&gt;In order to run this we add another button on the window. The handler for Click event for the button can be as follows:&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;private void btnFireAndForget_Click(object sender, RoutedEventArgs e)&lt;br /&gt;{&lt;br /&gt;    decimal operand1 = Decimal.Parse(this.textBoxOperand1.Text);&lt;br /&gt;    decimal operand2 = Decimal.Parse(this.textBoxOperand2.Text);&lt;br /&gt;&lt;br /&gt;    Observable.ToAsynclt;decimal, decimal&amp;gt;(ProcessOperandsFireAndForget, Scheduler.TaskPool)(operand1, operand2)&lt;br /&gt;       .ObserveOnDispatcher()&lt;br /&gt;       .Subscribe&amp;lt;Unit&amp;gt;(&lt;br /&gt;                  (result) =&gt; { ; },&lt;br /&gt;                  (ex) =&gt; this.Background = Brushes.Red,&lt;br /&gt;                  () =&gt; this.Background = Brushes.Green);&lt;br /&gt;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;Before running this code, let me explain the expected behavior. Basically you should be expecting the same behavior as of a method which actually returns a value. We can see that from marble diagram:&lt;br /&gt;&lt;br /&gt;&lt;span style="font-style:italic;"&gt;Graceful method execution:&lt;br /&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://4.bp.blogspot.com/-TJnhj8HLFNw/TWXr15ANIoI/AAAAAAAAA5o/B7oMudryiAQ/s1600/2.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 130px;" src="http://4.bp.blogspot.com/-TJnhj8HLFNw/TWXr15ANIoI/AAAAAAAAA5o/B7oMudryiAQ/s400/2.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5577123024635503234" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;span style="font-style:italic;"&gt;Exception in method execution:&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://1.bp.blogspot.com/-xUEWTuGG8DI/TWXr474OIpI/AAAAAAAAA5w/G94zjcCkoJs/s1600/8.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 393px; height: 148px;" src="http://1.bp.blogspot.com/-xUEWTuGG8DI/TWXr474OIpI/AAAAAAAAA5w/G94zjcCkoJs/s400/8.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5577123076946928274" /&gt;&lt;/a&gt;&lt;br /&gt;Now one thing is of interest which you might have already noticed. It is about &lt;span style="font-style:italic;"&gt;OnNext &lt;/span&gt;message. Since OnNext passes some data in its argument, what data runtime would be passing in this as this method has &lt;span style="font-style:italic;"&gt;void &lt;/span&gt; return type. Just to clarify this, I have used a generic overload of &lt;span style="font-style:italic;"&gt;Subscribe &lt;/span&gt;method. See &lt;span style="font-style:italic;"&gt;Unit &lt;/span&gt;type there? Basically is a new &lt;span style="font-style:italic;"&gt;IEquatable struct&lt;/span&gt; provided in .net framework. Basically the message is generated. For methods with no return types, &lt;span style="font-style:italic;"&gt;OnNext &lt;/span&gt;messages are generated with this type. &lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://4.bp.blogspot.com/-sku-3GZRsuQ/TWXwIfbfA8I/AAAAAAAAA54/K48T0gemkG0/s1600/13.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 93px;" src="http://4.bp.blogspot.com/-sku-3GZRsuQ/TWXwIfbfA8I/AAAAAAAAA54/K48T0gemkG0/s400/13.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5577127742234624962" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;IScheduler support for Observable.ToAsync:&lt;/span&gt;&lt;br /&gt;As I have told you that various overloads have been provided for &lt;span style="font-style:italic;"&gt;Observable.ToAsync&lt;/span&gt; have been provided to accommodate all different overloads of &lt;span style="font-style:italic;"&gt;Func &lt;/span&gt;and &lt;span style="font-style:italic;"&gt;Action &lt;/span&gt;delegates. Make it at least double. Basically with each overload provided to support a particular number of arguments, one overload is provided to support an &lt;span style="font-style:italic;"&gt;IScheduler &lt;/span&gt;so that we could decide which &lt;span style="font-style:italic;"&gt;IScheduler &lt;/span&gt;to use to run this asynchronous code. Using these overloads we can specify which &lt;span style="font-style:italic;"&gt;Scheduler &lt;/span&gt;we want to use to execute the method. Whatever thread is used to execute the method, would be the same thread on which &lt;span style="font-style:italic;"&gt;OnNext&lt;/span&gt;, &lt;span style="font-style:italic;"&gt;OnCompleted &lt;/span&gt;and &lt;span style="font-style:italic;"&gt;OnError &lt;/span&gt;messages are generated.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Note:&lt;/span&gt; &lt;br /&gt;We can also execute methods without any parameters with / without any return type using &lt;span style="font-style:italic;"&gt;Observable.ToAsync&lt;/span&gt;. It would be following the same marble diagrams as presented in this post.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Download Code:&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;iframe title ="Preview" scrolling="no" marginheight="0" marginwidth="0" frameborder="0" style="width:98px;height:115px;padding:0;background-color:#fcfcfc;" src="http://cid-b5fee7d7acde5072.office.live.com/embedicon.aspx/Observable%20ToASync%202/WpfApp^_AsynchObserver.zip"&gt;&lt;/iframe&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8085117242240449595-4319510231838887469?l=www.shujaat.net' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.shujaat.net/feeds/4319510231838887469/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8085117242240449595&amp;postID=4319510231838887469&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/4319510231838887469'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/4319510231838887469'/><link rel='alternate' type='text/html' href='http://www.shujaat.net/2011/02/wpf-asynchronous-function-using_23.html' title='WPF - ASynchronous Function using Observable.ToASync [Rx ASynchronous Delegate] - Part # 2'/><author><name>Muhammad Shujaat Siddiqi</name><uri>http://www.blogger.com/profile/02519138704633566929</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://4.bp.blogspot.com/-TJnhj8HLFNw/TWXr15ANIoI/AAAAAAAAA5o/B7oMudryiAQ/s72-c/2.jpg' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8085117242240449595.post-6776532221785738772</id><published>2011-02-22T22:35:00.022-06:00</published><updated>2011-02-24T00:06:24.801-06:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='wpf'/><category scheme='http://www.blogger.com/atom/ns#' term='observable'/><category scheme='http://www.blogger.com/atom/ns#' term='functional'/><category scheme='http://www.blogger.com/atom/ns#' term='.net'/><category scheme='http://www.blogger.com/atom/ns#' term='asynch wpf'/><category scheme='http://www.blogger.com/atom/ns#' term='ASynchDelegate'/><category scheme='http://www.blogger.com/atom/ns#' term='IObservable'/><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><category scheme='http://www.blogger.com/atom/ns#' term='Observable.ToAsync'/><title type='text'>WPF - ASynchronous Function using Observable.ToASync [Rx ASynchronous Delegate] - Part # 1</title><content type='html'>This is the first part of our discussion about asynchronous method execution using Reactive Extension. The second part of this discussion can be found here:&lt;br /&gt;&lt;br /&gt;&lt;a href="http://shujaatsiddiqi.blogspot.com/2011/02/wpf-asynchronous-function-using_23.html"&gt;http://shujaatsiddiqi.blogspot.com/2011/02/wpf-asynchronous-function-using_23.html&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;In this post we discuss how we can execute a method asynchronously using the features provided in &lt;span style="font-style:italic;"&gt;Reactive Extensions&lt;/span&gt; Rx. We discussed the usage of &lt;span style="font-style:italic;"&gt;asynchronous delegate&lt;/span&gt; in a WPF application in the following post:&lt;br /&gt;&lt;br /&gt;&lt;a href="http://shujaatsiddiqi.blogspot.com/2010/12/asynchronous-delegate-exception-model.html"&gt;http://shujaatsiddiqi.blogspot.com/2010/12/asynchronous-delegate-exception-&lt;br /&gt;model.html&lt;/a&gt;&lt;br /&gt;This is basically the similar concept in Rx. &lt;br /&gt;&lt;pre class="brush: xml; gutter: false;"&gt;&lt;br /&gt;&amp;lt;Window x:Class="WpfApp_AsynchObserver.MainWindow"&lt;br /&gt;        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"&lt;br /&gt;        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&lt;br /&gt;        Title="MainWindow" Height="350" Width="525"&amp;gt;&lt;br /&gt;    &amp;lt;Grid&amp;gt;&lt;br /&gt;        &amp;lt;TextBox Height="27" HorizontalAlignment="Left" Margin="138,22,0,0"      &lt;br /&gt;                 Name="textBoxOperand1" VerticalAlignment="Top" Width="311" /&amp;gt;&lt;br /&gt;        &amp;lt;TextBox Height="27" HorizontalAlignment="Left" Margin="138,55,0,0"      &lt;br /&gt;                 Name="textBoxOperand2" VerticalAlignment="Top" Width="311" /&amp;gt;&lt;br /&gt;        &amp;lt;TextBox Height="27" HorizontalAlignment="Left" Margin="138,143,0,0"     &lt;br /&gt;                 Name="textBoxResult" VerticalAlignment="Top" Width="311" /&amp;gt;&lt;br /&gt;        &amp;lt;Button Content="Sum" Height="28" HorizontalAlignment="Left" Margin="139,88,0,0"              &lt;br /&gt;                Name="button1" VerticalAlignment="Top" Width="143" Click="button1_Click" /&amp;gt;&lt;br /&gt;        &amp;lt;Label Content="Operand 1" Height="27" HorizontalAlignment="Left" Margin="12,22,0,0"             &lt;br /&gt;               Name="label1" VerticalAlignment="Top" Width="120" /&amp;gt;&lt;br /&gt;        &amp;lt;Label Content="Operand 2" Height="27" HorizontalAlignment="Left" Margin="12,55,0,0"         &lt;br /&gt;               Name="label2" VerticalAlignment="Top" Width="120" /&amp;gt;&lt;br /&gt;        &amp;lt;Label Content="Result" Height="27" HorizontalAlignment="Left" Margin="12,143,0,0"          &lt;br /&gt;               Name="label3" VerticalAlignment="Top" Width="120" /&amp;gt;&lt;br /&gt;    &amp;lt;/Grid&amp;gt;&lt;br /&gt;&amp;lt;/Window&amp;gt;&lt;/pre&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://1.bp.blogspot.com/-HfPIiRQrY8g/TWSPx9_XStI/AAAAAAAAA4I/1xroubG_3JU/s1600/1.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 267px;" src="http://1.bp.blogspot.com/-HfPIiRQrY8g/TWSPx9_XStI/AAAAAAAAA4I/1xroubG_3JU/s400/1.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5576740327208209106" /&gt;&lt;/a&gt;&lt;br /&gt;The code behind is as follows:&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;public partial class MainWindow : Window&lt;br /&gt;{&lt;br /&gt;    public MainWindow()&lt;br /&gt;    {&lt;br /&gt;        InitializeComponent();&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private decimal ProcessOperands(decimal operand1, decimal operand2)&lt;br /&gt;    {&lt;br /&gt;        decimal sum;&lt;br /&gt;        sum = operand1 + operand2;&lt;br /&gt;&lt;br /&gt;        return sum;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private void button1_Click(object sender, RoutedEventArgs e)&lt;br /&gt;    {&lt;br /&gt;        decimal operand1 = Decimal.Parse(this.textBoxOperand1.Text);&lt;br /&gt;        decimal operand2 = Decimal.Parse(this.textBoxOperand2.Text);&lt;br /&gt;&lt;br /&gt;        this.textBoxResult.Text = ProcessOperands(operand1, operand2).ToString();&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;Lets run the application now. Everything is working great. We enter numeric digits in the two operands fields. When we click Enter, the result appears in the Result text box. Now let us change the method call (ProcessOperands) to be an asynchronous call using Observable.ToAsync. We need to update the button’s click handler as follows:&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;private void button1_Click(object sender, RoutedEventArgs e)&lt;br /&gt;{&lt;br /&gt;    decimal operand1 = Decimal.Parse(this.textBoxOperand1.Text);&lt;br /&gt;    decimal operand2 = Decimal.Parse(this.textBoxOperand2.Text);&lt;br /&gt;&lt;br /&gt;    Observable.ToAsync&amp;lt;decimal, decimal, decimal&amp;gt;(ProcessOperands)(operand1, operand2)&lt;br /&gt;        .Subscribe(&lt;br /&gt;                     (result) =&gt; { this.textBoxResult.Text = result.ToString(); }&lt;br /&gt;                  );&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;The code clearly shows that we have used an overload of &lt;span style="font-style:italic;"&gt;ToAsync &lt;/span&gt;which takes two decimal values as arguments and returns a decimal value. We have used this as our &lt;span style="font-style:italic;"&gt;ProcessOperand &lt;/span&gt;method is defined like that. You can see that we have used the value provided in the onNext parameter to populate the &lt;span style="font-style:italic;"&gt;textBoxResult&lt;/span&gt;. Basically onNext is placed when the async code is finished execution and result is available. If we compare it to the code we have written for &lt;span style="font-style:italic;"&gt;Asynchronous delegates&lt;/span&gt;, we realize that &lt;span style="font-style:italic;"&gt;Rx &lt;/span&gt;has internally executed code for &lt;span style="font-style:italic;"&gt;BeginInvoke &lt;/span&gt;and also called &lt;span style="font-style:italic;"&gt;EndInvoke &lt;/span&gt;for us getting the result using &lt;span style="font-style:italic;"&gt;IAsyncResult&lt;/span&gt;. If we look at the marble diagram, it should be like this.&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://3.bp.blogspot.com/-8vTLouiuviI/TWSS29cpX1I/AAAAAAAAA4Q/zPTqz5cI5FA/s1600/2.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 130px;" src="http://3.bp.blogspot.com/-8vTLouiuviI/TWSS29cpX1I/AAAAAAAAA4Q/zPTqz5cI5FA/s400/2.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5576743711496822610" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;In the marble diagram, this has shown to be placing an &lt;span style="font-style:italic;"&gt;OnCompleted &lt;/span&gt;message afterwards. Let us verify that this event is generated. In the following code, we are updating the Background color to green when &lt;span style="font-style:italic;"&gt;OnCompleted &lt;/span&gt;message is received from the Observable generated for the method.&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;private void button1_Click(object sender, RoutedEventArgs e)&lt;br /&gt;{&lt;br /&gt;    decimal operand1 = Decimal.Parse(this.textBoxOperand1.Text);&lt;br /&gt;    decimal operand2 = Decimal.Parse(this.textBoxOperand2.Text);&lt;br /&gt;&lt;br /&gt;    Observable.ToAsync&amp;lt;decimal, decimal, decimal&amp;gt;(ProcessOperands)(operand1, operand2)&lt;br /&gt;        .Subscribe(&lt;br /&gt;                     (result) =&amp;gt; { this.textBoxResult.Text = result.ToString(); },&lt;br /&gt;                     () =&amp;gt; this.Background = Brushes.Green&lt;br /&gt;                  );&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;Now we run the application and enter values in the operands text boxes. When we click the button, the &lt;span style="font-style:italic;"&gt;textBoxResult &lt;/span&gt;is updated with the sum of two operands. The window also turns green. This is due to the code we have written in &lt;span style="font-style:italic;"&gt;OnCompleted &lt;/span&gt;handler.&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://2.bp.blogspot.com/-nPINgFghkZ8/TWSUGB2HxwI/AAAAAAAAA4Y/PU2FrvLai80/s1600/3.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 267px;" src="http://2.bp.blogspot.com/-nPINgFghkZ8/TWSUGB2HxwI/AAAAAAAAA4Y/PU2FrvLai80/s400/3.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5576745069887080194" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Long running methods and Rx Thread Management for generating asynchronous block:&lt;/span&gt;&lt;br /&gt;Now you might be thinking that this is a very simple example. What if the method is a long running method taking a few seconds. Would it still be the same code. Let’s mimic that this method is taking a few seconds by putting Thread.Sleep in method code as follows:&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;private decimal ProcessOperands(decimal operand1, decimal operand2)&lt;br /&gt;{&lt;br /&gt;    decimal sum;&lt;br /&gt;    sum = operand1 + operand2;&lt;br /&gt;&lt;br /&gt;    Thread.Sleep(5000);&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;If you run this and enter data in the input text boxes and click Sum. You get the following exception:&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://4.bp.blogspot.com/-_wbkJMTYo0E/TWSU-fFYx7I/AAAAAAAAA4g/3Qd2rCMkURk/s1600/4.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 246px;" src="http://4.bp.blogspot.com/-_wbkJMTYo0E/TWSU-fFYx7I/AAAAAAAAA4g/3Qd2rCMkURk/s400/4.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5576746039808411570" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Why is this exception generated by just delaying in the asynchronous method? Basically we have caused the subscription to be on a ThreadPool thread. Since we are delaying for 5 seconds, all Rx messages (OnNext, OnCompleted and OnError) seem to be dispatched on the calling thread of subscriber.&lt;br /&gt;&lt;br /&gt;It seems if there is a delay of more than &lt;span style="font-style:italic;"&gt;3 milliseconds&lt;/span&gt; then the &lt;span style="font-style:italic;"&gt;OnNext &lt;/span&gt;messages are dispatched on a ThreadPool thread otherwise they are dispatched on the thread of the subscriber. In this case it is &lt;span style="font-style:italic;"&gt;UI thread&lt;/span&gt;. If the delay is &lt;span style="font-style:italic;"&gt;3 milliseconds&lt;/span&gt; or lesser these messages are always dispatched on &lt;span style="font-style:italic;"&gt;UI thread&lt;/span&gt;. This is true even though we know that &lt;span style="font-style:italic;"&gt;ToAsync &lt;/span&gt;is causing the method to be executed on a &lt;span style="font-style:italic;"&gt;ThreadPool &lt;/span&gt;thread.&lt;br /&gt;&lt;br /&gt;Fig: When OnNext is received in more than 3 milliseconds:&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://1.bp.blogspot.com/-P686GnW_Xwg/TWSVardoEzI/AAAAAAAAA4o/ySRs13Iawz0/s1600/5.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 189px;" src="http://1.bp.blogspot.com/-P686GnW_Xwg/TWSVardoEzI/AAAAAAAAA4o/ySRs13Iawz0/s400/5.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5576746524167639858" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Fig: When OnNext is received in 3 milliseconds or less:&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://2.bp.blogspot.com/-hyn7II9v0C8/TWSWDcnqsSI/AAAAAAAAA4w/okVaIv8Ydr8/s1600/6.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 197px;" src="http://2.bp.blogspot.com/-hyn7II9v0C8/TWSWDcnqsSI/AAAAAAAAA4w/okVaIv8Ydr8/s400/6.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5576747224557859106" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;How exceptions are handled?&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;As we have discussed [&lt;a href="http://shujaatsiddiqi.blogspot.com/2010/12/asynchronous-delegate-exception-model.html"&gt;http://shujaatsiddiqi.blogspot.com/2010/12/asynchronous-delegate-exception-model.html&lt;/a&gt;] the runtime is silent about exceptions for &lt;span style="font-style:italic;"&gt;Async delegates&lt;/span&gt; if we don’t call &lt;span style="font-style:italic;"&gt;EndInvoke&lt;/span&gt;. It is not the case with &lt;span style="font-style:italic;"&gt;Observable.ToAsync&lt;/span&gt;. It always generate exception message &lt;span style="font-style:italic;"&gt;OnError &lt;/span&gt;when there is an exception in the method executed asynchronously. Let us change the code of &lt;span style="font-style:italic;"&gt;ProcessOperands &lt;/span&gt;so that it throws an exception.&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;[DebuggerStepThrough]&lt;br /&gt;private decimal ProcessOperands(decimal operand1, decimal operand2)&lt;br /&gt;{&lt;br /&gt;    decimal sum;&lt;br /&gt;    sum = operand1 + operand2;&lt;br /&gt;&lt;br /&gt;    if (sum &lt; 0)&lt;br /&gt;    {&lt;br /&gt;        throw new System.Exception("Exception in processing data!");&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    return sum;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;The above code is resulting an exception if the sum of these two operands is negative. We also need to update the code so that &lt;span style="font-style:italic;"&gt;IObservable &lt;/span&gt;generated from &lt;span style="font-style:italic;"&gt;Observable.ToAsync&lt;/span&gt; has a non-default OnError handler. I have decorated the method with &lt;span style="font-style:italic;"&gt;DebuggerStepThrough &lt;/span&gt;attribute so that Debugger doesn’t bother me as I have &lt;span style="font-style:italic;"&gt;FCEs &lt;/span&gt;turned on. Let’s update button1_Click as follows:&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;private void button1_Click(object sender, RoutedEventArgs e)&lt;br /&gt;{&lt;br /&gt;    decimal operand1 = Decimal.Parse(this.textBoxOperand1.Text);&lt;br /&gt;    decimal operand2 = Decimal.Parse(this.textBoxOperand2.Text);&lt;br /&gt;&lt;br /&gt;    Observable.ToAsync&amp;lt;decimal, decimal, decimal&amp;gt;(ProcessOperands)(operand1, operand2)&lt;br /&gt;        .Subscribe(&lt;br /&gt;            (result) =&amp;gt; { this.textBoxResult.Text = result.ToString(); },&lt;br /&gt;            (ex) =&amp;gt; this.Background = Brushes.Red,&lt;br /&gt;            () =&amp;gt; this.Background = Brushes.Green&lt;br /&gt;        );&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;It just changes the background of the window to Red if there is an &lt;span style="font-style:italic;"&gt;OnError &lt;/span&gt;message from the method. Let’s run the application and enter data &lt;span style="font-style:italic;"&gt;2 &lt;/span&gt;and &lt;span style="font-style:italic;"&gt;-5&lt;/span&gt; in the operand fields. As we know that their sum is &lt;span style="font-style:italic;"&gt;-3&lt;/span&gt;, the background of the window should turn Red.&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://1.bp.blogspot.com/-0A4yVcKbbuQ/TWSX-fhd7QI/AAAAAAAAA44/RhAkrIx7kyw/s1600/7.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 267px;" src="http://1.bp.blogspot.com/-0A4yVcKbbuQ/TWSX-fhd7QI/AAAAAAAAA44/RhAkrIx7kyw/s400/7.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5576749338461072642" /&gt;&lt;/a&gt;&lt;br /&gt;We can show this in marble diagram as follows:&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://4.bp.blogspot.com/-RIlDjx-RFbA/TWSYbvDDfMI/AAAAAAAAA5A/JjxrNouSrIc/s1600/8.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 393px; height: 148px;" src="http://4.bp.blogspot.com/-RIlDjx-RFbA/TWSYbvDDfMI/AAAAAAAAA5A/JjxrNouSrIc/s400/8.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5576749840844684482" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Observing on Non-UI thread using different IScheduler:&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Now we suppose that the method would always take more than 3 milliseconds. Can we still use ToAsync feature of Observable? Yes we can!&lt;br /&gt;&lt;br /&gt;We just need to Observe on the Dispatcher. This can be done by using &lt;span style="font-style:italic;"&gt;ObserveOn &lt;/span&gt;feature of &lt;span style="font-style:italic;"&gt;IObservable&lt;/span&gt;. There are two methods provided for this purpose. One method allows us to generate the messages on any &lt;span style="font-style:italic;"&gt;IScheduler &lt;/span&gt;(including built-in schedulers like &lt;span style="font-style:italic;"&gt;Dispatcher, ThreadPool, TaskPool, Immediate, CurrentThread, NewThread&lt;/span&gt;). We can use any of the four overloads of this method. We can also directly use &lt;span style="font-style:italic;"&gt;ObserveOnDispatcher &lt;/span&gt;method from &lt;span style="font-style:italic;"&gt;IObservable&lt;/span&gt;. We have used the same as below.&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;private void button1_Click(object sender, RoutedEventArgs e)&lt;br /&gt;{&lt;br /&gt;    decimal operand1 = Decimal.Parse(this.textBoxOperand1.Text);&lt;br /&gt;    decimal operand2 = Decimal.Parse(this.textBoxOperand2.Text);&lt;br /&gt;&lt;br /&gt;    Observable.ToAsync&amp;lt;decimal, decimal, decimal&amp;gt;(ProcessOperands)(operand1, operand2)&lt;br /&gt;        .ObserveOnDispatcher&amp;lt;decimal&amp;gt;()&lt;br /&gt;        .Subscribe(&lt;br /&gt;            (result) =&amp;gt; { this.textBoxResult.Text = result.ToString(); },&lt;br /&gt;            (ex) =&amp;gt; this.Background = Brushes.Red,&lt;br /&gt;            () =&amp;gt; this.Background = Brushes.Green&lt;br /&gt;        );&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;Now we run the application. Although the method is being executed on a separate &lt;span style="font-style:italic;"&gt;ThreadPool &lt;/span&gt;thread but the &lt;span style="font-style:italic;"&gt;OnNext&lt;/span&gt;, &lt;span style="font-style:italic;"&gt;OnError &lt;/span&gt;and &lt;span style="font-style:italic;"&gt;OnCompleted &lt;/span&gt;messages are dispatched on &lt;span style="font-style:italic;"&gt;UI thread&lt;/span&gt;.&lt;br /&gt;&lt;br /&gt;Fig: Method executed on a ThreadPool thread&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://4.bp.blogspot.com/-kKuytbgTolM/TWSZqpXDVPI/AAAAAAAAA5I/L42kTdszEi8/s1600/9.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 173px;" src="http://4.bp.blogspot.com/-kKuytbgTolM/TWSZqpXDVPI/AAAAAAAAA5I/L42kTdszEi8/s400/9.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5576751196527613170" /&gt;&lt;/a&gt;&lt;br /&gt;Fig: &lt;span style="font-style:italic;"&gt;OnNext &lt;/span&gt;message generated on Main UI Thread&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://3.bp.blogspot.com/-i1u-Fgxyfbk/TWSaD7lZM7I/AAAAAAAAA5Q/6jhtfsDLkcw/s1600/10.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 118px;" src="http://3.bp.blogspot.com/-i1u-Fgxyfbk/TWSaD7lZM7I/AAAAAAAAA5Q/6jhtfsDLkcw/s400/10.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5576751630916334514" /&gt;&lt;/a&gt;&lt;br /&gt;Fig: &lt;span style="font-style:italic;"&gt;OnCompleted &lt;/span&gt;placed on Main UI thread&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://1.bp.blogspot.com/-TPDMopmdCXA/TWSaZ99_D7I/AAAAAAAAA5Y/mAkD13AQWig/s1600/11.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 98px;" src="http://1.bp.blogspot.com/-TPDMopmdCXA/TWSaZ99_D7I/AAAAAAAAA5Y/mAkD13AQWig/s400/11.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5576752009513471922" /&gt;&lt;/a&gt;&lt;br /&gt;Fig: &lt;span style="font-style:italic;"&gt;OnError &lt;/span&gt;placed on Main UI thread&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://3.bp.blogspot.com/-zFq-pyxV2-w/TWSa0dMnlAI/AAAAAAAAA5g/_hbmMn1F-00/s1600/12.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 189px;" src="http://3.bp.blogspot.com/-zFq-pyxV2-w/TWSa0dMnlAI/AAAAAAAAA5g/_hbmMn1F-00/s400/12.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5576752464572945410" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Limitations:&lt;/span&gt;&lt;br /&gt;Since this is a way to implement Anonymous asynchronous delegates using Reactive Extensions so it seems to have has the same limitation as anonymous asynchronous delegate (Func) has. We can not have &lt;span style="font-style:italic;"&gt;out&lt;/span&gt; or &lt;span style="font-style:italic;"&gt;ref&lt;/span&gt; parameters in the method that we want to execute asynchronously. In non-reactive model, we might easily implement named asynchronous delegate as a work around but in the reactive extension world there doesn't seem to be any alternative.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Download Code:&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;iframe title ="Preview" scrolling="no" marginheight="0" marginwidth="0" frameborder="0" style="width:98px;height:115px;padding:0;background-color:#fcfcfc;" src="http://cid-b5fee7d7acde5072.office.live.com/embedicon.aspx/WPF%20Rx%20ASync%20Delegate/WpfApp^_AsynchObserver.zip"&gt;&lt;/iframe&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8085117242240449595-6776532221785738772?l=www.shujaat.net' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.shujaat.net/feeds/6776532221785738772/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8085117242240449595&amp;postID=6776532221785738772&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/6776532221785738772'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/6776532221785738772'/><link rel='alternate' type='text/html' href='http://www.shujaat.net/2011/02/wpf-asynchronous-function-using.html' title='WPF - ASynchronous Function using Observable.ToASync [Rx ASynchronous Delegate] - Part # 1'/><author><name>Muhammad Shujaat Siddiqi</name><uri>http://www.blogger.com/profile/02519138704633566929</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://1.bp.blogspot.com/-HfPIiRQrY8g/TWSPx9_XStI/AAAAAAAAA4I/1xroubG_3JU/s72-c/1.jpg' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8085117242240449595.post-7562833505090208406</id><published>2011-02-17T22:45:00.013-06:00</published><updated>2011-02-18T01:43:06.298-06:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Rx'/><category scheme='http://www.blogger.com/atom/ns#' term='ThreadPool'/><category scheme='http://www.blogger.com/atom/ns#' term='IEvent'/><category scheme='http://www.blogger.com/atom/ns#' term='wpf'/><category scheme='http://www.blogger.com/atom/ns#' term='Throttle'/><category scheme='http://www.blogger.com/atom/ns#' term='reactive extensions'/><category scheme='http://www.blogger.com/atom/ns#' term='IObservable'/><category scheme='http://www.blogger.com/atom/ns#' term='EventStream'/><title type='text'>IObservable.Throttle causes OnNext on ThreadPool thread</title><content type='html'>This is a continuation of our following post:&lt;br /&gt;&lt;br /&gt;&lt;a href="http://shujaatsiddiqi.blogspot.com/2011/02/mvvm-observable-inotifypropertychangedp.html"&gt;http://shujaatsiddiqi.blogspot.com/2011/02/mvvm-observable-inotifypropertychangedp.html&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;In the above post we discussed about using &lt;span style="font-style:italic;"&gt;PropertyChanged &lt;/span&gt;event of &lt;span style="font-style:italic;"&gt;INotifyPropertyChanged&lt;/span&gt; by observing &lt;span style="font-style:italic;"&gt;EventStream &lt;/span&gt;support of &lt;span style="font-style:italic;"&gt;Reactive Extensions Rx&lt;/span&gt;. In this post we change the view model a bit. We remove the implementation of &lt;span style="font-style:italic;"&gt;INotifyPropertyChanged&lt;/span&gt;. We rather define it as a &lt;span style="font-style:italic;"&gt;DependencyObject &lt;/span&gt;to support a different change notification mechanism from view model. This is to demonstrate the following: &lt;br /&gt;&lt;br /&gt;&lt;span style="font-style:italic;"&gt;IObservable.Throttle causes OnNext to be generated on a ThreadPool thread instead.&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;We will see what problems might be caused by this and how we can work around this.&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;public class StudentViewModel : DependencyObject&lt;br /&gt;{&lt;br /&gt;    #region Model&lt;br /&gt;    private Student _model;&lt;br /&gt;    #endregion Model&lt;br /&gt;&lt;br /&gt;    #region Constructor&lt;br /&gt;&lt;br /&gt;    public StudentViewModel(Student student)&lt;br /&gt;    {&lt;br /&gt;        _model = student;&lt;br /&gt;&lt;br /&gt;        Observable.FromEvent&amp;lt;PropertyChangedEventArgs&amp;gt;(_model, "PropertyChanged")&lt;br /&gt;            .Where(et =&gt; et.EventArgs.PropertyName == "StudentName")&lt;br /&gt;            .Subscribe((arg) =&gt;&lt;br /&gt;                           {&lt;br /&gt;                               this.StudentId = _model.StudentId;&lt;br /&gt;                               this.StudentName = _model.StudentName;&lt;br /&gt;                           });&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    #endregion Constructor&lt;br /&gt;&lt;br /&gt;    #region Dependency Properties&lt;br /&gt;&lt;br /&gt;    public static DependencyProperty StudentIdProperty =&lt;br /&gt;        DependencyProperty.Register("StudentId", typeof(int), typeof(StudentViewModel));&lt;br /&gt;    public int StudentId&lt;br /&gt;    {&lt;br /&gt;        get { return (int)GetValue(StudentIdProperty); }&lt;br /&gt;        set { SetValue(StudentIdProperty, value); }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public static DependencyProperty StudentNameProperty =&lt;br /&gt;        DependencyProperty.Register("StudentName", typeof(string), typeof(StudentViewModel));&lt;br /&gt;    public string StudentName&lt;br /&gt;    {&lt;br /&gt;        get { return (string)GetValue(StudentNameProperty); }&lt;br /&gt;        set { SetValue(StudentNameProperty, value); }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    #endregion Dependency Properties&lt;br /&gt;&lt;br /&gt;    #region Overriden methods of DependencyObject&lt;br /&gt;    protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)&lt;br /&gt;    {&lt;br /&gt;        base.OnPropertyChanged(e);&lt;br /&gt;        switch (e.Property.Name)&lt;br /&gt;        {&lt;br /&gt;            case "StudentId":&lt;br /&gt;                _model.StudentId = (int)e.NewValue;&lt;br /&gt;                break;&lt;br /&gt;            case "StudentName":&lt;br /&gt;                _model.StudentName = (string)e.NewValue;&lt;br /&gt;                break;&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;    #endregion Overriden methods of DependencyObject&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;We have update the properties &lt;span style="font-style:italic;"&gt;StudentId &lt;/span&gt;and &lt;span style="font-style:italic;"&gt;StudentName &lt;/span&gt;to be Dependency properties. To synchronize the model's corresponding properties we have overridden &lt;span style="font-style:italic;"&gt;OnPropertyChanged &lt;/span&gt;method of &lt;span style="font-style:italic;"&gt;DependencyObject&lt;/span&gt;. The argument &lt;span style="font-style:italic;"&gt;DependencyPropertyChangedEventArgs &lt;/span&gt;, not only, provides us the details about the property being updated but it also provides the old and new values of this property. As you can see we are just using the new values of these properties to update the corresponding model's properties.&lt;br /&gt;&lt;br /&gt;We have kept the handling of model's &lt;span style="font-style:italic;"&gt;PropertyChanged &lt;/span&gt;event observation using Reactive extension's Observable event stream support available in &lt;span style="font-style:italic;"&gt;CoreEx &lt;/span&gt;assembly. Let's run the application now and open two child windows.&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://4.bp.blogspot.com/-1bJjF-WmJow/TV4DaUeyNJI/AAAAAAAAA3A/jwP5Xo3IDlY/s1600/1.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 138px;" src="http://4.bp.blogspot.com/-1bJjF-WmJow/TV4DaUeyNJI/AAAAAAAAA3A/jwP5Xo3IDlY/s400/1.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5574897139440563346" /&gt;&lt;/a&gt;&lt;br /&gt;When we enter &lt;span style="font-style:italic;"&gt;StudentName &lt;/span&gt;in one child window, the same changes are reflected in the other child window.&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://3.bp.blogspot.com/-C9qbmkQysS8/TV4E2TDBuGI/AAAAAAAAA3I/5fBX70gVgq8/s1600/2.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 138px;" src="http://3.bp.blogspot.com/-C9qbmkQysS8/TV4E2TDBuGI/AAAAAAAAA3I/5fBX70gVgq8/s400/2.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5574898719603669090" /&gt;&lt;/a&gt;&lt;br /&gt;Now we add throttling support in order to avoid frequent updates to the other child windows due to updates in model's properties. Let's update the constructor of StudentViewModel as follows:&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;public StudentViewModel(Student student)&lt;br /&gt;{&lt;br /&gt;    _model = student;&lt;br /&gt;&lt;br /&gt;    Observable.FromEvent&amp;lt;PropertyChangedEventArgs&amp;gt;(_model, "PropertyChanged")&lt;br /&gt;        .Where(et =&gt; et.EventArgs.PropertyName == "StudentName")&lt;br /&gt;        .Throttle(TimeSpan.FromMilliseconds(500))&lt;br /&gt;        .Subscribe((arg) =&gt;&lt;br /&gt;                       {&lt;br /&gt;                           this.StudentId = _model.StudentId;&lt;br /&gt;                           this.StudentName = _model.StudentName;&lt;br /&gt;                       });&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;This definition is same as previous. We have just used Throttling for PropertyChanged event for 500 milliseconds. Now we run the application. Open two child windows and enter data in &lt;span style="font-style:italic;"&gt;StudentName &lt;/span&gt;property in one of the child window. As soon as we settle, the application shuts down. Let's see what is going on by updating the code further as follows:&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;public StudentViewModel(Student student)&lt;br /&gt;{&lt;br /&gt;    _model = student;&lt;br /&gt;&lt;br /&gt;    Observable.FromEvent&amp;lt;PropertyChangedEventArgs&amp;gt;(_model, "PropertyChanged")&lt;br /&gt;        .Where(et =&gt; et.EventArgs.PropertyName == "StudentName")&lt;br /&gt;        .Throttle(TimeSpan.FromMilliseconds(500))&lt;br /&gt;        .Subscribe((arg) =&gt;&lt;br /&gt;                       {&lt;br /&gt;                           try&lt;br /&gt;                           {&lt;br /&gt;                               this.StudentId = _model.StudentId;&lt;br /&gt;                               this.StudentName = _model.StudentName;&lt;br /&gt;                           }&lt;br /&gt;                           catch (Exception ex)&lt;br /&gt;                           {&lt;br /&gt;                               MessageBox.Show(ex.Message);&lt;br /&gt;                           }&lt;br /&gt;                       });&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Now we run the application and enter data in &lt;span style="font-style:italic;"&gt;StudentName &lt;/span&gt;text box as previous. The exception handling logic causes the following &lt;span style="font-style:italic;"&gt;MessageBox &lt;/span&gt;to be displayed.&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://1.bp.blogspot.com/-hjZ0imZajxg/TV4NnG4cryI/AAAAAAAAA3Q/4jLGzrEBg8o/s1600/3.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 138px;" src="http://1.bp.blogspot.com/-hjZ0imZajxg/TV4NnG4cryI/AAAAAAAAA3Q/4jLGzrEBg8o/s400/3.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5574908354244685602" /&gt;&lt;/a&gt;&lt;br /&gt;This is because of the reason that &lt;span style="font-style:italic;"&gt;IObservable.Throttle&lt;/span&gt; causes &lt;span style="font-style:italic;"&gt;OnNext &lt;/span&gt;to be placed in a &lt;span style="font-style:italic;"&gt;ThreadPool &lt;/span&gt;thread.&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://4.bp.blogspot.com/-6INwF6qzGaA/TV4QZMSLPDI/AAAAAAAAA3Y/435Z1TDXDsY/s1600/4.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 185px;" src="http://4.bp.blogspot.com/-6INwF6qzGaA/TV4QZMSLPDI/AAAAAAAAA3Y/435Z1TDXDsY/s400/4.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5574911413711486002" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Using Invoke / BeginInvoke on Dispatcher:&lt;/span&gt;&lt;br /&gt;The first solution could be to directly using &lt;span style="font-style:italic;"&gt;Dispatcher.Invoke&lt;/span&gt; / &lt;span style="font-style:italic;"&gt;Dispatcher.BeginInvoke&lt;/span&gt;. We can specify the code that we want to execute in the &lt;span style="font-style:italic;"&gt;Action &lt;/span&gt;delegate. The delegate's code is executed here on UI thread. We update the constructor as follows:&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;public StudentViewModel(Student student)&lt;br /&gt;{&lt;br /&gt;    _model = student;&lt;br /&gt;&lt;br /&gt;    Observable.FromEvent&amp;lt;PropertyChangedEventArgs&amp;gt;(_model, "PropertyChanged")&lt;br /&gt;        .Where(et =&gt; et.EventArgs.PropertyName == "StudentName")&lt;br /&gt;        .Throttle(TimeSpan.FromMilliseconds(500))&lt;br /&gt;        .Subscribe((arg) =&gt;&lt;br /&gt;                       {&lt;br /&gt;                           Dispatcher.BeginInvoke(new Action(() =&gt;&lt;br /&gt;                                  {&lt;br /&gt;                                      this.StudentId = _model.StudentId;&lt;br /&gt;                                      this.StudentName = _model.StudentName;&lt;br /&gt;                                  }), null);                                   &lt;br /&gt;                           &lt;br /&gt;                       });&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Now we run the application. Again we open two windows and enter data in &lt;span style="font-style:italic;"&gt;StudentName &lt;/span&gt;text box. We see that the data is successfully updated in the other window now. Let's insert the break point again in &lt;span style="font-style:italic;"&gt;OnNext &lt;/span&gt;code.&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://1.bp.blogspot.com/-2RXZ59oc3SM/TV4Yh1xF5CI/AAAAAAAAA3g/g9q_1OnsVPc/s1600/5.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 175px;" src="http://1.bp.blogspot.com/-2RXZ59oc3SM/TV4Yh1xF5CI/AAAAAAAAA3g/g9q_1OnsVPc/s400/5.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5574920358378988578" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Using other overload of Throttle:&lt;/span&gt;&lt;br /&gt;We can use other overload of &lt;span style="font-style:italic;"&gt;IObservable.Throttle&lt;/span&gt; method. This requires an additional overload which has an additional parameter of type &lt;span style="font-style:italic;"&gt;IScheduler&lt;/span&gt;. &lt;span style="font-style:italic;"&gt;IScheduler &lt;/span&gt;is a Rx interface available in &lt;span style="font-style:italic;"&gt;CoreEx&lt;/span&gt; assembly and &lt;span style="font-style:italic;"&gt;System.Concurrency&lt;/span&gt; namespace.&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;public StudentViewModel(Student student)&lt;br /&gt;{&lt;br /&gt;    _model = student;&lt;br /&gt;&lt;br /&gt;    Observable.FromEvent&amp;lt;PropertyChangedEventArgs&amp;gt;(_model, "PropertyChanged")&lt;br /&gt;        .Where(et =&gt; et.EventArgs.PropertyName == "StudentName")&lt;br /&gt;        .Throttle(TimeSpan.FromMilliseconds(500), Scheduler.Dispatcher)&lt;br /&gt;        .Subscribe((arg) =&gt;&lt;br /&gt;                       {&lt;br /&gt;                           this.StudentId = _model.StudentId;&lt;br /&gt;                           this.StudentName = _model.StudentName;&lt;br /&gt;                       });&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;We have specified &lt;span style="font-style:italic;"&gt;Scheduler.Dispatcher&lt;/span&gt; for other parameter. This is also available in &lt;span style="font-style:italic;"&gt;System.Concurrency&lt;/span&gt; namespace. It is available in &lt;span style="font-style:italic;"&gt;CoreEx &lt;/span&gt;assembly. This is saving us from dispatching in our code but Throttle's generated OnNext messages will be generated in the UI thread. Let's run the application and open two child windows like before.&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://4.bp.blogspot.com/-EH4mjqknQ_s/TV4coo6Zz-I/AAAAAAAAA3o/l8gKgP1gLK0/s1600/6.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 176px;" src="http://4.bp.blogspot.com/-EH4mjqknQ_s/TV4coo6Zz-I/AAAAAAAAA3o/l8gKgP1gLK0/s400/6.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5574924873233977314" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Download:&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;iframe title ="Preview" scrolling="no" marginheight="0" marginwidth="0" frameborder="0" style="width:98px;height:115px;padding:0;background-color:#fcfcfc;" src="http://cid-b5fee7d7acde5072.office.live.com/embedicon.aspx/MVVM%20Reactive%20-%20Throttling/ReactiveModelSynch%20-%20Throttling.zip"&gt;&lt;/iframe&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8085117242240449595-7562833505090208406?l=www.shujaat.net' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.shujaat.net/feeds/7562833505090208406/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8085117242240449595&amp;postID=7562833505090208406&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/7562833505090208406'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/7562833505090208406'/><link rel='alternate' type='text/html' href='http://www.shujaat.net/2011/02/iobservablethrottle-causes-onnext-on.html' title='IObservable.Throttle causes OnNext on ThreadPool thread'/><author><name>Muhammad Shujaat Siddiqi</name><uri>http://www.blogger.com/profile/02519138704633566929</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://4.bp.blogspot.com/-1bJjF-WmJow/TV4DaUeyNJI/AAAAAAAAA3A/jwP5Xo3IDlY/s72-c/1.jpg' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8085117242240449595.post-5592487212238566545</id><published>2011-02-15T22:14:00.023-06:00</published><updated>2011-02-17T02:01:25.325-06:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='OnCompleted'/><category scheme='http://www.blogger.com/atom/ns#' term='MVVM'/><category scheme='http://www.blogger.com/atom/ns#' term='wpf'/><category scheme='http://www.blogger.com/atom/ns#' term='observable'/><category scheme='http://www.blogger.com/atom/ns#' term='OnNext'/><category scheme='http://www.blogger.com/atom/ns#' term='IObserver'/><category scheme='http://www.blogger.com/atom/ns#' term='IObservable'/><category scheme='http://www.blogger.com/atom/ns#' term='OnError'/><title type='text'>WPF MVVM - Retry &amp; Catch for Observables in Reactive Extension Rx</title><content type='html'>In this post we are going to simulate a scenario of client server communication. This would simulate how observables can be used to attempt to reconnect to the server and then switching to a different server after a few unsuccessful attempts. We will keep the view simple. We would just keep a &lt;span style="font-weight:bold;"&gt;TextBlock &lt;/span&gt;to show the status of connection. If it is connected, the status should be displayed with &lt;span style="font-style:italic;"&gt;green foreground&lt;/span&gt;, otherwise it should be shown with &lt;span style="font-style:italic;"&gt;Red foreground&lt;/span&gt;.&lt;br /&gt;&lt;pre class="brush: xml; gutter: false;"&gt;&lt;br /&gt;&amp;lt;Window x:Class="Wpf_MVVM_Observables.MainWindow"&lt;br /&gt;        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"&lt;br /&gt;        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&lt;br /&gt;        xmlns:local="clr-namespace:Wpf_MVVM_Observables"&lt;br /&gt;        Title="MainWindow" Height="350" Width="525"&amp;gt;&lt;br /&gt;    &amp;lt;Window.DataContext&amp;gt;&lt;br /&gt;        &amp;lt;local:MainWindowViewModel /&amp;gt;&lt;br /&gt;    &amp;lt;/Window.DataContext&amp;gt;&lt;br /&gt;    &amp;lt;Grid&amp;gt;&lt;br /&gt;        &amp;lt;Label Content="Connection Status:" Height="25" HorizontalAlignment="Left"&lt;br /&gt;               Margin="12,114,0,0" Name="lblConnectionStatusMessage" VerticalAlignment="Top" Width="122" /&amp;gt;&lt;br /&gt;        &amp;lt;TextBlock Height="27" HorizontalAlignment="Left" Margin="140,119,0,0"&lt;br /&gt;                   Name="textBlockConnectionStatusMessage" Text="{Binding ConnectionStatusMessage}"&lt;br /&gt;                   VerticalAlignment="Top" Width="221" &amp;gt;&lt;br /&gt;            &amp;lt;TextBlock.Style&amp;gt;&lt;br /&gt;                &amp;lt;Style&amp;gt;&lt;br /&gt;                    &amp;lt;Setter Property="TextBlock.Foreground" Value="Red" /&amp;gt;&lt;br /&gt;                    &amp;lt;Style.Triggers&amp;gt;&lt;br /&gt;                        &amp;lt;DataTrigger Binding="{Binding ConnectionStatusMessage}" Value="Connected"&amp;gt;                          &lt;br /&gt;                            &amp;lt;Setter Property="TextBlock.Foreground" Value="Green" /&amp;gt;                           &lt;br /&gt;                        &amp;lt;/DataTrigger&amp;gt;&lt;br /&gt;                    &amp;lt;/Style.Triggers&amp;gt;&lt;br /&gt;                &amp;lt;/Style&amp;gt;&lt;br /&gt;            &amp;lt;/TextBlock.Style&amp;gt;&lt;br /&gt;        &amp;lt;/TextBlock&amp;gt;&lt;br /&gt;    &amp;lt;/Grid&amp;gt;&lt;br /&gt;&amp;lt;/Window&amp;gt;&lt;/pre&gt;&lt;br /&gt;This is expecting MainWindowViewModel in the same assembly. The view model should have a property, named ConnectionStatusMessage. The text of connection message is shown by binding it directly to the Text property of the TextBlock. The foreground of the message is managed through a DataTrigger on the TextBlock. DataTrigger allows us to trigger based on the values of ConnectionStatusMessage from DataContext. If the value is “Connected”, we are setting it as Green, otherwise, it would keep it as Red. Below are the way the view should appear in both states:&lt;br /&gt;&lt;br /&gt;When connected:&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://4.bp.blogspot.com/-tYMxhzmG4IE/TVtQXCl-6BI/AAAAAAAAA1o/7JIOjJZx_sQ/s1600/1.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 267px;" src="http://4.bp.blogspot.com/-tYMxhzmG4IE/TVtQXCl-6BI/AAAAAAAAA1o/7JIOjJZx_sQ/s400/1.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5574137320564516882" /&gt;&lt;/a&gt;&lt;br /&gt;When Disconnected (with specific connection status message):&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://2.bp.blogspot.com/-x0yVUuKt_uw/TVtQpsnitaI/AAAAAAAAA1w/yYX4YaSeisI/s1600/2.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 267px;" src="http://2.bp.blogspot.com/-x0yVUuKt_uw/TVtQpsnitaI/AAAAAAAAA1w/yYX4YaSeisI/s400/2.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5574137641082992034" /&gt;&lt;/a&gt;&lt;br /&gt;The simplest view model to fulfill the requirements of the above view can be developed as presented below:&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;class MainWindowViewModel : INotifyPropertyChanged&lt;br /&gt;{&lt;br /&gt;     #region Properties&lt;br /&gt;&lt;br /&gt;     private string _connectionStatusMessage;&lt;br /&gt;&lt;br /&gt;     public string ConnectionStatusMessage&lt;br /&gt;     {&lt;br /&gt;         get { return _connectionStatusMessage; }&lt;br /&gt;         set&lt;br /&gt;         {&lt;br /&gt;             _connectionStatusMessage = value;&lt;br /&gt;             OnPropertyChanged("ConnectionStatusMessage");&lt;br /&gt;         }&lt;br /&gt;     } &lt;br /&gt;&lt;br /&gt;     #endregion Properties &lt;br /&gt;&lt;br /&gt;     #region INotifyPropertyChanged implementation &lt;br /&gt;&lt;br /&gt;     public event PropertyChangedEventHandler PropertyChanged = delegate { };&lt;br /&gt;&lt;br /&gt;     private void OnPropertyChanged(string propertyName)&lt;br /&gt;     {&lt;br /&gt;         PropertyChanged(this, new PropertyChangedEventArgs(propertyName));&lt;br /&gt;     }   &lt;br /&gt;&lt;br /&gt;     #endregion INotifyPropertyChanged implementation&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;As expected by the view, it has a property ConnectionStatusMessage. This is a string property.  This is supporting change notification by implementing INotifyPropertyChanged. To verify if the view logic actually works, we can use DispatcherTimer and keep flipping the status message and see the effects in the view. We can update the view model by adding this code:&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;private DispatcherTimer _timer;&lt;br /&gt;&lt;br /&gt;public MainWindowViewModel()&lt;br /&gt;{&lt;br /&gt;    _connectionStatusMessage = "Disconnected";&lt;br /&gt;&lt;br /&gt;    _timer = new DispatcherTimer();&lt;br /&gt;    _timer.Interval = TimeSpan.FromSeconds(3);&lt;br /&gt;    _timer.Tick += new EventHandler(_timer_Tick);&lt;br /&gt;    _timer.Start();&lt;br /&gt;} &lt;br /&gt;&lt;br /&gt;void _timer_Tick(object sender, EventArgs e)&lt;br /&gt;{&lt;br /&gt;    ConnectionStatusMessage = (_connectionStatusMessage == "Connected") ? "Disconnected" : "Connected";&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;We have just used DispatcherTimer to flip the status message between Connected and Disconnected after every 3 seconds. When we run the application we notice that when status message is Connected, the foreground appears as Green, otherwise for Disconnected, it appears as Red. We would need to add System.Windows.Threading namespace for using DispatcherTimer. When we are done testing, the above code can be safely removed from the view model.&lt;br /&gt;&lt;br /&gt;Now we consider that we have a Server connection type which is observable. We will see the possible gains, by just making these types Observable. Here we are using static methods of Observable and Observer classes available in System.Linq namespace. We need to add the reference of System.Reactive assembly (currently need to install reactive extensions).  &lt;br /&gt;&lt;br /&gt;Observable.Create allows to define an Observable without actually implementing IObservable interface.  We can specify the code we need to execute when an observer subscribes to this. This is an example of Cold Observable i.e. it only exists when an observable subscribes to it. Since server communications are generally maintained on a separate worker thread, we have created a new background thread [IsBackground = true]. This would also keep the UI responsive.  Observable.Create has two overloads. One overload returns an IDisposable. The other one returns an Action delegate. This is the code executed when the observer gets unsubscribed. We have specified the return statement in the form of a lambda statement. All the Thread.Sleep statements are just to keep the different messages on the UI for a while so that we could see those messages on the display.&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;public MainWindowViewModel()&lt;br /&gt;{&lt;br /&gt;    IObservable&amp;lt;Server&amp;gt; observableServerConnection = Observable.Create&amp;lt;Server&amp;gt;((o) =&gt;&lt;br /&gt;                                                                   {&lt;br /&gt;                                                                       new Thread(() =&gt; {&lt;br /&gt;                                                                                           for (int i = 0; i &lt; 3; i++)&lt;br /&gt;                                                                                           { &lt;br /&gt;                                                                                              Thread.Sleep(2000);&lt;br /&gt;                                                                                              o.OnNext(new Server() { ServerStatus = "Connected"});&lt;br /&gt;                                                                                            }&lt;br /&gt;                                                                                            o.OnError(new Exception("Server Disconnected"));&lt;br /&gt;                                                                                  }) {IsBackground = true}.Start();&lt;br /&gt; &lt;br /&gt;                                                                       return () =&gt;&lt;br /&gt;                                                                                  {&lt;br /&gt;                                                                                      ConnectionStatusMessage = "Running Disconnect Procedure!";&lt;br /&gt; &lt;br /&gt;                                                                                      Thread.Sleep(2000);&lt;br /&gt;                                                                                      ConnectionStatusMessage = "Disconnected";&lt;br /&gt;                                                                                  };&lt;br /&gt;                                                                   });&lt;br /&gt; &lt;br /&gt;    IObserver&amp;lt;Server&amp;gt; observer = Observer.Create&amp;lt;Server&amp;gt;(&lt;br /&gt;        (server) =&gt; this.ConnectionStatusMessage = server.ServerStatus,&lt;br /&gt;        (ex) =&gt; {&lt;br /&gt;                    this.ConnectionStatusMessage = "Getting Disconnected";&lt;br /&gt;                    Thread.Sleep(2000);&lt;br /&gt;        });&lt;br /&gt;    &lt;br /&gt;    observableServerConnection.Subscribe(observer);&lt;br /&gt; &lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Like Observable, Observer also allows us to define an IObserver without actually implementing it by a class. We can specify the handlers for OnNext, OnCompleted and OnError. There are different overloads available. At the minimum, we need to specify the handler for OnNext. Here we have specified the handlers for OnNext and OnError. For the remaining methods, default implementation of these methods in Observer class are used. For this example, the connection status is updated on the display as follows:&lt;br /&gt;&lt;br /&gt;After each OnNext message (step 1):&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://2.bp.blogspot.com/-thamUj6s1rs/TVtWIFxMMDI/AAAAAAAAA14/ynTltqQXNvY/s1600/3.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 267px;" src="http://2.bp.blogspot.com/-thamUj6s1rs/TVtWIFxMMDI/AAAAAAAAA14/ynTltqQXNvY/s400/3.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5574143660788559922" /&gt;&lt;/a&gt;&lt;br /&gt;After OnError is called from Observable (step 2)&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://2.bp.blogspot.com/-PO8KoATdJKM/TVtWcX_fxYI/AAAAAAAAA2A/UEU2AFisYGw/s1600/4.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 267px;" src="http://2.bp.blogspot.com/-PO8KoATdJKM/TVtWcX_fxYI/AAAAAAAAA2A/UEU2AFisYGw/s400/4.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5574144009277785474" /&gt;&lt;/a&gt;&lt;br /&gt;Observer is automatically un-subscribed (step 3-a)&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://2.bp.blogspot.com/-f0IKv1ilhgk/TVtWrAegoxI/AAAAAAAAA2I/mq-v_Foz_Fw/s1600/5.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 267px;" src="http://2.bp.blogspot.com/-f0IKv1ilhgk/TVtWrAegoxI/AAAAAAAAA2I/mq-v_Foz_Fw/s400/5.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5574144260663452434" /&gt;&lt;/a&gt;&lt;br /&gt;Observer is automatically un-subscribed (step 3-b)&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://3.bp.blogspot.com/-HDAGIS5LcHs/TVtXJ2tG5FI/AAAAAAAAA2Q/oO0j8C3Ac-o/s1600/6.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 267px;" src="http://3.bp.blogspot.com/-HDAGIS5LcHs/TVtXJ2tG5FI/AAAAAAAAA2Q/oO0j8C3Ac-o/s400/6.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5574144790616269906" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;In order to understand the above example better, we can draw a &lt;span style="font-style:italic;"&gt;marble diagram&lt;/span&gt;. You can see that the Observable keeps on sending OnNext messages ten times. After that it sends calls OnError on the Observer. After this, the unsubscription code is executed. This explains the order of messages:&lt;br /&gt;&lt;br /&gt;    - &lt;span style="font-style:italic;"&gt;Connected (Due to OnNext)&lt;/span&gt;&lt;br /&gt;    - &lt;span style="font-style:italic;"&gt;Getting Disconnected (Due to OnError)&lt;/span&gt;&lt;br /&gt;    - &lt;span style="font-style:italic;"&gt;Running Disconnect Procedure! (Due to unsubscription)&lt;/span&gt;&lt;br /&gt;    - &lt;span style="font-style:italic;"&gt;Disconnected (Due to unsubscription)&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Now you can see that unsubscription code is executed when &lt;span style="font-style:italic;"&gt;OnError &lt;/span&gt;is finished execution.&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://3.bp.blogspot.com/-ZXfJ_Vb-UGQ/TVuDBX7U4GI/AAAAAAAAA2o/J6D16h1ypKw/s1600/marble2.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 101px;" src="http://3.bp.blogspot.com/-ZXfJ_Vb-UGQ/TVuDBX7U4GI/AAAAAAAAA2o/J6D16h1ypKw/s400/marble2.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5574193023427076194" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Attempt to Retry few times before giving up:&lt;/span&gt;&lt;br /&gt;Now we assume a requirement which directs us to try to reconnect a few times to a server before giving it up. We want to show that how easily it is for &lt;span style="font-style:italic;"&gt;Observable &lt;/span&gt;to work in a situation like this. Just comment the subscription in the previous code and update it with the following code:&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;observableServerConnection.Retry(2).Subscribe(observer);&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;This code attempts to subscribe two times. If there is an error after two times, OnError of Observable is called with the exact exception message. The order of messages displayed on the screen would be as follows:&lt;br /&gt;&lt;br /&gt;    - &lt;span style="font-style:italic;"&gt;Connected&lt;/span&gt;&lt;br /&gt;    - &lt;span style="font-style:italic;"&gt;Running Disconnect Procedure!&lt;/span&gt;&lt;br /&gt;    - &lt;span style="font-style:italic;"&gt;Disconnected&lt;/span&gt;&lt;br /&gt;    - &lt;span style="font-style:italic;"&gt;Connected&lt;/span&gt;&lt;br /&gt;    - &lt;span style="font-style:italic;"&gt;Getting Disconnected&lt;/span&gt;&lt;br /&gt;    - &lt;span style="font-style:italic;"&gt;Running Disconnect Procedure!&lt;/span&gt;&lt;br /&gt;    - &lt;span style="font-style:italic;"&gt;Disconnected&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;After seeing the marble diagram below the above sequence of messages should make sense. It can tell why OnError is executed before unsubscription code when observable is retrying. Basically, for the last Observable, the unsubscription code would be executed after &lt;span style="font-style:italic;"&gt;OnCompleted &lt;/span&gt;/ &lt;span style="font-style:italic;"&gt;OnError &lt;/span&gt;is called on the &lt;span style="font-style:italic;"&gt;Observable&lt;/span&gt;.&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://3.bp.blogspot.com/-iFZoWfORXKI/TVuIeCqxJWI/AAAAAAAAA2w/6BnQyVXLgsE/s1600/marble3.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 106px;" src="http://3.bp.blogspot.com/-iFZoWfORXKI/TVuIeCqxJWI/AAAAAAAAA2w/6BnQyVXLgsE/s400/marble3.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5574199013494826338" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;After Certain number of attempts, connect to a different server:&lt;/span&gt;&lt;br /&gt;What if we need to connect to a different server after making a certain number of attempts to a server. In the example below, we are trying to reconnect two times to the server. After failing again, it just doesn't give up but attempt to connect to a different server. Look at how easy it could become if we implement Server's connection as &lt;span style="font-style:italic;"&gt;Observable&lt;/span&gt;. Here we have used &lt;span style="font-style:italic;"&gt;Catch &lt;/span&gt;method of &lt;span style="font-style:italic;"&gt;Observable&lt;/span&gt;. We just need to update the constructor or &lt;span style="font-style:italic;"&gt;MainWindowViewModel&lt;/span&gt;. We have created a new Observable like already existing &lt;span style="font-style:italic;"&gt;Observable&lt;/span&gt;. If there is no error finally in the Observable on which Catch is defined then this &lt;span style="font-style:italic;"&gt;Observable &lt;/span&gt;is not subscribed.&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;public MainWindowViewModel()&lt;br /&gt;{&lt;br /&gt;    IObservable&amp;lt;Server&amp;gt; observableServerConnection =&lt;br /&gt;        Observable.Create&amp;lt;Server&amp;gt;((o) =&amp;gt;&lt;br /&gt;                                      {&lt;br /&gt;                                          new Thread(() =&amp;gt;&lt;br /&gt;                                                         {&lt;br /&gt;                                                             for (int i = 0; i &amp;lt; 3; i++)&lt;br /&gt;                                                             {&lt;br /&gt;                                                                 Thread.Sleep(2000);&lt;br /&gt;                                                                 o.OnNext(new Server()&lt;br /&gt;                                                                              {ServerStatus = "Connected"});&lt;br /&gt;                                                             }&lt;br /&gt;&lt;br /&gt;                                                             o.OnError(new Exception("Server Disconnected"));&lt;br /&gt;                                                             //o.OnCompleted();&lt;br /&gt;                                                         }) {IsBackground = true}.Start();&lt;br /&gt;&lt;br /&gt;                                          return () =&amp;gt;&lt;br /&gt;                                                     {&lt;br /&gt;                                                         ConnectionStatusMessage =&lt;br /&gt;                                                             "Running Disconnect Procedure!";&lt;br /&gt;&lt;br /&gt;                                                         Thread.Sleep(2000);&lt;br /&gt;&lt;br /&gt;                                                         ConnectionStatusMessage = "Disconnected";&lt;br /&gt;                                                     };&lt;br /&gt;                                      });&lt;br /&gt;&lt;br /&gt;    IObservable&amp;lt;Server&amp;gt; observableServerConnection2 =&lt;br /&gt;        Observable.Create&amp;lt;Server&amp;gt;((o) =&amp;gt;&lt;br /&gt;        {&lt;br /&gt;            new Thread(() =&amp;gt;&lt;br /&gt;            {&lt;br /&gt;                for (int i = 0; i &amp;lt; 3; i++)&lt;br /&gt;                {&lt;br /&gt;                    Thread.Sleep(2000);&lt;br /&gt;                    o.OnNext(new Server() { ServerStatus = "Connected" });&lt;br /&gt;                }&lt;br /&gt;&lt;br /&gt;                o.OnError(new Exception("Server Disconnected2"));&lt;br /&gt;                //o.OnCompleted();&lt;br /&gt;            }) { IsBackground = true }.Start();&lt;br /&gt;&lt;br /&gt;            return () =&amp;gt;&lt;br /&gt;            {&lt;br /&gt;                ConnectionStatusMessage =&lt;br /&gt;                    "Running Disconnect Procedure 2!";&lt;br /&gt;&lt;br /&gt;                Thread.Sleep(2000);&lt;br /&gt;&lt;br /&gt;                ConnectionStatusMessage = "Disconnected2";&lt;br /&gt;            };&lt;br /&gt;        });&lt;br /&gt;&lt;br /&gt;    IObserver&amp;lt;Server&amp;gt; observer =&lt;br /&gt;        Observer.Create&amp;lt;Server&amp;gt;(&lt;br /&gt;            (server) =&amp;gt; this.ConnectionStatusMessage = server.ServerStatus,&lt;br /&gt;            (ex) =&amp;gt;&lt;br /&gt;                {&lt;br /&gt;                    this.ConnectionStatusMessage = "Getting Disconnected";&lt;br /&gt;                    Thread.Sleep(2000);&lt;br /&gt;                });&lt;br /&gt;    &lt;br /&gt;    //observableServerConnection.Subscribe(observer);&lt;br /&gt;    &lt;br /&gt;    observableServerConnection.Retry(2).Catch&amp;lt;Server&amp;gt;(observableServerConnection2).Subscribe(observer);&lt;br /&gt;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;The view goes through these steps when application is run:&lt;br /&gt;&lt;br /&gt;    - &lt;span style="font-style:italic;"&gt;Connected&lt;/span&gt;&lt;br /&gt;    - &lt;span style="font-style:italic;"&gt;Running Disconnect Procedure!&lt;/span&gt;&lt;br /&gt;    - &lt;span style="font-style:italic;"&gt;Disconnected&lt;/span&gt;&lt;br /&gt;    - &lt;span style="font-style:italic;"&gt;Connected&lt;/span&gt;&lt;br /&gt;    - &lt;span style="font-style:italic;"&gt;Running Disconnect Procedure!&lt;/span&gt;&lt;br /&gt;    - &lt;span style="font-style:italic;"&gt;Disconnected&lt;/span&gt;&lt;br /&gt;    - &lt;span style="font-style:italic;"&gt;Connected&lt;/span&gt;&lt;br /&gt;    - &lt;span style="font-style:italic;"&gt;Getting Disconnected&lt;/span&gt;&lt;br /&gt;    - &lt;span style="font-style:italic;"&gt;Running Disconnect Procedure 2!&lt;/span&gt;&lt;br /&gt;    - &lt;span style="font-style:italic;"&gt;Disconnected2&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Download:&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;iframe title ="Preview" scrolling="no" marginheight="0" marginwidth="0" frameborder="0" style="width:98px;height:115px;padding:0;background-color:#fcfcfc;" src="http://cid-b5fee7d7acde5072.office.live.com/embedicon.aspx/MVVM%20Retry%20^0%20Catch/Wpf^_MVVM^_Observables^_Final.zip"&gt;&lt;/iframe&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8085117242240449595-5592487212238566545?l=www.shujaat.net' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.shujaat.net/feeds/5592487212238566545/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8085117242240449595&amp;postID=5592487212238566545&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/5592487212238566545'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/5592487212238566545'/><link rel='alternate' type='text/html' href='http://www.shujaat.net/2011/02/wpf-mvvm-retry-catch-for-observables-in.html' title='WPF MVVM - Retry &amp; Catch for Observables in Reactive Extension Rx'/><author><name>Muhammad Shujaat Siddiqi</name><uri>http://www.blogger.com/profile/02519138704633566929</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://4.bp.blogspot.com/-tYMxhzmG4IE/TVtQXCl-6BI/AAAAAAAAA1o/7JIOjJZx_sQ/s72-c/1.jpg' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8085117242240449595.post-4986357128431580047</id><published>2011-02-13T11:49:00.018-06:00</published><updated>2011-02-13T18:07:31.834-06:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='MVVM'/><category scheme='http://www.blogger.com/atom/ns#' term='Rx'/><category scheme='http://www.blogger.com/atom/ns#' term='Model'/><category scheme='http://www.blogger.com/atom/ns#' term='IObserver'/><category scheme='http://www.blogger.com/atom/ns#' term='reactive extensions'/><category scheme='http://www.blogger.com/atom/ns#' term='linq to IObservable'/><category scheme='http://www.blogger.com/atom/ns#' term='linq'/><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><category scheme='http://www.blogger.com/atom/ns#' term='Reactive extension'/><category scheme='http://www.blogger.com/atom/ns#' term='View Model'/><category scheme='http://www.blogger.com/atom/ns#' term='IObsevable'/><title type='text'>MVVM - Joining Rx's IObservables using LINQ to IObservable in a WPF Application</title><content type='html'>In this post, we will see how we can combine two &lt;span style="font-style:italic;"&gt;IObservable&lt;/span&gt;(s) using &lt;span style="font-style:italic;"&gt;LINQ&lt;/span&gt;. The project is developed on top of the code as developed in this post:&lt;br /&gt;&lt;br /&gt;&lt;a href="http://shujaatsiddiqi.blogspot.com/2011/02/mvvm-view-model-iobserver-observing.html"&gt;http://shujaatsiddiqi.blogspot.com/2011/02/mvvm-view-model-iobserver-observing.html&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;We will just be discussing the changes required for this example. For the discussion of complete code please refer to the link provided above.&lt;br /&gt;&lt;br /&gt;As in the previous post, the view model will be observing the data streams from to IObservable. It needs to combine them both using &lt;span style="font-style:italic;"&gt;LINQ &lt;/span&gt;(as specified above). It would be interesting as we would see how data is combined when data is pushed by the &lt;span style="font-style:italic;"&gt;IObservable&lt;/span&gt;. As soon as the data is available, it would automatically combine it using different operators provided by &lt;span style="font-style:italic;"&gt;Reactive Extensions&lt;/span&gt; (Rx). Since we don't need to display data separately in the view, we update the view just to have one &lt;span style="font-style:italic;"&gt;ListBox&lt;/span&gt;. The ListBox should show Id and Name of each Student. It should also show the name of the course the student is enrolled in, which could be obtained from observing &lt;span style="font-style:italic;"&gt;CourseModel&lt;/span&gt;.&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://4.bp.blogspot.com/-s25kOZuIahw/TVgZp2duq7I/AAAAAAAAA0o/ApMnOEhmkZc/s1600/1.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 267px;" src="http://4.bp.blogspot.com/-s25kOZuIahw/TVgZp2duq7I/AAAAAAAAA0o/ApMnOEhmkZc/s400/1.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5573232745656527794" /&gt;&lt;/a&gt;&lt;br /&gt;After completion of data stream, the use should be notified by changing the Fill color of ellipse as green. The expected final display is shown as follows:&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://4.bp.blogspot.com/-1l4zYLoLQNg/TVgZycA8WoI/AAAAAAAAA0w/PA_9ZILK6lc/s1600/2.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 267px;" src="http://4.bp.blogspot.com/-1l4zYLoLQNg/TVgZycA8WoI/AAAAAAAAA0w/PA_9ZILK6lc/s400/2.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5573232893175290498" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;To update the view as described above, we need to update the design of the view as follows:&lt;br /&gt;&lt;pre class="brush: xml; gutter: false;"&gt;&lt;br /&gt;&amp;lt;Window x:Class="WpfApp_MVVM_ReactiveModel.MainWindow"&lt;br /&gt;        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"&lt;br /&gt;        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&lt;br /&gt;        xmlns:local="clr-namespace:WpfApp_MVVM_ReactiveModel"&lt;br /&gt;        Title="MainWindow" Height="350" Width="525" &amp;gt;    &lt;br /&gt;    &amp;lt;Window.DataContext&amp;gt;&lt;br /&gt;        &amp;lt;local:MainWindowViewModel /&amp;gt;&lt;br /&gt;    &amp;lt;/Window.DataContext&amp;gt;   &lt;br /&gt;    &amp;lt;Grid&amp;gt;       &lt;br /&gt;        &amp;lt;ListBox Height="250" HorizontalAlignment="Left" Margin="-2,0,0,0" &lt;br /&gt;                 Name="listBox1" VerticalAlignment="Top" Width="493" &lt;br /&gt;                 ItemsSource="{Binding StudentList}"&amp;gt;&lt;br /&gt;            &amp;lt;ListBox.ItemTemplate&amp;gt;&lt;br /&gt;                &amp;lt;DataTemplate &amp;gt;&lt;br /&gt;                    &amp;lt;StackPanel Orientation="Horizontal"&amp;gt;&lt;br /&gt;                        &amp;lt;TextBlock Text="{Binding StudentId, StringFormat=Id:{0}}" /&amp;gt;&lt;br /&gt;                        &amp;lt;TextBlock Text="       " /&amp;gt;&lt;br /&gt;                        &amp;lt;TextBlock Text="{Binding StudentName, StringFormat=Name:{0}}" /&amp;gt;&lt;br /&gt;                        &amp;lt;TextBlock Text="       " /&amp;gt;&lt;br /&gt;                        &amp;lt;TextBlock Text="{Binding CourseName, StringFormat=Name:{0}}" /&amp;gt;&lt;br /&gt;                    &amp;lt;/StackPanel&amp;gt;&lt;br /&gt;                &amp;lt;/DataTemplate&amp;gt;&lt;br /&gt;            &amp;lt;/ListBox.ItemTemplate&amp;gt;&lt;br /&gt;        &amp;lt;/ListBox&amp;gt;&lt;br /&gt;        &amp;lt;Ellipse Height="39" HorizontalAlignment="Left" Margin="370,257,0,0" &lt;br /&gt;                 Name="ellipse1" Stroke="Black" VerticalAlignment="Top" Width="116" &amp;gt;&lt;br /&gt;            &amp;lt;Ellipse.Style&amp;gt;                &lt;br /&gt;                &amp;lt;Style TargetType="{x:Type Ellipse}"&amp;gt;&lt;br /&gt;                    &amp;lt;Style.Setters&amp;gt;&lt;br /&gt;                        &amp;lt;Setter Property="Fill" Value ="Blue" /&amp;gt;&lt;br /&gt;                    &amp;lt;/Style.Setters&amp;gt;&lt;br /&gt;                    &amp;lt;Style.Triggers&amp;gt;&lt;br /&gt;                        &amp;lt;DataTrigger Binding="{Binding IsLoaded}" Value="true" &amp;gt;&lt;br /&gt;                            &amp;lt;Setter Property="Fill" Value="Green" /&amp;gt;&lt;br /&gt;                        &amp;lt;/DataTrigger&amp;gt;&lt;br /&gt;                    &amp;lt;/Style.Triggers&amp;gt;&lt;br /&gt;                &amp;lt;/Style&amp;gt;&lt;br /&gt;            &amp;lt;/Ellipse.Style&amp;gt;&lt;br /&gt;        &amp;lt;/Ellipse&amp;gt;&lt;br /&gt;    &amp;lt;/Grid&amp;gt;&lt;br /&gt;&amp;lt;/Window&amp;gt;&lt;/pre&gt;&lt;br /&gt;The view is still using &lt;span style="font-style:italic;"&gt;MainWindowViewModel &lt;/span&gt;as &lt;span style="font-style:italic;"&gt;DataContext&lt;/span&gt;. You can see that an additional TextBlock is added to the template of items of ListBox. It is bound to &lt;span style="font-style:italic;"&gt;CourseName&lt;/span&gt; from each item of the collection bound to the list box. The DataContext is expected to have a collection &lt;span style="font-style:italic;"&gt;StudentList &lt;/span&gt;with items having properties &lt;span style="font-style:italic;"&gt;StudentId&lt;/span&gt;, &lt;span style="font-style:italic;"&gt;StudentName &lt;/span&gt;and &lt;span style="font-style:italic;"&gt;CourseName&lt;/span&gt;. This is implemented as an &lt;span style="font-style:italic;"&gt;ObservableCollection &lt;/span&gt;so that as the items are entered in the collection, the view could update itself using the notification mechanism built-in for this type of collection. It should also have a boolean property, &lt;span style="font-style:italic;"&gt;IsDataLoaded&lt;/span&gt;. It should turn true when data is completely loaded. This is used in &lt;span style="font-style:italic;"&gt;DataTrigger&lt;/span&gt; in the view to turn the notification ellipse to be filled as &lt;span style="font-style:italic;"&gt;Green&lt;/span&gt;. We need to implement &lt;span style="font-style:italic;"&gt;INotifyPropertyChanged&lt;/span&gt; just because of this property so that view can be notified for this change and the data triggered could trigger the fill color of the ellipse.&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;class MainWindowViewModel : INotifyPropertyChanged&lt;br /&gt;{&lt;br /&gt;    private readonly ObservableCollection&amp;lt;StudentViewModel&amp;gt; _studentList = &lt;br /&gt;        new ObservableCollection&amp;lt;StudentViewModel&amp;gt;();&lt;br /&gt;&lt;br /&gt;    public ObservableCollection&amp;lt;StudentViewModel&amp;gt; StudentList&lt;br /&gt;    {&lt;br /&gt;        get { return _studentList; }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private bool _isLoaded = false;&lt;br /&gt;    public bool IsLoaded&lt;br /&gt;    {&lt;br /&gt;        get { return _isLoaded; }&lt;br /&gt;        set &lt;br /&gt;        {&lt;br /&gt;            _isLoaded = value;&lt;br /&gt;            onPropertyChanged("IsLoaded");&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public MainWindowViewModel()&lt;br /&gt;    {&lt;br /&gt;        var courseModel2 = new CourseModel();&lt;br /&gt;        var studentModel2 = new StudentsModel();&lt;br /&gt;&lt;br /&gt;        (from c in courseModel2&lt;br /&gt;         from s in studentModel2&lt;br /&gt;         where s.CourseId == c.CourseId&lt;br /&gt;         select new { s.StudentName, s.StudentId, c.CourseName })&lt;br /&gt;            .Subscribe(&lt;br /&gt;                (on) =&amp;gt; _studentList.Add(new StudentViewModel(on)),&lt;br /&gt;                (ex) =&amp;gt; Console.WriteLine(@"On error"),&lt;br /&gt;                () =&amp;gt; IsLoaded = true);&lt;br /&gt;     &lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    #region INotifyPropertyChanged implementation&lt;br /&gt;    public event PropertyChangedEventHandler PropertyChanged;&lt;br /&gt;    private void onPropertyChanged(string propertyname)&lt;br /&gt;    {&lt;br /&gt;        if (PropertyChanged != null)&lt;br /&gt;        {&lt;br /&gt;            PropertyChanged(this, new PropertyChangedEventArgs(propertyname));&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;    #endregion INotifyPropertyChanged implementation&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;The focal point of this post is the constructor of &lt;span style="font-style:italic;"&gt;MainWindowViewModel&lt;/span&gt;. Here we are combining to IObservable based collections using LINQ. This is a special new flavor of &lt;span style="font-style:italic;"&gt;LINQ &lt;/span&gt;released with &lt;span style="font-style:italic;"&gt;Rx&lt;/span&gt;. This is called &lt;span style="font-style:italic;"&gt;LINQ to IObservable&lt;/span&gt;. This is available in &lt;span style="font-style:italic;"&gt;System.Reactive&lt;/span&gt; assembly. Let's have a close look at the constructor.&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&gt;&lt;br /&gt;public MainWindowViewModel()&lt;br /&gt;{&lt;br /&gt;    var courseModel2 = new CourseModel();&lt;br /&gt;    var studentModel2 = new StudentsModel();&lt;br /&gt;&lt;br /&gt;    (from c in courseModel2&lt;br /&gt;     from s in studentModel2&lt;br /&gt;     where s.CourseId == c.CourseId&lt;br /&gt;     select new { s.StudentName, s.StudentId, c.CourseName })&lt;br /&gt;        .Subscribe(&lt;br /&gt;            (on) =&gt; _studentList.Add(new StudentViewModel(on)),&lt;br /&gt;            (ex) =&gt; Console.WriteLine(@"On error"),&lt;br /&gt;            () =&gt; IsLoaded = true);&lt;br /&gt; &lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;So we are cross-joining instances of &lt;span style="font-style:italic;"&gt;CourseModel &lt;/span&gt;and &lt;span style="font-style:italic;"&gt;StudentsModel&lt;/span&gt;. This would be creating a Cartesian Product. We are filtering it for only those which have matching &lt;span style="font-style:italic;"&gt;CourseId&lt;/span&gt;(s). &lt;br /&gt;&lt;br /&gt;As specified in the definition of the view, we are interested in &lt;span style="font-style:italic;"&gt;StudentId &lt;/span&gt;and &lt;span style="font-style:italic;"&gt;StudentName &lt;/span&gt;from &lt;span style="font-style:italic;"&gt;StudentsModel &lt;/span&gt;and &lt;span style="font-style:italic;"&gt;CourseName &lt;/span&gt;from &lt;span style="font-style:italic;"&gt;CourseModel&lt;/span&gt;. &lt;br /&gt;&lt;br /&gt;The cross product of Cartesian Product of two or more &lt;span style="font-style:italic;"&gt;IObservable&lt;/span&gt;(s) is also an &lt;span style="font-style:italic;"&gt;IObservable&lt;/span&gt;. This enables us to subscribe to it by providing the &lt;span style="font-style:italic;"&gt;OnNext&lt;/span&gt;, &lt;span style="font-style:italic;"&gt;OnCompleted &lt;/span&gt;and &lt;span style="font-style:italic;"&gt;OnError &lt;/span&gt;of Observer. It is to remember that &lt;span style="font-style:italic;"&gt;MainWindowViewModel &lt;/span&gt;is not the observable for the new &lt;span style="font-style:italic;"&gt;IObservable &lt;/span&gt;created by combining &lt;span style="font-style:italic;"&gt;CourseModel &lt;/span&gt;and &lt;span style="font-style:italic;"&gt;StudentsModel&lt;/span&gt;. Rx run-time would take care of how the provided lambda expressions for &lt;span style="font-style:italic;"&gt;OnNext&lt;/span&gt;, &lt;span style="font-style:italic;"&gt;OnCompleted &lt;/span&gt;and &lt;span style="font-style:italic;"&gt;OnError &lt;/span&gt;are to be executed. &lt;br /&gt;&lt;br /&gt;The overload of Subscribe method that we have used takes three arguments &lt;span style="font-style:italic;"&gt;OnNext&lt;/span&gt;, &lt;span style="font-style:italic;"&gt;OnError &lt;/span&gt;and &lt;span style="font-style:italic;"&gt;OnCompleted &lt;/span&gt;respectively. We are not doing anything useful in the lambda expression provided for &lt;span style="font-style:italic;"&gt;OnError&lt;/span&gt; except just writing on the exception message on the console. In the &lt;span style="font-style:italic;"&gt;OnCompleted &lt;/span&gt;expressoin we are setting &lt;span style="font-style:italic;"&gt;IsLoaded &lt;/span&gt;to true. This would trigger the DataTrigger in the view and change the fill color of Notification ellipse to Green. The type of parameter of &lt;span style="font-style:italic;"&gt;OnNext &lt;/span&gt;is the anonymous type created for &lt;span style="font-style:italic;"&gt;Select&lt;/span&gt;. This would have same elements with similar names. As we have data available in OnNext, we are creating a &lt;span style="font-style:italic;"&gt;StudentViewModel &lt;/span&gt;object and add it to the &lt;span style="font-style:italic;"&gt;StudentsList ObservableCollection &lt;/span&gt;. This is bound to the &lt;span style="font-style:italic;"&gt;ListBox &lt;/span&gt;in the view which would show this new element. Though we can not use foreach for IObservable as it is a feature of just &lt;span style="font-style:italic;"&gt;IEnumerable&lt;/span&gt;, we can understand it by this nested &lt;span style="font-style:italic;"&gt;foreach &lt;/span&gt;loop. Don't even try this:&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://4.bp.blogspot.com/-AGPeu_GjGKo/TVhSBeaAWOI/AAAAAAAAA1A/dN3exMoKOlY/s1600/4.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 175px;" src="http://4.bp.blogspot.com/-AGPeu_GjGKo/TVhSBeaAWOI/AAAAAAAAA1A/dN3exMoKOlY/s400/4.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5573294724166473954" /&gt;&lt;/a&gt;&lt;br /&gt;Since the combined collections have &lt;span style="font-style:italic;"&gt;IObservable &lt;/span&gt;based, we don't have the data available at the same time. This makes it very special form of joining. This would keep each element of &lt;span style="font-style:italic;"&gt;courseModel2 &lt;/span&gt;in memory until &lt;span style="font-style:italic;"&gt;OnCompleted &lt;/span&gt;is not executed from &lt;span style="font-style:italic;"&gt;studentModel2&lt;/span&gt;. As the elements are being received in background &lt;span style="font-style:italic;"&gt;OnNext &lt;/span&gt;for &lt;span style="font-style:italic;"&gt;studentModel &lt;/span&gt;they are combined with each element of courseModel. This would be creating equal number of &lt;span style="font-style:italic;"&gt;Observers &lt;/span&gt;for &lt;span style="font-style:italic;"&gt;studentModel2 &lt;/span&gt;as the total number of elements pushed by &lt;span style="font-style:italic;"&gt;courseModel2&lt;/span&gt;. As the elements of courseModel2 continue to be received they are added to the list of &lt;span style="font-style:italic;"&gt;Observers &lt;/span&gt;of &lt;span style="font-style:italic;"&gt;studentModel2&lt;/span&gt;.&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://1.bp.blogspot.com/-GurlPc61KN4/TVhLx8dH3UI/AAAAAAAAA04/yr3frGyZxeI/s1600/3.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 195px;" src="http://1.bp.blogspot.com/-GurlPc61KN4/TVhLx8dH3UI/AAAAAAAAA04/yr3frGyZxeI/s400/3.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5573287860284939586" /&gt;&lt;/a&gt;&lt;br /&gt;We should be able to safely make a summarized statement about it as follows:&lt;br /&gt;&lt;span style="font-style:italic;"&gt;&lt;br /&gt;All the elements pushed through &lt;span style="font-style:italic;"&gt;OnNext &lt;/span&gt;of &lt;span style="font-style:italic;"&gt;courseModel2 &lt;/span&gt;would be combined with all the elements pushed by &lt;span style="font-style:italic;"&gt;studentModel2&lt;/span&gt;. If there is any OnNext of either of these &lt;span style="font-style:italic;"&gt;IObservable &lt;/span&gt;before this &lt;span style="font-style:italic;"&gt;LINQ&lt;/span&gt;, that would not be considered for joining.&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;As soon as the &lt;span style="font-style:italic;"&gt;OnCompleted &lt;/span&gt;is executed for this Observer created at runtime, it would automatically unsubscribe it by disposing itself. As we have seen in previous posts that disposing an unsubscriber would result in its &lt;span style="font-style:italic;"&gt;unsubscription&lt;/span&gt;. I think this is the default implementation provided for this dynamic &lt;span style="font-style:italic;"&gt;Observer &lt;/span&gt;by Rx runtime.&lt;br /&gt;&lt;br /&gt;This would need updates in &lt;span style="font-style:italic;"&gt;StudentViewModel&lt;/span&gt;. We need to add a property CourseName as used in &lt;span style="font-style:italic;"&gt;MainWindowViewModel&lt;/span&gt;. There is one more interesting thing, the datatype of parameter for constructor is specified as &lt;span style="font-style:italic;"&gt;dynamic&lt;/span&gt;. This is basically because of anonymous type constructed during &lt;span style="font-style:italic;"&gt;LINQ &lt;/span&gt;operation. In the constructor, we are using it as a duck type datatype, we know what properties would it have but we don't know it's name as it would be assigned any arbitrary name at run-time. This is a special feature of .net framework 4.0 [&lt;a href="http://msdn.microsoft.com/en-us/library/dd264736.aspx"&gt;http://msdn.microsoft.com/en-us/library/dd264736.aspx&lt;/a&gt;].&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;class StudentViewModel : INotifyPropertyChanged&lt;br /&gt;{&lt;br /&gt;    public StudentViewModel(dynamic student)&lt;br /&gt;    {&lt;br /&gt;        this.StudentId = student.StudentId;&lt;br /&gt;        this.StudentName = student.StudentName;&lt;br /&gt;        this.CourseName = student.CourseName;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private string _courseName;&lt;br /&gt;    public string CourseName&lt;br /&gt;    {&lt;br /&gt;        get { return _courseName; }&lt;br /&gt;        set &lt;br /&gt;        { &lt;br /&gt;            _courseName = value;&lt;br /&gt;            OnPropertyChanged("CourseName");&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private string _studentName;&lt;br /&gt;    public string StudentName&lt;br /&gt;    {&lt;br /&gt;        get { return _studentName; }&lt;br /&gt;        set &lt;br /&gt;        { &lt;br /&gt;            _studentName = value;&lt;br /&gt;            OnPropertyChanged("StudentName");&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private int _studentId;&lt;br /&gt;    public int StudentId&lt;br /&gt;    {&lt;br /&gt;        get { return _studentId; }&lt;br /&gt;        set&lt;br /&gt;        {&lt;br /&gt;            _studentId = value;&lt;br /&gt;            OnPropertyChanged("StudentId");&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    #region INotifyPropertyChanged implementation&lt;br /&gt;&lt;br /&gt;        public event PropertyChangedEventHandler  PropertyChanged;&lt;br /&gt;        private void OnPropertyChanged(string propertyName)&lt;br /&gt;        {&lt;br /&gt;            if (PropertyChanged != null)&lt;br /&gt;            {&lt;br /&gt;                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        #endregion INotifyPropertyChanged implementation&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;So we need to update Student to add a new property, CourseId. This would be used as a key to join &lt;span style="font-style:italic;"&gt;StudentsModel &lt;/span&gt;and &lt;span style="font-style:italic;"&gt;CourseModel &lt;/span&gt;IObservable collections. This is &lt;span style="font-style:italic;"&gt;int &lt;/span&gt;type.&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&gt;&lt;br /&gt;class Student &lt;br /&gt;{&lt;br /&gt;    public string StudentName { get; set; }&lt;br /&gt;    public int StudentId { get; set; }&lt;br /&gt;    public int CourseId { get; set; }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;Since we have updated &lt;span style="font-style:italic;"&gt;Student &lt;/span&gt;type, we need to update the definition for &lt;span style="font-style:italic;"&gt;StudentsModel&lt;/span&gt;. This is to specify value of CourseId. We are just deriving it based on a algorithm [If _studentId is odd then set CourseId as 2, otherwise, set it as 1]. We are also reducing the number of times that timer event would execute. You can see that we are calling Observer's &lt;span style="font-style:italic;"&gt;OnCompleted &lt;/span&gt;just when the event has been executed 3 times. As we call OnCompleted on Observer, we are also stopping the timer, this would not keep the timer running on the background.&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&gt;&lt;br /&gt;class StudentsModel : IObservable&amp;lt;Student&amp;gt;&lt;br /&gt;{&lt;br /&gt;    private int _studentId = 1;&lt;br /&gt;&lt;br /&gt;    //Timer to notify observers about updates in the reactive observable&lt;br /&gt;    private readonly DispatcherTimer _t = new DispatcherTimer();&lt;br /&gt;&lt;br /&gt;    public List&amp;lt;IObserver&amp;lt;Student&amp;gt;&amp;gt; Observers = &lt;br /&gt;        new List&amp;lt;IObserver&amp;lt;Student&amp;gt;&amp;gt;();&lt;br /&gt;&lt;br /&gt;    public StudentsModel()&lt;br /&gt;    {&lt;br /&gt;        _t.Interval = TimeSpan.FromMilliseconds(3000);&lt;br /&gt;        _t.Tick += new EventHandler(Tick);&lt;br /&gt;        _t.Start();&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    void Tick(object sender, EventArgs e)&lt;br /&gt;    {&lt;br /&gt;        var student = new Student()&lt;br /&gt;                          {&lt;br /&gt;                              StudentId = _studentId,&lt;br /&gt;                              StudentName = string.Format("Student: {0}", _studentId),&lt;br /&gt;                              CourseId = ((int)(_studentId % 2)) + 1&lt;br /&gt;                          };&lt;br /&gt;&lt;br /&gt;        if (_studentId &lt;= 3)&lt;br /&gt;        {&lt;br /&gt;            Observers.ForEach((observer) =&gt; observer.OnNext(student));&lt;br /&gt;            _studentId++;&lt;br /&gt;        }&lt;br /&gt;        else&lt;br /&gt;        {&lt;br /&gt;            Observers.ForEach((observer) =&gt; observer.OnCompleted());&lt;br /&gt;            _t.Stop();&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public IDisposable Subscribe(IObserver&amp;lt;Student&amp;gt; observer)&lt;br /&gt;    {&lt;br /&gt;        IDisposable unSubscriber = new Unsubscriber&amp;lt;Student&amp;gt;(Observers, observer);&lt;br /&gt;        if (!Observers.Contains(observer))&lt;br /&gt;        {&lt;br /&gt;            Observers.Add(observer);&lt;br /&gt;        }&lt;br /&gt;        return unSubscriber;&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Now Let's run the application. The application runs successfully and we see the elements being added to the list box. &lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://3.bp.blogspot.com/-ZO_28q2jRyg/TVhWp7s5gJI/AAAAAAAAA1I/RS-wWMffRW0/s1600/5.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 267px;" src="http://3.bp.blogspot.com/-ZO_28q2jRyg/TVhWp7s5gJI/AAAAAAAAA1I/RS-wWMffRW0/s400/5.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5573299817271623826" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;But there is a weird thing. The notification ellipse is still filled as blue. It should have turned Green if &lt;span style="font-style:italic;"&gt;OnCompleted &lt;/span&gt;of the &lt;span style="font-style:italic;"&gt;LINQ &lt;/span&gt;result is executed in &lt;span style="font-style:italic;"&gt;MainWindowViewModel&lt;/span&gt;. It means that &lt;span style="font-style:italic;"&gt;OnCompleted &lt;/span&gt;,for this, is not executed. You can prove that by inserting break point in the lambda expression used for &lt;span style="font-style:italic;"&gt;OnCompleted&lt;/span&gt;. But the main question is why it is not executed??&lt;br /&gt;&lt;br /&gt;Basically, we have discussed that equal numbers of Observers would be created for studentModel2 as the number of elements pushed by courseModel2 after the LINQ statment is executed. So there are will be two observers for this. If we insert break-point in the Tick event handler for timer &lt;span style="font-style:italic;"&gt;_t&lt;/span&gt; in &lt;span style="font-style:italic;"&gt;StudentsModel &lt;/span&gt;then we realize that &lt;span style="font-style:italic;"&gt;OnCompleted &lt;/span&gt;is executed only once. We need to execute &lt;span style="font-style:italic;"&gt;OnCompleted &lt;/span&gt;for all observers to fix this. This is really weird because we are using &lt;span style="font-style:italic;"&gt;Foreach &lt;/span&gt;on &lt;span style="font-style:italic;"&gt;Obsevers &lt;/span&gt;List. It should have executed the &lt;span style="font-style:italic;"&gt;OnCompleted &lt;/span&gt; for all observers. There should have been no Observer in the list before next statement is executed [&lt;span style="font-style:italic;"&gt;_t.Stop()&lt;/span&gt;]. But if we put a break point then it seems that OnCompleted is executed only once as one Observer is still lingering on.&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://1.bp.blogspot.com/-9NtlqQ46_X4/TVheBnc4vkI/AAAAAAAAA1Q/IQan_hDaqMM/s1600/6.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 249px;" src="http://1.bp.blogspot.com/-9NtlqQ46_X4/TVheBnc4vkI/AAAAAAAAA1Q/IQan_hDaqMM/s400/6.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5573307920734010946" /&gt;&lt;/a&gt;&lt;br /&gt;This seems to get fixed if we update the code as follows:&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;void Tick(object sender, EventArgs e)&lt;br /&gt;{&lt;br /&gt;    var student = new Student()&lt;br /&gt;                      {&lt;br /&gt;                          StudentId = _studentId,&lt;br /&gt;                          StudentName = string.Format("Student: {0}", _studentId),&lt;br /&gt;                          CourseId = ((int)(_studentId % 2)) + 1&lt;br /&gt;                      };&lt;br /&gt;&lt;br /&gt;    if (_studentId &lt;= 3)&lt;br /&gt;    {&lt;br /&gt;        Observers.ForEach((observer) =&gt; observer.OnNext(student));&lt;br /&gt;        _studentId++;&lt;br /&gt;    }&lt;br /&gt;    else&lt;br /&gt;    {&lt;br /&gt;        Observers.ToList().ForEach((observer) =&gt; observer.OnCompleted());                &lt;br /&gt;        _t.Stop();&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Now run this and insert the break point appropriately.&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://3.bp.blogspot.com/-CWXzHDVNPQg/TVheqCYo8EI/AAAAAAAAA1Y/eKa0AO-0MiU/s1600/7.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 239px;" src="http://3.bp.blogspot.com/-CWXzHDVNPQg/TVheqCYo8EI/AAAAAAAAA1Y/eKa0AO-0MiU/s400/7.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5573308615158722626" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;We have just called ToList() on a collection which is already a Generic List to fix this. This shows some issue with the deferred execution of Lambdas of &lt;span style="font-style:italic;"&gt;foreach&lt;/span&gt; here, which is executing &lt;span style="font-style:italic;"&gt;OnCompleted&lt;/span&gt; for each observer. This would definitely introduce some performance delay but whatever works...  &lt;br /&gt;&lt;br /&gt;Now since all the OnCompleted have been executed for all the collections involved in the LINQ query, it is safe to executed the &lt;span style="font-style:italic;"&gt;OnCompleted &lt;/span&gt;of the result. Rx runtime does exactly that. This sets IsLoaded to true and results in filling the Notification ellipse as Green.&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://2.bp.blogspot.com/-FIotIZ99GB8/TVhf4zGk-BI/AAAAAAAAA1g/IStzKy75qCY/s1600/8.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 267px;" src="http://2.bp.blogspot.com/-FIotIZ99GB8/TVhf4zGk-BI/AAAAAAAAA1g/IStzKy75qCY/s400/8.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5573309968266098706" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Download Code:&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;iframe title ="Preview" scrolling="no" marginheight="0" marginwidth="0" frameborder="0" style="width:98px;height:115px;padding:0;background-color:#fcfcfc;" src="http://cid-b5fee7d7acde5072.office.live.com/embedicon.aspx/MVVM%20Rx%20Linq%20to%20IObservable/WpfApp^_MVVM^_ReactiveModel.zip"&gt;&lt;/iframe&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8085117242240449595-4986357128431580047?l=www.shujaat.net' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.shujaat.net/feeds/4986357128431580047/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8085117242240449595&amp;postID=4986357128431580047&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/4986357128431580047'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/4986357128431580047'/><link rel='alternate' type='text/html' href='http://www.shujaat.net/2011/02/wpf-joining-rxs-iobservables-using-linq.html' title='MVVM - Joining Rx&apos;s IObservables using LINQ to IObservable in a WPF Application'/><author><name>Muhammad Shujaat Siddiqi</name><uri>http://www.blogger.com/profile/02519138704633566929</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://4.bp.blogspot.com/-s25kOZuIahw/TVgZp2duq7I/AAAAAAAAA0o/ApMnOEhmkZc/s72-c/1.jpg' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8085117242240449595.post-1002046634202115131</id><published>2011-02-10T21:24:00.022-06:00</published><updated>2011-02-11T02:13:20.294-06:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='MVVM'/><category scheme='http://www.blogger.com/atom/ns#' term='Rx'/><category scheme='http://www.blogger.com/atom/ns#' term='IEvent'/><category scheme='http://www.blogger.com/atom/ns#' term='wpf'/><category scheme='http://www.blogger.com/atom/ns#' term='IObserver'/><category scheme='http://www.blogger.com/atom/ns#' term='INotifyPropertyChanged'/><category scheme='http://www.blogger.com/atom/ns#' term='IObservable'/><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><category scheme='http://www.blogger.com/atom/ns#' term='Reactive extension'/><category scheme='http://www.blogger.com/atom/ns#' term='PropertyChanged'/><title type='text'>MVVM - Observable INotifyPropertyChanged.PropertyChanged Event Stream Using Reactive Extension</title><content type='html'>In this post we are going to discuss how we can use observable event streams using &lt;span style="font-style:italic;"&gt;Reactive Extension&lt;/span&gt;. Since we have been trying to apply this knowledge to &lt;span style="font-style:italic;"&gt;MVVM &lt;/span&gt;and seeking what benefit we can obtain from Rx, we will be mostly interested in those events which we deal with the most frequently. One such event is &lt;span style="font-style:italic;"&gt;PropertyChanged &lt;/span&gt;event of &lt;span style="font-style:italic;"&gt;INotifyPropertyChanged&lt;/span&gt;.&lt;br /&gt;&lt;br /&gt;Let’s start with a sample WPF application. As is general in this blog, We will start with a very simple example. Then we will keep adding complexity to it and discuss why we actually need them. Below is a typical WPF window. It just has a button. We need to show another window to enter the details about student.&lt;br /&gt;&lt;pre class="brush: xml; gutter: false;"&gt;&lt;br /&gt;&amp;lt;Window x:Class="WpfApp_MVVM_ReactiveModelSynch.MainWindow"&lt;br /&gt;        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"&lt;br /&gt;        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&lt;br /&gt;        Title="MainWindow" Height="350" Width="525"&amp;gt;&lt;br /&gt;    &amp;lt;Grid&amp;gt;&lt;br /&gt;        &amp;lt;Button Content="Show Student Form" Height="47" HorizontalAlignment="Left"&lt;br /&gt;                Margin="104,244,0,0" Name="button1" VerticalAlignment="Top" Width="318" Click="button1_Click" /&amp;gt;&lt;br /&gt;    &amp;lt;/Grid&amp;gt;&lt;br /&gt;&amp;lt;/Window&amp;gt;&lt;/pre&gt;&lt;br /&gt;Since these details need to be shared between different StudentView windows, we are defining the Student object as instance variable. When user clicks the window, we are constructing the view model on the fly but we keep passing the same Student instance. This would enable the information to be shared between different windows. We are calling Show() on this new instance of StudentView. As you know this would show this window as a Modeless window. This is to demonstrate the scenarios in which we might not instantiate view models inside the view but we need to hand it over, somehow, to the view.&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;public partial class MainWindow : Window&lt;br /&gt;{&lt;br /&gt;    private Student _student;&lt;br /&gt;&lt;br /&gt;    public MainWindow()&lt;br /&gt;    {&lt;br /&gt;        InitializeComponent(); &lt;br /&gt;&lt;br /&gt;        _student = new Student();&lt;br /&gt;    } &lt;br /&gt;&lt;br /&gt;    private void button1_Click(object sender, RoutedEventArgs e)&lt;br /&gt;    {&lt;br /&gt;        new StudentView(new StudentViewModel(_student)).Show();&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://2.bp.blogspot.com/-WwU2IJaSErw/TVSt0uslI8I/AAAAAAAAAzo/SIKol8F9Z5Y/s1600/1.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 267px;" src="http://2.bp.blogspot.com/-WwU2IJaSErw/TVSt0uslI8I/AAAAAAAAAzo/SIKol8F9Z5Y/s400/1.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5572269760363963330" /&gt;&lt;/a&gt;&lt;br /&gt;Now we have a look at the definition of StudentView. It just has two text boxes for user entry. The information regarding Id and Name of Student can be entered in those text boxes. These text boxes are bound to StudentId and StudentName properties from the DataContext.&lt;br /&gt;&lt;pre class="brush: xml; gutter: false;"&gt;&lt;br /&gt;&amp;lt;Window x:Class="WpfApp_MVVM_ReactiveModelSynch.StudentView"&lt;br /&gt;        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"&lt;br /&gt;        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&lt;br /&gt;        Title="StudentView" Height="300" Width="484"&amp;gt;&lt;br /&gt;    &amp;lt;Grid&amp;gt;&lt;br /&gt;        &amp;lt;Label Content="Id" Height="26" HorizontalAlignment="Left" Margin="11,30,0,0"&lt;br /&gt;               Name="labelId" VerticalAlignment="Top" Width="73" /&amp;gt;&lt;br /&gt;        &amp;lt;TextBox Height="26" HorizontalAlignment="Left" Margin="90,30,0,0"&lt;br /&gt;                 Name="textBoxId" VerticalAlignment="Top" Width="362"&lt;br /&gt;                 Text="{Binding Path=StudentId, UpdateSourceTrigger=PropertyChanged}"/&amp;gt;&lt;br /&gt;        &amp;lt;Label Content="Name" Height="25" HorizontalAlignment="Left" Margin="11,76,0,0"&lt;br /&gt;               Name="labelName" VerticalAlignment="Top" Width="73" /&amp;gt;&lt;br /&gt;        &amp;lt;TextBox Height="26" HorizontalAlignment="Left" Margin="90,75,0,0" Name="textBoxName"&lt;br /&gt;                 VerticalAlignment="Top" Width="362"&lt;br /&gt;                 Text="{Binding Path=StudentName, UpdateSourceTrigger=PropertyChanged}"/&amp;gt;&lt;br /&gt;    &amp;lt;/Grid&amp;gt;&lt;br /&gt;&amp;lt;/Window&amp;gt;&lt;/pre&gt;&lt;br /&gt;In the code behind, we assign the view model passed as constructor argument to the DataContext property of the view.&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;public partial class StudentView : Window&lt;br /&gt;{&lt;br /&gt;    public StudentView(StudentViewModel studentViewModel)&lt;br /&gt;    {&lt;br /&gt;        InitializeComponent();&lt;br /&gt;&lt;br /&gt;        this.DataContext = studentViewModel;&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://3.bp.blogspot.com/-DFYFhaN7s0k/TVSvdNUomoI/AAAAAAAAAzw/47kbFIHgZW8/s1600/2.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 248px;" src="http://3.bp.blogspot.com/-DFYFhaN7s0k/TVSvdNUomoI/AAAAAAAAAzw/47kbFIHgZW8/s400/2.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5572271555291421314" /&gt;&lt;/a&gt;&lt;br /&gt;As is expected by the view, StudentViewModel has two properties StudentId and StudentName. Both support change notification using INotifyPropertyChanged’s PropertyChanged event. As is specified in the MainWindow.xaml.cs, we are using Student object as constructor parameter. We are assigning it to the instance variable _model. We are using _model as Model for this view. WPF Binding system would update the values of these properties as the user enters data in the text boxes bound to these properties. In the setters of these properties, we are just assigning these values to the corresponding properties in _model. This should keep model being updated. Since this is shared by the view models used by each StudentView object, we expect the other views to be updated as these changes are applied.&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;public class StudentViewModel : INotifyPropertyChanged&lt;br /&gt;{&lt;br /&gt;    private int _studentId;&lt;br /&gt;    private string _studentName; &lt;br /&gt;&lt;br /&gt;    private Student _model; &lt;br /&gt;&lt;br /&gt;    public StudentViewModel(Student student)&lt;br /&gt;    {&lt;br /&gt;        _model = student;&lt;br /&gt;    } &lt;br /&gt;&lt;br /&gt;    public int StudentId&lt;br /&gt;    {&lt;br /&gt;        get { return _studentId; }&lt;br /&gt;        set&lt;br /&gt;        {&lt;br /&gt;            if (_studentId != value)&lt;br /&gt;            {&lt;br /&gt;                _studentId = value;&lt;br /&gt;                _model.StudentId = value;&lt;br /&gt;                OnPropertyChanged("StudentId");  &lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;    } &lt;br /&gt;&lt;br /&gt;    public string StudentName&lt;br /&gt;    {&lt;br /&gt;        get { return _studentName; }&lt;br /&gt;        set&lt;br /&gt;        {&lt;br /&gt;            if(_studentName != value)&lt;br /&gt;            {&lt;br /&gt;                _studentName = value;&lt;br /&gt;                _model.StudentName = value;&lt;br /&gt;                OnPropertyChanged("StudentName");&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;    } &lt;br /&gt;&lt;br /&gt;    public event PropertyChangedEventHandler PropertyChanged = delegate { };&lt;br /&gt;    private void OnPropertyChanged(string propertyName)&lt;br /&gt;    {&lt;br /&gt;        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;As you might have guessed from the above code, Student has two properties StudentId and StudentName. This also implements INotifyPropertyChanged so needs to define PropertyChanged event. Whenever the values of these properties are changed, PropertyChanged event is raised to notify all observers about this change. Though it does not provide the actual change but it does tell about the property updated. We can handle this event in the code using StudentModel and act accordingly.&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;public class Student : INotifyPropertyChanged&lt;br /&gt;{&lt;br /&gt;    private int _studentId;&lt;br /&gt;    private string _studentName; &lt;br /&gt;&lt;br /&gt;    public int StudentId&lt;br /&gt;    {&lt;br /&gt;        get { return _studentId; }&lt;br /&gt;        set&lt;br /&gt;        {&lt;br /&gt;            if (_studentId != value)&lt;br /&gt;            {&lt;br /&gt;                _studentId = value;&lt;br /&gt;                OnPropertyChanged("StudentId");&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;    } &lt;br /&gt;&lt;br /&gt;    public string StudentName&lt;br /&gt;    {&lt;br /&gt;        get { return _studentName; }&lt;br /&gt;        set&lt;br /&gt;        {&lt;br /&gt;            if (_studentName != value)&lt;br /&gt;            {&lt;br /&gt;                _studentName = value;&lt;br /&gt;                OnPropertyChanged("StudentName");&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;    } &lt;br /&gt;&lt;br /&gt;    public event PropertyChangedEventHandler PropertyChanged = delegate { };&lt;br /&gt;    private void OnPropertyChanged(string propertyName)&lt;br /&gt;    {&lt;br /&gt;        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;Now let’s run this! We open two StudentView windows. We enter data in one window. The data is not being updated in the second window. Why is this?? As is apparent in the code of view model, as we receive updates in View Model’s properties through WPF Binding System, we are passing the same updates to the corresponding properties in the model.&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://4.bp.blogspot.com/-Pb3SIPleX8M/TVS6Uh__kyI/AAAAAAAAAz4/pJs6tsuj-6w/s1600/3.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 148px;" src="http://4.bp.blogspot.com/-Pb3SIPleX8M/TVS6Uh__kyI/AAAAAAAAAz4/pJs6tsuj-6w/s400/3.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5572283500851073826" /&gt;&lt;/a&gt;&lt;br /&gt;If you put break points in the model properties’ setter, you would notice that the setter code is being executed. Even the PropertyChanged event is being raised. We just need to handle this event in the view model so that the view model could update its properties. Since these properties are supporting change notifications using INotifyPropertyChanged, the bound element in the view should also be updated accordingly. As discussed, let’s subscribe PropertyChanged event in the view model for model object.&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;_model.PropertyChanged += new PropertyChangedEventHandler(_model_PropertyChanged);&lt;/pre&gt;&lt;br /&gt;The definition of _model_PropertyChanged is as follows:&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;void _model_PropertyChanged(object sender, PropertyChangedEventArgs e)&lt;br /&gt;{&lt;br /&gt;    object value = _model.GetType().GetProperty(e.PropertyName).GetValue(_model, null);&lt;br /&gt;    this.GetType().GetProperty(e.PropertyName).SetValue(this, value, null);&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;This is based on reflection and based on the assumption that View Model has properties with same names. Their types are also assumed to be supportive. Since we only have limited properties, we can also avoid reflection and update each property. Let’s do that.&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;void _model_PropertyChanged(object sender, PropertyChangedEventArgs e)&lt;br /&gt;{&lt;br /&gt;    this.StudentId = _model.StudentId;&lt;br /&gt;    this.StudentName = _model.StudentName;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;Now let’s run this application. We will again open two windows and enter data in one window and observe if the same updates are made in the second window.&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://1.bp.blogspot.com/-wempwI5qyMw/TVS7XAb-aDI/AAAAAAAAA0A/uw2SxD4ljxs/s1600/4.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 139px;" src="http://1.bp.blogspot.com/-wempwI5qyMw/TVS7XAb-aDI/AAAAAAAAA0A/uw2SxD4ljxs/s400/4.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5572284642892867634" /&gt;&lt;/a&gt;&lt;br /&gt;As expected, the updates are applied in the second window.&lt;br /&gt;&lt;br /&gt;Now since we have fulfilled whatever the requirements have stated, we should be the happiest person in the world. But we can certainly improve on this implementation. We needed to handle model’s &lt;span style="font-style:italic;"&gt;PropertyChanged &lt;/span&gt;event in &lt;span style="font-style:italic;"&gt;StudentViewModel&lt;/span&gt;. We can avoid these by using observable event stream support available in &lt;span style="font-style:italic;"&gt;Reactive Extension (Rx)&lt;/span&gt;. Not only it allows to subscribe to the observable event stream, it also allows a filtered subscription. So We will be subscribing to a subset of events using Where clause even if there is an active event stream.  It is also possible that we are receiving frequent updates from the model, like millions in a second. We don’t want to update our view so frequently.  Similarly, since we have set UpdateSourceTrigger as &lt;span style="font-style:italic;"&gt;PropertyChanged &lt;/span&gt;for both binding in the view. All the changes in the Text property of the text box will cause the property setter to execute. It is possible that the user of this system types very frequently, we might just want to update the model when it settles and not after each key entry. In short we might need throttling support for these property changes.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Using Observable Event Stream for model’s PropertyChanged event:&lt;/span&gt;&lt;br /&gt;Before adding the code described in this section remove model’s &lt;span style="font-style:italic;"&gt;PropertyChanged &lt;/span&gt;handling logic from &lt;span style="font-style:italic;"&gt;StudentViewModel&lt;/span&gt;. This includes event subscription in the constructor and definition of event handler. Before making the updates suggested above, we need to reference assemblies provided by Rx installer. We need to add references for following assemblies:&lt;br /&gt;&lt;br /&gt;1. System.Reactive.dll&lt;br /&gt;2. System.CoreEx&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://4.bp.blogspot.com/-y9u5xsJykFg/TVS9tRWYb-I/AAAAAAAAA0I/jQPJrfA-XCY/s1600/5.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 291px; height: 400px;" src="http://4.bp.blogspot.com/-y9u5xsJykFg/TVS9tRWYb-I/AAAAAAAAA0I/jQPJrfA-XCY/s400/5.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5572287224413188066" /&gt;&lt;/a&gt;&lt;br /&gt;These assemblies are installed as part of installation of &lt;span style="font-style:italic;"&gt;Reactive Extension (Rx)&lt;/span&gt;. It can be downloaded as follows:&lt;br /&gt;&lt;br /&gt;&lt;a href="http://msdn.microsoft.com/en-us/devlabs/ee794896"&gt;http://msdn.microsoft.com/en-us/devlabs/ee794896&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Update the code of the constructor of &lt;span style="font-style:italic;"&gt;StudentViewModel&lt;/span&gt; as follows:&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;public StudentViewModel(Student student)&lt;br /&gt;{&lt;br /&gt;    _model = student;&lt;br /&gt;&lt;br /&gt;    Observable.FromEvent&amp;lt;PropertyChangedEventArgs&amp;gt;(_model, "PropertyChanged")            &lt;br /&gt;        .Subscribe((arg) =&gt;&lt;br /&gt;                       {&lt;br /&gt;                           this.StudentId = _model.StudentId;&lt;br /&gt;                           this.StudentName = _model.StudentName;&lt;br /&gt;                       });&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;span style="font-style:italic;"&gt;System.Linq.Observable&lt;/span&gt; from &lt;span style="font-style:italic;"&gt;System.Reactive&lt;/span&gt; assembly allows to subscribe with any event stream. &lt;span style="font-style:italic;"&gt;System.Collections.Generic.IEvent&amp;lt;T&amp;gt;&lt;/span&gt; is defined in &lt;span style="font-style:italic;"&gt;System.CoreEx&lt;/span&gt; assembly. We are subscribing to PropertyChanged event stream from _model instance. Observable.FromEvent&amp;lt;T&amp;gt;() returns IObservable&amp;lt;IEvent&amp;lt;T&amp;gt;&amp;gt;. Since it is an &lt;span style="font-style:italic;"&gt;IObservable&lt;/span&gt;, we can subscribe to it. The code that we want to execute when event is triggered can be specified in the &lt;span style="font-style:italic;"&gt;onNext &lt;/span&gt;delegate. Let's run the application now. &lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://2.bp.blogspot.com/-izJjBRGVhiM/TVTGgX7qhpI/AAAAAAAAA0Q/6X-221XVLtA/s1600/6.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 143px;" src="http://2.bp.blogspot.com/-izJjBRGVhiM/TVTGgX7qhpI/AAAAAAAAA0Q/6X-221XVLtA/s400/6.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5572296898446526098" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Like before, we are opening two instances of &lt;span style="font-style:italic;"&gt;StudentView &lt;/span&gt;window. When we enter information in the text boxes, information is updated in other window. The contents are updated because of the event handling logic in the observable event stream handler code as presented above.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Filtering events from Event Stream:&lt;/span&gt;&lt;br /&gt;Since it is an IObservable&amp;lt;T&amp;gt; we can filter it using &lt;span style="font-style:italic;"&gt;Where &lt;/span&gt;operator. Let's filter it to just handle the case when event is received because of update in &lt;span style="font-style:italic;"&gt;StudentName &lt;/span&gt;property. The changes in &lt;span style="font-style:italic;"&gt;StudentId &lt;/span&gt;are ignored. Let's update the code as follows:&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;public StudentViewModel(Student student)&lt;br /&gt;{&lt;br /&gt;    _model = student;&lt;br /&gt;&lt;br /&gt;    Observable.FromEvent&amp;lt;PropertyChangedEventArgs&amp;gt;(_model, "PropertyChanged")&lt;br /&gt;        .Where(et =&gt; et.EventArgs.PropertyName == "StudentName")&lt;br /&gt;        .Subscribe((arg) =&gt;&lt;br /&gt;                       {&lt;br /&gt;                           this.StudentId = _model.StudentId;&lt;br /&gt;                           this.StudentName = _model.StudentName;&lt;br /&gt;                       });&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Now run the application and again open two instances. The update in text box for &lt;span style="font-style:italic;"&gt;StudentName &lt;/span&gt;shows the updates in the other window. If we update &lt;span style="font-style:italic;"&gt;StudentId&lt;/span&gt;, it doesn't update the other window as the event stream is filtered.&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://3.bp.blogspot.com/-S3yiFnZTnLY/TVTPyWFriLI/AAAAAAAAA0Y/l6RTFi1_98A/s1600/7.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 141px;" src="http://3.bp.blogspot.com/-S3yiFnZTnLY/TVTPyWFriLI/AAAAAAAAA0Y/l6RTFi1_98A/s400/7.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5572307102793959602" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Throttling events from Event Stream:&lt;/span&gt;&lt;br /&gt;Since are binding using &lt;span style="font-style:italic;"&gt;UpdateSourceTrigger &lt;/span&gt;as &lt;span style="font-style:italic;"&gt;PropertyChanged&lt;/span&gt;, as the user types in the text boxes in &lt;span style="font-style:italic;"&gt;StudentView&lt;/span&gt;,&lt;span style="font-style:italic;"&gt; WPF Binding System&lt;/span&gt; automatically updates the values in the View model's properties. This updates corresponding properties of the model using the view model's property setters. We just don't want to keep sending updates to the model but we should wait until the user is done typing and then update the model's properties. This can be supported by throttling support. This can by achieved introducing PropertyChanged event in the view models for itself. We can remove the code to update corresponding model's properties in the setters. Let's update the definition of &lt;span style="font-style:italic;"&gt;StudentViewModel &lt;/span&gt;as follows:&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;public class StudentViewModel : INotifyPropertyChanged&lt;br /&gt;{&lt;br /&gt;    private int _studentId;&lt;br /&gt;    private string _studentName;&lt;br /&gt;&lt;br /&gt;    private Student _model;&lt;br /&gt;&lt;br /&gt;    public StudentViewModel(Student student)&lt;br /&gt;    {&lt;br /&gt;        _model = student;&lt;br /&gt;&lt;br /&gt;        Observable.FromEvent&amp;lt;PropertyChangedEventArgs&amp;gt;(_model, "PropertyChanged")&lt;br /&gt;            .Where(et =&amp;gt; et.EventArgs.PropertyName == "StudentName")&lt;br /&gt;            .Subscribe((arg) =&amp;gt;&lt;br /&gt;                           {&lt;br /&gt;                               this.StudentId = _model.StudentId;&lt;br /&gt;                               this.StudentName = _model.StudentName;&lt;br /&gt;                           });&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;        Observable.FromEvent&amp;lt;PropertyChangedEventArgs&amp;gt;(this, "PropertyChanged")&lt;br /&gt;            .Throttle(TimeSpan.FromMilliseconds(500))&lt;br /&gt;            .Where(et =&amp;gt; et.EventArgs.PropertyName == "StudentName")&lt;br /&gt;            .Subscribe((ar) =&amp;gt;&lt;br /&gt;            {&lt;br /&gt;                _model.StudentId = this.StudentId;&lt;br /&gt;                _model.StudentName = this.StudentName;&lt;br /&gt;            });&lt;br /&gt;       &lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    //void _model_PropertyChanged(object sender, PropertyChangedEventArgs e)&lt;br /&gt;    //{&lt;br /&gt;    //    //object value = _model.GetType().GetProperty(e.PropertyName).GetValue(_model, null);&lt;br /&gt;    //    //this.GetType().GetProperty(e.PropertyName).SetValue(this, value, null);&lt;br /&gt;    //    //this.StudentId = _model.StudentId;&lt;br /&gt;    //    //this.StudentName = _model.StudentName;&lt;br /&gt;    //}&lt;br /&gt;&lt;br /&gt;    public int StudentId&lt;br /&gt;    {&lt;br /&gt;        get { return _studentId; }&lt;br /&gt;        set&lt;br /&gt;        {&lt;br /&gt;            if (_studentId != value)&lt;br /&gt;            {&lt;br /&gt;                _studentId = value;&lt;br /&gt;                //_model.StudentId = value;&lt;br /&gt;                OnPropertyChanged("StudentId");   &lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public string StudentName&lt;br /&gt;    {&lt;br /&gt;        get { return _studentName; }&lt;br /&gt;        set&lt;br /&gt;        {&lt;br /&gt;            if(_studentName != value)&lt;br /&gt;            {&lt;br /&gt;                _studentName = value;&lt;br /&gt;                //_model.StudentName = value;&lt;br /&gt;                OnPropertyChanged("StudentName");&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public event PropertyChangedEventHandler PropertyChanged = delegate { };&lt;br /&gt;    private void OnPropertyChanged(string propertyName)&lt;br /&gt;    {&lt;br /&gt;        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;We needed to remove the code resulting in the updates in the setter of properties in the view model. Let' throttle these updates. When user types in StudentName, the IObservable doesn't update the other window immediately. It is rather waiting for property to settle down. After which it is causing the &lt;span style="font-style:italic;"&gt;PropertyChanged &lt;/span&gt;events to be handled.&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://3.bp.blogspot.com/-9e2EdNzXUbk/TVTaER-zhyI/AAAAAAAAA0g/Ku2a81kHM_s/s1600/8.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 139px;" src="http://3.bp.blogspot.com/-9e2EdNzXUbk/TVTaER-zhyI/AAAAAAAAA0g/Ku2a81kHM_s/s400/8.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5572318406045304610" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Download:&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;iframe title ="Preview" scrolling="no" marginheight="0" marginwidth="0" frameborder="0" style="width:98px;height:115px;padding:0;background-color:#fcfcfc;" src="http://cid-b5fee7d7acde5072.office.live.com/embedicon.aspx/MVVM%20Reactive%20Models%20Observable%20Event%20Streams/ReactiveModelSynch%20-%20Events.zip"&gt;&lt;/iframe&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8085117242240449595-1002046634202115131?l=www.shujaat.net' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.shujaat.net/feeds/1002046634202115131/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8085117242240449595&amp;postID=1002046634202115131&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/1002046634202115131'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/1002046634202115131'/><link rel='alternate' type='text/html' href='http://www.shujaat.net/2011/02/mvvm-observable-inotifypropertychangedp.html' title='MVVM - Observable INotifyPropertyChanged.PropertyChanged Event Stream Using Reactive Extension'/><author><name>Muhammad Shujaat Siddiqi</name><uri>http://www.blogger.com/profile/02519138704633566929</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://2.bp.blogspot.com/-WwU2IJaSErw/TVSt0uslI8I/AAAAAAAAAzo/SIKol8F9Z5Y/s72-c/1.jpg' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8085117242240449595.post-8154171549362445693</id><published>2011-02-09T23:40:00.010-06:00</published><updated>2011-02-10T01:52:02.853-06:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='OnCompleted'/><category scheme='http://www.blogger.com/atom/ns#' term='MVVM'/><category scheme='http://www.blogger.com/atom/ns#' term='Rx'/><category scheme='http://www.blogger.com/atom/ns#' term='multiple observer'/><category scheme='http://www.blogger.com/atom/ns#' term='wpf'/><category scheme='http://www.blogger.com/atom/ns#' term='OnNext'/><category scheme='http://www.blogger.com/atom/ns#' term='IObserver'/><category scheme='http://www.blogger.com/atom/ns#' term='IObservable'/><category scheme='http://www.blogger.com/atom/ns#' term='Reactive extension'/><category scheme='http://www.blogger.com/atom/ns#' term='OnError'/><title type='text'>MVVM - View Model (IObserver) Observing multiple IObservable (s)</title><content type='html'>This is a continuation of posts of our discussion about the usage of Reactive Extension (Rx) in MVVM implementation in WPF. For this post, we will be trying to find out how a View model observes multiple observables. The main question is, Can an &lt;span style="font-style:italic;"&gt;IObserver &lt;/span&gt;observes multiple &lt;span style="font-style:italic;"&gt;IObservable&lt;/span&gt;?&lt;br /&gt;&lt;br /&gt;In this example, view model is observing the data from different sources. We want to show the list of students and courses on the same window. I am not saying this is the best thing or I would do it in a real world application. But this is more of a what if kind of a scenario. We want our view to look like this:&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://3.bp.blogspot.com/-tyodWpmPoy4/TVOC5Z1sa-I/AAAAAAAAAzI/Echakk0qBjo/s1600/1.png"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 387px; height: 400px;" src="http://3.bp.blogspot.com/-tyodWpmPoy4/TVOC5Z1sa-I/AAAAAAAAAzI/Echakk0qBjo/s400/1.png" border="0" alt=""id="BLOGGER_PHOTO_ID_5571941086687685602" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Let us update the view in the previous post as follows:&lt;br /&gt;&lt;pre class="brush: xml; gutter: false;"&gt;&lt;br /&gt;&amp;lt;Window x:Class="WpfApp_MVVM_ReactiveModel.MainWindow"&lt;br /&gt;        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"&lt;br /&gt;        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&lt;br /&gt;        xmlns:local="clr-namespace:WpfApp_MVVM_ReactiveModel"&lt;br /&gt;        Title="MainWindow" Height="544" Width="526"&amp;gt;    &lt;br /&gt;    &amp;lt;Window.DataContext&amp;gt;&lt;br /&gt;        &amp;lt;local:MainWindowViewModel /&amp;gt;&lt;br /&gt;    &amp;lt;/Window.DataContext&amp;gt;&lt;br /&gt;    &amp;lt;Grid&amp;gt;&lt;br /&gt;        &amp;lt;Label Content="Students" Height="26" HorizontalAlignment="Left" Name="label1"&lt;br /&gt;               VerticalAlignment="Top" Width="161" FontWeight="Bold" /&amp;gt;&lt;br /&gt;        &amp;lt;ListBox Height="234" HorizontalAlignment="Left" Margin="4,30,0,0" &lt;br /&gt;                 Name="listBox1" VerticalAlignment="Top" Width="493" &lt;br /&gt;                 ItemsSource="{Binding StudentList}"&amp;gt;&lt;br /&gt;            &amp;lt;ListBox.ItemTemplate&amp;gt;&lt;br /&gt;                &amp;lt;DataTemplate &amp;gt;&lt;br /&gt;                    &amp;lt;StackPanel Orientation="Horizontal"&amp;gt;&lt;br /&gt;                        &amp;lt;TextBlock Text="{Binding StudentId, StringFormat=Id:{0}}" /&amp;gt;&lt;br /&gt;                        &amp;lt;TextBlock Text="       " /&amp;gt;&lt;br /&gt;                        &amp;lt;TextBlock Text="{Binding StudentName, StringFormat=Name:{0}}" /&amp;gt;&lt;br /&gt;                    &amp;lt;/StackPanel&amp;gt;&lt;br /&gt;                &amp;lt;/DataTemplate&amp;gt;&lt;br /&gt;            &amp;lt;/ListBox.ItemTemplate&amp;gt;&lt;br /&gt;        &amp;lt;/ListBox&amp;gt;        &lt;br /&gt;        &amp;lt;Label Content="Courses" FontWeight="Bold" Height="26" HorizontalAlignment="Left" Margin="0,270,0,0" &lt;br /&gt;               Name="label2" VerticalAlignment="Top" Width="161" /&amp;gt;&lt;br /&gt;        &amp;lt;ListBox Height="161" HorizontalAlignment="Left" Margin="5,294,0,0" Name="listBoxCourse" &lt;br /&gt;                 VerticalAlignment="Top" Width="492"&lt;br /&gt;                 ItemsSource="{Binding CourseList}"&amp;gt;&lt;br /&gt;            &amp;lt;ListBox.ItemTemplate&amp;gt;&lt;br /&gt;                &amp;lt;DataTemplate &amp;gt;&lt;br /&gt;                    &amp;lt;StackPanel Orientation="Horizontal"&amp;gt;&lt;br /&gt;                        &amp;lt;TextBlock Text="{Binding CourseId, StringFormat=Id:{0}}" /&amp;gt;&lt;br /&gt;                        &amp;lt;TextBlock Text="       " /&amp;gt;&lt;br /&gt;                        &amp;lt;TextBlock Text="{Binding CourseName, StringFormat=Name:{0}}" /&amp;gt;&lt;br /&gt;                    &amp;lt;/StackPanel&amp;gt;&lt;br /&gt;                &amp;lt;/DataTemplate&amp;gt;&lt;br /&gt;            &amp;lt;/ListBox.ItemTemplate&amp;gt;&lt;br /&gt;        &amp;lt;/ListBox&amp;gt;&lt;br /&gt;        &amp;lt;Ellipse Height="31" HorizontalAlignment="Left" Margin="326,462,0,0" Name="ellipse1" &lt;br /&gt;                 Stroke="Black" VerticalAlignment="Top" Width="166" &amp;gt;&lt;br /&gt;            &amp;lt;Ellipse.Style&amp;gt;&lt;br /&gt;                &amp;lt;Style&amp;gt;&lt;br /&gt;                    &amp;lt;Setter Property="Ellipse.Fill" Value="Yellow" /&amp;gt;&lt;br /&gt;                    &amp;lt;Style.Triggers&amp;gt;&lt;br /&gt;                        &amp;lt;DataTrigger Binding="{Binding IsDataStreamFinished}" Value="true"&amp;gt;&lt;br /&gt;                            &amp;lt;Setter Property="Ellipse.Fill" Value="Green" /&amp;gt;&lt;br /&gt;                        &amp;lt;/DataTrigger&amp;gt;&lt;br /&gt;                    &amp;lt;/Style.Triggers&amp;gt;&lt;br /&gt;                &amp;lt;/Style&amp;gt;&lt;br /&gt;            &amp;lt;/Ellipse.Style&amp;gt;&lt;br /&gt;        &amp;lt;/Ellipse&amp;gt;&lt;br /&gt;    &amp;lt;/Grid&amp;gt;&lt;br /&gt;&amp;lt;/Window&amp;gt;&lt;/pre&gt;&lt;br /&gt;As you might have noticed we have thrown in a couple of labels to identify the data loaded in the two list boxes. The difference is we have incorporated another list box to show the list of Courses. It is bound to &lt;span style="font-style:italic;"&gt;CourseList &lt;/span&gt;in the view model. Each member of this collection should have two properties i.e. &lt;span style="font-style:italic;"&gt;CourseId &lt;/span&gt;and &lt;span style="font-style:italic;"&gt;CourseName&lt;/span&gt;.&lt;br /&gt;&lt;br /&gt;As we described above the view model is expected to have a collection called &lt;span style="font-style:italic;"&gt;CourseList&lt;/span&gt; and each member of this collection should be having two properties &lt;span style="font-style:italic;"&gt;CourseId &lt;/span&gt;and &lt;span style="font-style:italic;"&gt;CourseName&lt;/span&gt;. Let us see what updates we need to make in the view model.&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;class MainWindowViewModel : IObserver&amp;lt;Student&amp;gt;, INotifyPropertyChanged, IObserver&amp;lt;Course&amp;gt;&lt;br /&gt;{        &lt;br /&gt;    #region Properties&lt;br /&gt;&lt;br /&gt;    private ObservableCollection&amp;lt;StudentViewModel&amp;gt; _studentList;&lt;br /&gt;    public ObservableCollection&amp;lt;StudentViewModel&amp;gt; StudentList&lt;br /&gt;    {&lt;br /&gt;        get { return _studentList; }&lt;br /&gt;        set&lt;br /&gt;        {&lt;br /&gt;            _studentList = value;&lt;br /&gt;            onPropertyChanged("StudentList");&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private ObservableCollection&amp;lt;CourseViewModel&amp;gt; _courseList;&lt;br /&gt;    public ObservableCollection&amp;lt;CourseViewModel&amp;gt; CourseList&lt;br /&gt;    {&lt;br /&gt;        get { return _courseList; }&lt;br /&gt;        set&lt;br /&gt;        {&lt;br /&gt;            _courseList = value;&lt;br /&gt;            onPropertyChanged("CourseList");&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private bool _isDataStreamFinished;&lt;br /&gt;    public bool IsDataStreamFinished&lt;br /&gt;    {&lt;br /&gt;        get { return _isDataStreamFinished; }&lt;br /&gt;        set&lt;br /&gt;        {&lt;br /&gt;            _isDataStreamFinished = value;&lt;br /&gt;            onPropertyChanged("IsDataStreamFinished");&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    #endregion Properties&lt;br /&gt;&lt;br /&gt;    #region Observable Model&lt;br /&gt;    //Model&lt;br /&gt;    private StudentsModel model;&lt;br /&gt;    private CoursesModel courseModel;&lt;br /&gt;&lt;br /&gt;    #endregion Observable Model&lt;br /&gt;&lt;br /&gt;    IDisposable unsubscriber;&lt;br /&gt;&lt;br /&gt;    #region Constructor&lt;br /&gt;    &lt;br /&gt;    public MainWindowViewModel()&lt;br /&gt;    {&lt;br /&gt;        _studentList = new ObservableCollection&amp;lt;StudentViewModel&amp;gt;();&lt;br /&gt;&lt;br /&gt;        model = new StudentsModel();&lt;br /&gt;        &lt;br /&gt;        //subscribe to all updates&lt;br /&gt;        //model.Subscribe(this);&lt;br /&gt;&lt;br /&gt;        //subscribe to 10 updates after first 2 updates&lt;br /&gt;        //unsubscriber = model.Skip(2).Take&amp;lt;Student&amp;gt;(10).Subscribe(this);            &lt;br /&gt;&lt;br /&gt;        //subscribe to all students whose Ids are even&lt;br /&gt;        //unsubscriber = (from m in model &lt;br /&gt;        //                where m.StudentId % 2 == 0&lt;br /&gt;        //                    select m).Subscribe(this);&lt;br /&gt;&lt;br /&gt;        //observe on UI thread&lt;br /&gt;        unsubscriber = Observable.ObserveOnDispatcher&amp;lt;Student&amp;gt;(&lt;br /&gt;            (from m in model &lt;br /&gt;             where m.StudentId % 2 == 0&lt;br /&gt;             select m)&lt;br /&gt;             ).Subscribe(this);&lt;br /&gt;&lt;br /&gt;        courseModel = new CoursesModel();&lt;br /&gt;        _courseList = new ObservableCollection&amp;lt;CourseViewModel&amp;gt;();&lt;br /&gt;        Observable.ObserveOnDispatcher&amp;lt;Course&amp;gt;(courseModel).Subscribe(this);&lt;br /&gt;        &lt;br /&gt;    }&lt;br /&gt;    &lt;br /&gt;    #endregion Constructor&lt;br /&gt;&lt;br /&gt;    #region IObserver implementation&lt;br /&gt;    public void OnCompleted()&lt;br /&gt;    {&lt;br /&gt;        //throw new NotImplementedException();&lt;br /&gt;        //unsubscriber.Dispose();&lt;br /&gt;        IsDataStreamFinished = true;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public void OnError(Exception error)&lt;br /&gt;    {&lt;br /&gt;        //throw new NotImplementedException();&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public void OnNext(Student value)&lt;br /&gt;    {&lt;br /&gt;        //throw new NotImplementedException();&lt;br /&gt;        _studentList.Add(new StudentViewModel(value));&lt;br /&gt;    }&lt;br /&gt;    &lt;br /&gt;    #endregion IObserver implementation&lt;br /&gt;&lt;br /&gt;    #region INotifyPropertyChanged implementation&lt;br /&gt;    &lt;br /&gt;    public event PropertyChangedEventHandler PropertyChanged;&lt;br /&gt;    private void onPropertyChanged(string propertyname)&lt;br /&gt;    {&lt;br /&gt;        if (PropertyChanged != null)&lt;br /&gt;        {&lt;br /&gt;            PropertyChanged(this, new PropertyChangedEventArgs(propertyname));&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    #endregion INotifyPropertyChanged implementation&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;    public void OnNext(Course value)&lt;br /&gt;    {&lt;br /&gt;        //throw new NotImplementedException();&lt;br /&gt;        _courseList.Add(new CourseViewModel(value));&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;You should notice that the view model is not implementing &lt;span style="font-style:italic;"&gt;IObserver&amp;lt;Course&amp;gt&lt;/span&gt;;. This would enable it to observe an &lt;span style="font-style:italic;"&gt;IObservable&amp;lt;Course&amp;gt;&lt;/span&gt;. It has been introduced with one IObservable&amp;lt;Course&amp;gt; instance named &lt;span style="font-style:italic;"&gt;courseModel&lt;/span&gt;. We have also subscribed to this in the constructor to observe the &lt;span style="font-style:italic;"&gt;courseModel &lt;/span&gt;on &lt;span style="font-style:italic;"&gt;Dispatcher&lt;/span&gt;. To implement the interface, we need to provide the definition of three methods, &lt;span style="font-style:italic;"&gt;OnNext&lt;/span&gt;, &lt;span style="font-style:italic;"&gt;OnCompleted &lt;/span&gt;and &lt;span style="font-style:italic;"&gt;OnError&lt;/span&gt;. Since &lt;span style="font-style:italic;"&gt;OnCompleted &lt;/span&gt;and &lt;span style="font-style:italic;"&gt;OnError &lt;/span&gt; are already provided so we don't need to provide a new definition, even, we can not implement as this would be considered as overloading the methods and this requires the methods, being overloaded, to have different signatures. In the &lt;span style="font-style:italic;"&gt;OnNext(Course)&lt;/span&gt; method, we are adding a new &lt;span style="font-style:italic;"&gt;CourseViewModel&lt;/span&gt; to &lt;span style="font-style:italic;"&gt;CourseList &lt;/span&gt;collection.&lt;br /&gt;&lt;br /&gt;Now let us provide the definition CourseModel. This is an IObservable&amp;lt;Course&amp;gt;. This would require it to provide an implementation of &lt;span style="font-style:italic;"&gt;Subscribe()&lt;/span&gt; method. This method should accept IObserver&amp;lt;Course&amp;gt; and should return an &lt;span style="font-style:italic;"&gt;IDisposable&lt;/span&gt;. Disposing this returned object should result in the nullify the subscription. This definition is similar to &lt;span style="font-style:italic;"&gt;StudensModel&lt;/span&gt;.&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;class CoursesModel : IObservable&amp;lt;Course&amp;gt;&lt;br /&gt;{&lt;br /&gt;    private int _courseId;&lt;br /&gt;    //For updates on a non-UI thread&lt;br /&gt;    Timer t = new Timer(1000);&lt;br /&gt;&lt;br /&gt;    public List&amp;lt;IObserver&amp;lt;Course&amp;gt;&amp;gt; Observers =&lt;br /&gt;        new List&amp;lt;IObserver&amp;lt;Course&amp;gt;&amp;gt;();&lt;br /&gt;&lt;br /&gt;    public CoursesModel()&lt;br /&gt;    {&lt;br /&gt;        t.Elapsed += new ElapsedEventHandler(t_Elapsed);&lt;br /&gt;        t.Start();&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    //For updates on a non-UI thread&lt;br /&gt;    void t_Elapsed(object sender, ElapsedEventArgs e)&lt;br /&gt;    {&lt;br /&gt;        _courseId++;&lt;br /&gt;&lt;br /&gt;        var course = new Course()&lt;br /&gt;        {&lt;br /&gt;            CourseId = _courseId,&lt;br /&gt;            CourseName = string.Format("Course : {0}", _courseId)&lt;br /&gt;        };&lt;br /&gt;&lt;br /&gt;        if (_courseId &amp;lt;= 3)&lt;br /&gt;        {&lt;br /&gt;            Observers.ForEach((observer) =&amp;gt; observer.OnNext(course));&lt;br /&gt;        }&lt;br /&gt;        else&lt;br /&gt;        {&lt;br /&gt;            Observers.ForEach((observer) =&amp;gt; observer.OnCompleted());&lt;br /&gt;            t.Stop();&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public IDisposable Subscribe(IObserver&amp;lt;Course&amp;gt; observer)&lt;br /&gt;    {&lt;br /&gt;        IDisposable unSubscriber = new Unsubscriber&amp;lt;Course&amp;gt;(Observers, observer);&lt;br /&gt;        if (!Observers.Contains(observer))&lt;br /&gt;        {&lt;br /&gt;            Observers.Add(observer);&lt;br /&gt;        }&lt;br /&gt;        return unSubscriber;&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;The definition of &lt;span style="font-style:italic;"&gt;Course &lt;/span&gt;and &lt;span style="font-style:italic;"&gt;CourseViewModel &lt;/span&gt;are as follows:&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;class Course&lt;br /&gt;{&lt;br /&gt;    public string CourseName { get; set; }&lt;br /&gt;    public int CourseId { get; set; }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;class CourseViewModel : INotifyPropertyChanged&lt;br /&gt;{&lt;br /&gt;    public CourseViewModel(Course course)&lt;br /&gt;    {&lt;br /&gt;        this.CourseId = course.CourseId;&lt;br /&gt;        this.CourseName = course.CourseName;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    #region Properties&lt;br /&gt;&lt;br /&gt;    private string _coursetName;&lt;br /&gt;    public string CourseName&lt;br /&gt;    {&lt;br /&gt;        get { return _coursetName; }&lt;br /&gt;        set&lt;br /&gt;        {&lt;br /&gt;            _coursetName = value;&lt;br /&gt;            OnPropertyChanged("CourseName");&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private int _courseId;&lt;br /&gt;    public int CourseId&lt;br /&gt;    {&lt;br /&gt;        get { return _courseId; }&lt;br /&gt;        set&lt;br /&gt;        {&lt;br /&gt;            _courseId = value;&lt;br /&gt;            OnPropertyChanged("CourseId");&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    #endregion Properties&lt;br /&gt;&lt;br /&gt;    #region INotifyPropertyChanged implementation&lt;br /&gt;&lt;br /&gt;    public event PropertyChangedEventHandler PropertyChanged;&lt;br /&gt;    private void OnPropertyChanged(string propertyName)&lt;br /&gt;    {&lt;br /&gt;        if (PropertyChanged != null)&lt;br /&gt;        {&lt;br /&gt;            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    #endregion INotifyPropertyChanged implementation&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;Now run the application. It is successfully loading the data as desired but there is a problem. The courseModel data is loaded first. This causes &lt;span style="font-style:italic;"&gt;OnCompleted &lt;/span&gt;to be executed which fills the notification ellipse as green. So we are giving the notification to the user that the data is completely loaded even before it is completely loaded. &lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://1.bp.blogspot.com/-jUr9hbcOfI0/TVOQQHLz7OI/AAAAAAAAAzQ/Zhejehr6XFg/s1600/2.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 387px; height: 400px;" src="http://1.bp.blogspot.com/-jUr9hbcOfI0/TVOQQHLz7OI/AAAAAAAAAzQ/Zhejehr6XFg/s400/2.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5571955770468330722" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;So, an &lt;span style="font-style:italic;"&gt;IObserver&lt;/span&gt; can observe multiple &lt;span style="font-style:italic;"&gt;IObservable&lt;/span&gt; (s) but we really can not distinguish between &lt;span style="font-style:italic;"&gt;OnCompleted &lt;/span&gt;and &lt;span style="font-style:italic;"&gt;OnError &lt;/span&gt;being executed because of which &lt;span style="font-style:italic;"&gt;IObservable&lt;/span&gt;. We need to find out way to do that.&lt;br /&gt;&lt;br /&gt;There is an easier solution to this problem. We can implement the interfaces explicitly. Let us assume that the notification is just about &lt;span style="font-style:italic;"&gt;StudentList&lt;/span&gt;. The ellipse should turn green only when the &lt;span style="font-style:italic;"&gt;StudentList &lt;/span&gt;is loaded completely. Let us implement &lt;span style="font-style:italic;"&gt;IObserver&amp;lt;Course&amp;gt;&lt;/span&gt;. &lt;br /&gt;&lt;pre  class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;class MainWindowViewModel : IObserver&amp;lt;Student&amp;gt;, INotifyPropertyChanged, IObserver&amp;lt;Course&amp;gt;&lt;br /&gt;{        &lt;br /&gt;    #region Properties&lt;br /&gt;&lt;br /&gt;    private ObservableCollection&amp;lt;StudentViewModel&amp;gt; _studentList;&lt;br /&gt;    public ObservableCollection&amp;lt;StudentViewModel&amp;gt; StudentList&lt;br /&gt;    {&lt;br /&gt;        get { return _studentList; }&lt;br /&gt;        set&lt;br /&gt;        {&lt;br /&gt;            _studentList = value;&lt;br /&gt;            onPropertyChanged("StudentList");&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private ObservableCollection&amp;lt;CourseViewModel&amp;gt; _courseList;&lt;br /&gt;    public ObservableCollection&amp;lt;CourseViewModel&amp;gt; CourseList&lt;br /&gt;    {&lt;br /&gt;        get { return _courseList; }&lt;br /&gt;        set&lt;br /&gt;        {&lt;br /&gt;            _courseList = value;&lt;br /&gt;            onPropertyChanged("CourseList");&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private bool _isDataStreamFinished;&lt;br /&gt;    public bool IsDataStreamFinished&lt;br /&gt;    {&lt;br /&gt;        get { return _isDataStreamFinished; }&lt;br /&gt;        set&lt;br /&gt;        {&lt;br /&gt;            _isDataStreamFinished = value;&lt;br /&gt;            onPropertyChanged("IsDataStreamFinished");&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    #endregion Properties&lt;br /&gt;&lt;br /&gt;    #region Observable Model&lt;br /&gt;    //Model&lt;br /&gt;    private StudentsModel model;&lt;br /&gt;    private CoursesModel courseModel;&lt;br /&gt;&lt;br /&gt;    #endregion Observable Model&lt;br /&gt;&lt;br /&gt;    IDisposable unsubscriber;&lt;br /&gt;&lt;br /&gt;    #region Constructor&lt;br /&gt;    &lt;br /&gt;    public MainWindowViewModel()&lt;br /&gt;    {&lt;br /&gt;        _studentList = new ObservableCollection&amp;lt;StudentViewModel&amp;gt;();&lt;br /&gt;&lt;br /&gt;        model = new StudentsModel();&lt;br /&gt;        &lt;br /&gt;        //subscribe to all updates&lt;br /&gt;        //model.Subscribe(this);&lt;br /&gt;&lt;br /&gt;        //subscribe to 10 updates after first 2 updates&lt;br /&gt;        //unsubscriber = model.Skip(2).Take&amp;lt;Student&amp;gt;(10).Subscribe(this);            &lt;br /&gt;&lt;br /&gt;        //subscribe to all students whose Ids are even&lt;br /&gt;        //unsubscriber = (from m in model &lt;br /&gt;        //                where m.StudentId % 2 == 0&lt;br /&gt;        //                    select m).Subscribe(this);&lt;br /&gt;&lt;br /&gt;        //observe on UI thread&lt;br /&gt;        unsubscriber = Observable.ObserveOnDispatcher&amp;lt;Student&amp;gt;(&lt;br /&gt;            (from m in model &lt;br /&gt;             where m.StudentId % 2 == 0&lt;br /&gt;             select m)&lt;br /&gt;             ).Subscribe(this);&lt;br /&gt;&lt;br /&gt;        courseModel = new CoursesModel();&lt;br /&gt;        _courseList = new ObservableCollection&amp;lt;CourseViewModel&amp;gt;();&lt;br /&gt;        Observable.ObserveOnDispatcher&amp;lt;Course&amp;gt;(courseModel).Subscribe(this);&lt;br /&gt;        &lt;br /&gt;    }&lt;br /&gt;    &lt;br /&gt;    #endregion Constructor&lt;br /&gt;&lt;br /&gt;    #region IObserver implementation&lt;br /&gt;    public void OnCompleted()&lt;br /&gt;    {&lt;br /&gt;        //throw new NotImplementedException();&lt;br /&gt;        //unsubscriber.Dispose();&lt;br /&gt;        IsDataStreamFinished = true;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public void OnError(Exception error)&lt;br /&gt;    {&lt;br /&gt;        //throw new NotImplementedException();&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public void OnNext(Student value)&lt;br /&gt;    {&lt;br /&gt;        //throw new NotImplementedException();&lt;br /&gt;        _studentList.Add(new StudentViewModel(value));&lt;br /&gt;    }&lt;br /&gt;    &lt;br /&gt;    #endregion IObserver implementation&lt;br /&gt;&lt;br /&gt;    #region INotifyPropertyChanged implementation&lt;br /&gt;    &lt;br /&gt;    public event PropertyChangedEventHandler PropertyChanged;&lt;br /&gt;    private void onPropertyChanged(string propertyname)&lt;br /&gt;    {&lt;br /&gt;        if (PropertyChanged != null)&lt;br /&gt;        {&lt;br /&gt;            PropertyChanged(this, new PropertyChangedEventArgs(propertyname));&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    #endregion INotifyPropertyChanged implementation&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;    void IObserver&amp;lt;Course&amp;gt;.OnCompleted()&lt;br /&gt;    {&lt;br /&gt;        //throw new NotImplementedException();&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    void IObserver&amp;lt;Course&amp;gt;.OnError(Exception error)&lt;br /&gt;    {&lt;br /&gt;        //throw new NotImplementedException();&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    void IObserver&amp;lt;Course&amp;gt;.OnNext(Course value)&lt;br /&gt;    {&lt;br /&gt;        _courseList.Add(new CourseViewModel(value));&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;Now when CoursesModel calls OnCompleted on the observers the explicit implementation of the interface's OnCompleted gets called which currently no implementation (just an empty method). So the ellipse is still yellow.&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://1.bp.blogspot.com/-wG_EoKMUjdI/TVOVmUAS1ZI/AAAAAAAAAzY/SYUTnjDLrsw/s1600/3.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 387px; height: 400px;" src="http://1.bp.blogspot.com/-wG_EoKMUjdI/TVOVmUAS1ZI/AAAAAAAAAzY/SYUTnjDLrsw/s400/3.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5571961649424946578" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;After the data is completely loaded, &lt;span style="font-style:italic;"&gt;StudentsModel&lt;/span&gt;, an IObservable&amp;lt;Student&amp;gt; calls &lt;span style="font-style:italic;"&gt;OnCompleted&lt;/span&gt; which sets the variable bound to the trigger on the view to change the fill color of ellipse to green.&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://4.bp.blogspot.com/-pKVyjd4b0tA/TVOV1TKxR4I/AAAAAAAAAzg/_uyGd8cXtKA/s1600/4.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 387px; height: 400px;" src="http://4.bp.blogspot.com/-pKVyjd4b0tA/TVOV1TKxR4I/AAAAAAAAAzg/_uyGd8cXtKA/s400/4.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5571961906898487170" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Download:&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;iframe title ="Preview" scrolling="no" marginheight="0" marginwidth="0" frameborder="0" style="width:98px;height:115px;padding:0;background-color:#fcfcfc;" src="http://cid-b5fee7d7acde5072.office.live.com/embedicon.aspx/MVVM%20Rx%20Multiple%20Observers/MVVM%20Rx%20Multiple%20Observers.zip"&gt;&lt;/iframe&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8085117242240449595-8154171549362445693?l=www.shujaat.net' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.shujaat.net/feeds/8154171549362445693/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8085117242240449595&amp;postID=8154171549362445693&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/8154171549362445693'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/8154171549362445693'/><link rel='alternate' type='text/html' href='http://www.shujaat.net/2011/02/mvvm-view-model-iobserver-observing.html' title='MVVM - View Model (IObserver) Observing multiple IObservable (s)'/><author><name>Muhammad Shujaat Siddiqi</name><uri>http://www.blogger.com/profile/02519138704633566929</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://3.bp.blogspot.com/-tyodWpmPoy4/TVOC5Z1sa-I/AAAAAAAAAzI/Echakk0qBjo/s72-c/1.png' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8085117242240449595.post-8932532203480715572</id><published>2011-02-08T23:00:00.017-06:00</published><updated>2011-02-09T02:00:37.947-06:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='ObserveOnDispatcher'/><category scheme='http://www.blogger.com/atom/ns#' term='MVVM'/><category scheme='http://www.blogger.com/atom/ns#' term='dispatcher'/><category scheme='http://www.blogger.com/atom/ns#' term='UI thread'/><category scheme='http://www.blogger.com/atom/ns#' term='Rx'/><category scheme='http://www.blogger.com/atom/ns#' term='wpf'/><category scheme='http://www.blogger.com/atom/ns#' term='close window from View model'/><category scheme='http://www.blogger.com/atom/ns#' term='IObserver'/><category scheme='http://www.blogger.com/atom/ns#' term='Observer pattern'/><category scheme='http://www.blogger.com/atom/ns#' term='IObservable'/><category scheme='http://www.blogger.com/atom/ns#' term='reactive model'/><category scheme='http://www.blogger.com/atom/ns#' term='Reactive extension'/><title type='text'>WPF - IObservable Collection based Reactive Models In MVVM (Rx)</title><content type='html'>This post is a continuation of the discussion we started in last post. This would take this discussion a little further deep in the incorporation of &lt;span style="font-style:italic;"&gt;Reactive Extension&lt;/span&gt; (&lt;span style="font-style:italic;"&gt;Rx&lt;/span&gt;) in &lt;span style="font-style:italic;"&gt;MVVM&lt;/span&gt;. In previous post we discussed how &lt;span style="font-style:italic;"&gt;Rx &lt;/span&gt;is the mathematical dual of Linq to Object. Additionally, the interfaces &lt;span style="font-style:italic;"&gt;IObservable &lt;/span&gt;and &lt;span style="font-style:italic;"&gt;IObserver &lt;/span&gt;are mathematical dual of &lt;span style="font-style:italic;"&gt;IEnumerator &lt;/span&gt;and &lt;span style="font-style:italic;"&gt;IEnumerable&lt;/span&gt;.&lt;br /&gt;&lt;br /&gt;In this post, we are going to discuss the following:&lt;br /&gt;&lt;br /&gt;1. IObservable as a Collection of items.&lt;br /&gt;2. Observing Projections of &lt;span style="font-style:italic;"&gt;IObservable&lt;/span&gt;.&lt;br /&gt;3. Dispatching the observation on UI thread.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Example App:&lt;/span&gt;&lt;br /&gt;As an example application, we would be using a Window with a list (for Students) and a notification at the bottom. The notification ellipse should remain yellow until the data is being loaded.&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://4.bp.blogspot.com/_fVxKMZVpfzU/TVIhNFgXXtI/AAAAAAAAAyI/dsKdZHeEuYo/s1600/1.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 267px;" src="http://4.bp.blogspot.com/_fVxKMZVpfzU/TVIhNFgXXtI/AAAAAAAAAyI/dsKdZHeEuYo/s400/1.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5571552197710667474" /&gt;&lt;/a&gt;&lt;br /&gt;As soon as the data load is completed, the notification ellipse should be updated and filled with green as follows:&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://1.bp.blogspot.com/_fVxKMZVpfzU/TVIjjj9-8wI/AAAAAAAAAyQ/vrf0alk-NK4/s1600/2.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 267px;" src="http://1.bp.blogspot.com/_fVxKMZVpfzU/TVIjjj9-8wI/AAAAAAAAAyQ/vrf0alk-NK4/s400/2.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5571554782868337410" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Collection based Reactive Models:&lt;/span&gt;&lt;br /&gt;Let's create a window. The window should be populate with a list of students. As the list becomes completed, it should show some form of notification. For notification, we are adding an ellipsis. &lt;br /&gt;&lt;pre class="brush: xml; gutter: false;"&gt;&lt;br /&gt;&amp;lt;Window x:Class="WpfApp_MVVM_ReactiveModel.MainWindow"&lt;br /&gt;        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"&lt;br /&gt;        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&lt;br /&gt;        xmlns:local="clr-namespace:WpfApp_MVVM_ReactiveModel"&lt;br /&gt;        Title="MainWindow" Height="350" Width="525" &amp;gt;    &lt;br /&gt;    &amp;lt;Window.DataContext&amp;gt;&lt;br /&gt;        &amp;lt;local:MainWindowViewModel /&amp;gt;&lt;br /&gt;    &amp;lt;/Window.DataContext&amp;gt;&lt;br /&gt;    &amp;lt;Grid&amp;gt;&lt;br /&gt;        &amp;lt;ListBox Height="262" HorizontalAlignment="Left" Margin="4,2,0,0" &lt;br /&gt;                 Name="listBox1" VerticalAlignment="Top" Width="493" &lt;br /&gt;                 ItemsSource="{Binding StudentList}"&amp;gt;&lt;br /&gt;            &amp;lt;ListBox.ItemTemplate&amp;gt;&lt;br /&gt;                &amp;lt;DataTemplate &amp;gt;&lt;br /&gt;                    &amp;lt;StackPanel Orientation="Horizontal"&amp;gt;&lt;br /&gt;                        &amp;lt;TextBlock Text="{Binding StudentId, StringFormat=Id:{0}}" /&amp;gt;&lt;br /&gt;                        &amp;lt;TextBlock Text="       " /&amp;gt;&lt;br /&gt;                        &amp;lt;TextBlock Text="{Binding StudentName, StringFormat=Name:{0}}" /&amp;gt;&lt;br /&gt;                    &amp;lt;/StackPanel&amp;gt;&lt;br /&gt;                &amp;lt;/DataTemplate&amp;gt;&lt;br /&gt;            &amp;lt;/ListBox.ItemTemplate&amp;gt;&lt;br /&gt;        &amp;lt;/ListBox&amp;gt;&lt;br /&gt;        &amp;lt;Ellipse Height="31" HorizontalAlignment="Left" Margin="322,270,0,0" Name="ellipse1" &lt;br /&gt;                 Stroke="Black" VerticalAlignment="Top" Width="166" &amp;gt;&lt;br /&gt;            &amp;lt;Ellipse.Style&amp;gt;&lt;br /&gt;                &amp;lt;Style&amp;gt;&lt;br /&gt;                    &amp;lt;Setter Property="Ellipse.Fill" Value="Yellow" /&amp;gt;&lt;br /&gt;                    &amp;lt;Style.Triggers&amp;gt;&lt;br /&gt;                        &amp;lt;DataTrigger Binding="{Binding IsDataStreamFinished}" Value="true"&amp;gt;&lt;br /&gt;                            &amp;lt;Setter Property="Ellipse.Fill" Value="Green" /&amp;gt;&lt;br /&gt;                        &amp;lt;/DataTrigger&amp;gt;&lt;br /&gt;                    &amp;lt;/Style.Triggers&amp;gt;&lt;br /&gt;                &amp;lt;/Style&amp;gt;&lt;br /&gt;            &amp;lt;/Ellipse.Style&amp;gt;&lt;br /&gt;        &amp;lt;/Ellipse&amp;gt;&lt;br /&gt;    &amp;lt;/Grid&amp;gt;&lt;br /&gt;&amp;lt;/Window&amp;gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;As apparent from the above definition that the &lt;span style="font-style:italic;"&gt;DataContext &lt;/span&gt;is expected to have at least two properties &lt;span style="font-style:italic;"&gt;StudentList &lt;/span&gt;and &lt;span style="font-style:italic;"&gt;IsDataStreamFinished&lt;/span&gt;. The data from &lt;span style="font-style:italic;"&gt;StudentList &lt;/span&gt;is shown in the &lt;span style="font-style:italic;"&gt;ListBox&lt;/span&gt;. A customized &lt;span style="font-style:italic;"&gt;DataTemplate &lt;/span&gt;is defined to specify exactly how each member form the collection would be displayed. Each member of the collection &lt;span style="font-style:italic;"&gt;StudentList &lt;/span&gt;is expected to have two properties &lt;span style="font-style:italic;"&gt;StudentId &lt;/span&gt;and &lt;span style="font-style:italic;"&gt;StudentName&lt;/span&gt;. As soon as the value of &lt;span style="font-style:italic;"&gt;IsDataStreamFinished &lt;/span&gt;becomes true the &lt;span style="font-style:italic;"&gt;ellipse &lt;/span&gt;fills with &lt;span style="font-style:italic;"&gt;green &lt;/span&gt;color. This indicates the completion of data stream.&lt;br /&gt;&lt;br /&gt;As per the expectation of above view, the following view model is provided. It has both properties available i.e. &lt;span style="font-style:italic;"&gt;IsDataStreamFinished &lt;/span&gt;and &lt;span style="font-style:italic;"&gt;StudentList&lt;/span&gt;. This view model supports change notification of these properties by implementing &lt;span style="font-style:italic;"&gt;INotifyPropertyChanged &lt;/span&gt;interface. This requires to provide PropertyChanged event. This is raised through the setter of these properties providing the name of properties using magic strings.&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;class MainWindowViewModel : IObserver&amp;lt;Student&amp;gt;, INotifyPropertyChanged&lt;br /&gt;{        &lt;br /&gt;    #region Properties&lt;br /&gt;&lt;br /&gt;    private ObservableCollection&amp;lt;StudentViewModel&amp;gt; _studentList;&lt;br /&gt;    public ObservableCollection&amp;lt;StudentViewModel&amp;gt; StudentList&lt;br /&gt;    {&lt;br /&gt;        get { return _studentList; }&lt;br /&gt;        set&lt;br /&gt;        {&lt;br /&gt;            _studentList = value;&lt;br /&gt;            onPropertyChanged("StudentList");&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private bool _isDataStreamFinished;&lt;br /&gt;    public bool IsDataStreamFinished&lt;br /&gt;    {&lt;br /&gt;        get { return _isDataStreamFinished; }&lt;br /&gt;        set&lt;br /&gt;        {&lt;br /&gt;            _isDataStreamFinished = value;&lt;br /&gt;            onPropertyChanged("IsDataStreamFinished");&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    #endregion Properties&lt;br /&gt;&lt;br /&gt;    #region Observable Model&lt;br /&gt;        &lt;br /&gt;    //Model&lt;br /&gt;    private StudentsModel model;&lt;br /&gt;&lt;br /&gt;    #endregion Observable Model&lt;br /&gt;&lt;br /&gt;    IDisposable unsubscriber;&lt;br /&gt;&lt;br /&gt;    #region Constructor&lt;br /&gt;    &lt;br /&gt;    public MainWindowViewModel()&lt;br /&gt;    {&lt;br /&gt;        _studentList = new ObservableCollection&amp;lt;StudentViewModel&amp;gt;();&lt;br /&gt;&lt;br /&gt;        model = new StudentsModel();&lt;br /&gt;        unsubscriber = model.Subscribe(this);                   &lt;br /&gt;    }&lt;br /&gt;    &lt;br /&gt;    #endregion Constructor&lt;br /&gt;&lt;br /&gt;    #region IObserver implementation&lt;br /&gt;    public void OnCompleted()&lt;br /&gt;    {&lt;br /&gt;        IsDataStreamFinished = true;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public void OnError(Exception error)&lt;br /&gt;    {&lt;br /&gt;        //throw new NotImplementedException();&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public void OnNext(Student value)&lt;br /&gt;    {&lt;br /&gt;        //throw new NotImplementedException();&lt;br /&gt;        _studentList.Add(new StudentViewModel(value));&lt;br /&gt;    }&lt;br /&gt;    &lt;br /&gt;    #endregion IObserver implementation&lt;br /&gt;&lt;br /&gt;    #region INotifyPropertyChanged implementation&lt;br /&gt;    &lt;br /&gt;    public event PropertyChangedEventHandler PropertyChanged;&lt;br /&gt;    private void onPropertyChanged(string propertyname)&lt;br /&gt;    {&lt;br /&gt;        if (PropertyChanged != null)&lt;br /&gt;        {&lt;br /&gt;            PropertyChanged(this, new PropertyChangedEventArgs(propertyname));&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    #endregion INotifyPropertyChanged implementation&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;The view model also implements IObserver of Student i.e. IObserver&amp;lt;Student&amp;gt;. This makes it subscribe to the collection of &lt;span style="font-style:italic;"&gt;Student&lt;/span&gt; supporting observation by implementing &lt;span style="font-style:italic;"&gt;IObservable&amp;lt;Student&amp;gt;&lt;/span&gt; like our model defined later in the discussion. Implementing IObserver&amp;lt;Student&amp;gt; requires it to provide the definition of three methods i.e. &lt;span style="font-style:italic;"&gt;OnNext&lt;/span&gt;, &lt;span style="font-style:italic;"&gt;OnCompleted &lt;/span&gt;and &lt;span style="font-style:italic;"&gt;OnError&lt;/span&gt;. The &lt;span style="font-style:italic;"&gt;IObservable&lt;/span&gt; executes &lt;span style="font-style:italic;"&gt;OnNext&lt;/span&gt; of each &lt;span style="font-style:italic;"&gt;observer&lt;/span&gt; which is still subscribed. Similarly, &lt;span style="font-style:italic;"&gt;OnCompleted &lt;/span&gt;is executed by &lt;span style="font-style:italic;"&gt;IObservable&lt;/span&gt; when the collection subscribed by &lt;span style="font-style:italic;"&gt;IObserver &lt;/span&gt;is already completed. This might also be a subset of the actual collection. &lt;span style="font-style:italic;"&gt;OnError&lt;/span&gt; is resulted in case of any exception providing the detail of exception in the method parameter. &lt;br /&gt;&lt;br /&gt;In this example, &lt;span style="font-style:italic;"&gt;OnComplete()&lt;/span&gt; results in setting &lt;span style="font-style:italic;"&gt;IsDataStreamFinished &lt;/span&gt;to true. This would execute the data trigger in the view and fill the ellipse with Green. &lt;span style="font-style:italic;"&gt;OnNext()&lt;/span&gt; is resulting in the addition of a new instance of &lt;span style="font-style:italic;"&gt;StudentViewModel &lt;/span&gt;(constructed by using &lt;span style="font-style:italic;"&gt;Student &lt;/span&gt;available through method parameter). The definition of &lt;span style="font-style:italic;"&gt;StudentViewModel &lt;/span&gt;and &lt;span style="font-style:italic;"&gt;Student &lt;/span&gt;is as follows:&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;class StudentViewModel : INotifyPropertyChanged&lt;br /&gt;{&lt;br /&gt;    public StudentViewModel(Student student)&lt;br /&gt;    {&lt;br /&gt;        this.StudentId = student.StudentId;&lt;br /&gt;        this.StudentName = student.StudentName;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    #region Properties&lt;br /&gt;&lt;br /&gt;    private string _studentName;&lt;br /&gt;    public string StudentName&lt;br /&gt;    {&lt;br /&gt;        get { return _studentName; }&lt;br /&gt;        set &lt;br /&gt;        { &lt;br /&gt;            _studentName = value;&lt;br /&gt;            OnPropertyChanged("StudentName");&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private int _studentId;&lt;br /&gt;    public int StudentId&lt;br /&gt;    {&lt;br /&gt;        get { return _studentId; }&lt;br /&gt;        set&lt;br /&gt;        {&lt;br /&gt;            _studentId = value;&lt;br /&gt;            OnPropertyChanged("StudentId");&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    #endregion Properties&lt;br /&gt;&lt;br /&gt;    #region INotifyPropertyChanged implementation&lt;br /&gt;&lt;br /&gt;    public event PropertyChangedEventHandler  PropertyChanged;&lt;br /&gt;    private void OnPropertyChanged(string propertyName)&lt;br /&gt;    {&lt;br /&gt;        if (PropertyChanged != null)&lt;br /&gt;        {&lt;br /&gt;            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    #endregion INotifyPropertyChanged implementation&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;class Student &lt;br /&gt;{&lt;br /&gt;    public string StudentName { get; set; }&lt;br /&gt;    public int StudentId { get; set; }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;In the above definition &lt;span style="font-style:italic;"&gt;StudentViewModel &lt;/span&gt;implements &lt;span style="font-style:italic;"&gt;INotifyPropertyChanged &lt;/span&gt;to support change notifications.&lt;br /&gt;&lt;br /&gt;The Unsubscriber is the same as we used in previous post:&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;class Unsubscriber&amp;lt;T&amp;gt; : IDisposable&lt;br /&gt;{&lt;br /&gt;    private List&amp;lt;IObserver&amp;lt;T&amp;gt;&amp;gt; _observers;&lt;br /&gt;    private IObserver&amp;lt;T&amp;gt; _observer;&lt;br /&gt;&lt;br /&gt;    public Unsubscriber(List&amp;lt;IObserver&amp;lt;T&amp;gt;&amp;gt; observers, IObserver&amp;lt;T&amp;gt; observer)&lt;br /&gt;    {&lt;br /&gt;        this._observers = observers;&lt;br /&gt;        this._observer = observer;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public void Dispose()&lt;br /&gt;    {&lt;br /&gt;        if (_observer != null &amp;&amp; _observers.Contains(_observer))&lt;br /&gt;            _observers.Remove(_observer);&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;Now let us look at the definition of the model. It implements IObervable&amp;lt;Student&amp;gt;. This would enable it to support subscription of observers requiring the subscription. The only requirement is to provide definition of Subscribe method accepting the &lt;span style="font-style:italic;"&gt;IObservable &lt;/span&gt;of same type. As you can guess that in order to execute &lt;span style="font-style:italic;"&gt;OnNext&lt;/span&gt;, &lt;span style="font-style:italic;"&gt;OnCompleted &lt;/span&gt;and &lt;span style="font-style:italic;"&gt;OnError &lt;/span&gt;of these observers, the IObservable, somehow, needs to maintain observers in a form of list. The below model has &lt;span style="font-style:italic;"&gt;Observers &lt;/span&gt;List for the same purpose. &lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;class StudentsModel : IObservable&amp;lt;Student&amp;gt;&lt;br /&gt;{&lt;br /&gt;    private int _studentId;&lt;br /&gt;&lt;br /&gt;    public List&amp;lt;IObserver&amp;lt;Student&amp;gt;&amp;gt; observers = new List&amp;lt;IObserver&amp;lt;Student&amp;gt;&amp;gt;();&lt;br /&gt;&lt;br /&gt;    public StudentsModel()&lt;br /&gt;    {&lt;br /&gt;        t.Interval = TimeSpan.FromSeconds(1);&lt;br /&gt;        t.Tick += new EventHandler(t_Tick);&lt;br /&gt;&lt;br /&gt;        t.Start();&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    void t_Tick(object sender, EventArgs e)&lt;br /&gt;    {&lt;br /&gt;       _studentId++;&lt;br /&gt;       //throw new NotImplementedException();&lt;br /&gt;       var student = new Student()&lt;br /&gt;       {&lt;br /&gt;          StudentId = _studentId,&lt;br /&gt;          StudentName = string.Format("M{0}", _studentId)&lt;br /&gt;       };&lt;br /&gt;&lt;br /&gt;       if (_studentId &lt;= 20)&lt;br /&gt;       {&lt;br /&gt;          Observers.ForEach((observer) =&gt; observer.OnNext(student));&lt;br /&gt;       }&lt;br /&gt;       else&lt;br /&gt;       {&lt;br /&gt;          Observers.ForEach((observer) =&gt; observer.OnCompleted());&lt;br /&gt;          t.Stop();&lt;br /&gt;       }   &lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    DispatcherTimer t = new DispatcherTimer();&lt;br /&gt;&lt;br /&gt;    public IDisposable Subscribe(IObserver&amp;lt;Student&amp;gt; observer)&lt;br /&gt;    {&lt;br /&gt;        IDisposable unSubscriber = new Unsubscriber&amp;lt;Student&amp;gt;(Observers, observer);&lt;br /&gt;        if (!Observers.Contains(observer))&lt;br /&gt;        {&lt;br /&gt;            Observers.Add(observer);&lt;br /&gt;        }&lt;br /&gt;        return unSubscriber;&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;As the Observer calls Subscribe, it is added to the Observers list. This method returns an &lt;span style="font-style:italic;"&gt;IDisposable &lt;/span&gt;based object. This object can serve as an unsubscriber for getting updates through &lt;span style="font-style:italic;"&gt;OnNext&lt;/span&gt;, &lt;span style="font-style:italic;"&gt;OnCompleted &lt;/span&gt;and &lt;span style="font-style:italic;"&gt;OnNext &lt;/span&gt;through &lt;span style="font-style:italic;"&gt;IObservable&lt;/span&gt;. As we call dispose on the unsubscriber object, it removes the corresponding observer from the Observers list. Please see a wishful definition of unsubscriber from the last post.&lt;br /&gt;&lt;br /&gt;In order to simulate updates from another source, we have used Timer. This is a &lt;span style="font-style:italic;"&gt;DispatcherTimer &lt;/span&gt;with an interval of 1 second. For each timer tick, we are creating a new Student instance. We are calling &lt;span style="font-style:italic;"&gt;OnNext &lt;/span&gt;of each subscriber announcing the availability of a new Student. As we have seen in the view model, it would add a new &lt;span style="font-style:italic;"&gt;StudentViewModel &lt;/span&gt;to its list. This continues till 20 students are added.&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://1.bp.blogspot.com/_fVxKMZVpfzU/TVIzQsCi4NI/AAAAAAAAAyY/b0zlmzWixME/s1600/3.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 267px;" src="http://1.bp.blogspot.com/_fVxKMZVpfzU/TVIzQsCi4NI/AAAAAAAAAyY/b0zlmzWixME/s400/3.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5571572050803482834" /&gt;&lt;/a&gt;&lt;br /&gt;After which the timer stops simulating the end of data availability. This results in the execution of &lt;span style="font-style:italic;"&gt;OnCompleted &lt;/span&gt;method of each observer.&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://1.bp.blogspot.com/_fVxKMZVpfzU/TVI0hfd_kjI/AAAAAAAAAyg/lVpVyVzUJEI/s1600/4.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 267px;" src="http://1.bp.blogspot.com/_fVxKMZVpfzU/TVI0hfd_kjI/AAAAAAAAAyg/lVpVyVzUJEI/s400/4.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5571573438998352434" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Selective Members through IObservable:&lt;/span&gt;&lt;br /&gt;Being a dual of IEnumerable, IObservable supports the features provided by IEnumerable. It supports all standard &lt;span style="font-style:italic;"&gt;LSQO (LINQ Standard Query Operators)&lt;/span&gt; plus additional operators. These additional operators have also been copied to &lt;span style="font-style:italic;"&gt;IEnumerable &lt;/span&gt;later on.&lt;br /&gt;&lt;br /&gt;It must be remembered that we don't need to subscribe to the whole collection provided by &lt;span style="font-style:italic;"&gt;IObservable&lt;/span&gt;, we might subscribe to selective updates. Below, we are subscribing to only students whose &lt;span style="font-style:italic;"&gt;StudentId &lt;/span&gt;is even. We just need to update the subscription and the rest of the code should be equally useful. Below is the updated code for the constructor for &lt;span style="font-style:italic;"&gt;MainWindowViewModel &lt;/span&gt;for this requirement.&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;public MainWindowViewModel()&lt;br /&gt;{&lt;br /&gt;    _studentList = new ObservableCollection&amp;lt;StudentViewModel&amp;gt;();&lt;br /&gt;&lt;br /&gt;    model = new StudentsModel();&lt;br /&gt;   &lt;br /&gt;    unsubscriber = (from m in model &lt;br /&gt;                    where m.StudentId % 2 == 0&lt;br /&gt;                        select m).Subscribe(this);&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;The LINQ clause above is really &lt;span style="font-style:italic;"&gt;LINQ &lt;/span&gt;but it is not &lt;span style="font-style:italic;"&gt;LINQ to IEnumerable&lt;/span&gt; but it is &lt;span style="font-style:italic;"&gt;LINQ to IObservable&lt;/span&gt; (shipped for Reactive extension support). This is just subscribing to a subset of model whose &lt;span style="font-style:italic;"&gt;StudentId &lt;/span&gt;can be divided by 2 (definition of even number). We might want to take separate examination for even and odd students because of the limited seating availability in the examination hall. When we run the application, the final display is as follows:&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://3.bp.blogspot.com/_fVxKMZVpfzU/TVI4ruEcyDI/AAAAAAAAAyo/wWz-2zIwTYk/s1600/5.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 267px;" src="http://3.bp.blogspot.com/_fVxKMZVpfzU/TVI4ruEcyDI/AAAAAAAAAyo/wWz-2zIwTYk/s400/5.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5571578012762949682" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;In order to see another example of selection from IObservable, in the following code, we are subscribing for just 10 &lt;span style="font-style:italic;"&gt;Student&lt;/span&gt;(s) after first 2 &lt;span style="font-style:italic;"&gt;Student&lt;/span&gt;(s). The subscription code is as follows:&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;public MainWindowViewModel()&lt;br /&gt;{&lt;br /&gt;    _studentList = new ObservableCollection&amp;lt;StudentViewModel&amp;gt;();&lt;br /&gt;    model = new StudentsModel();&lt;br /&gt;    unsubscriber = model.Skip(2).Take&amp;lt;Student&amp;gt;(10).Subscribe(this);            &lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;When we run it, the finalized view becomes available as follows:&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://4.bp.blogspot.com/_fVxKMZVpfzU/TVI5lS-K_jI/AAAAAAAAAyw/dI4SXnXxLCU/s1600/6.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 267px;" src="http://4.bp.blogspot.com/_fVxKMZVpfzU/TVI5lS-K_jI/AAAAAAAAAyw/dI4SXnXxLCU/s400/6.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5571579001921273394" /&gt;&lt;/a&gt;&lt;br /&gt;As the subscription data becomes available, &lt;span style="font-style:italic;"&gt;OnCompleted &lt;/span&gt;is automatically called and &lt;span style="font-style:italic;"&gt;Dispose &lt;/span&gt;is called on the observer removing it from the Observers list in &lt;span style="font-style:italic;"&gt;IObservable &lt;/span&gt;implementation.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Updates on a non-UI Thread:&lt;/span&gt;&lt;br /&gt;I think it would be a usual case that &lt;span style="font-style:italic;"&gt;IObserver&lt;/span&gt; will have to observe &lt;span style="font-style:italic;"&gt;IObservable &lt;/span&gt;on a non-UI thread specially if &lt;span style="font-style:italic;"&gt;IObservable &lt;/span&gt;is model and &lt;span style="font-style:italic;"&gt;IObserver &lt;/span&gt;is a view model in &lt;span style="font-style:italic;"&gt;MVVM&lt;/span&gt;. &lt;br /&gt;&lt;br /&gt;Let's change the &lt;span style="font-style:italic;"&gt;Timer &lt;/span&gt;to &lt;span style="font-style:italic;"&gt;System.Timers.Timer&lt;/span&gt; and use its &lt;span style="font-style:italic;"&gt;Elapsed &lt;/span&gt;event to simulate updates. We know that System.Timers.Timer is a &lt;span style="font-style:italic;"&gt;multithreaded timer&lt;/span&gt;. Its event handler are executed on a &lt;span style="font-style:italic;"&gt;ThreadPool thread&lt;/span&gt;. If we generate &lt;span style="font-style:italic;"&gt;OnNext&lt;/span&gt;, &lt;span style="font-style:italic;"&gt;OnCompleted &lt;/span&gt;and &lt;span style="font-style:italic;"&gt;OnError &lt;/span&gt;updates then this can simulate updates in a non-UI thread.&lt;br /&gt;&lt;br /&gt;Let's update the definition of StudentsModel as follows:&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;class StudentsModel : IObservable&amp;lt;Student&amp;gt;&lt;br /&gt;{&lt;br /&gt;    private int _studentId;&lt;br /&gt;&lt;br /&gt;    public List&amp;lt;IObserver&amp;lt;Student&amp;gt;&amp;gt; Observers = &lt;br /&gt;        List&amp;lt;IObserver&amp;lt;Student&amp;gt;&amp;gt;();&lt;br /&gt;&lt;br /&gt;    public StudentsModel()&lt;br /&gt;    {&lt;br /&gt;        //For updates on non-UI thread&lt;br /&gt;        t.Elapsed += new ElapsedEventHandler(t_Elapsed);&lt;br /&gt;&lt;br /&gt;        t.Start();&lt;br /&gt;    }&lt;br /&gt;   &lt;br /&gt;    //For updates on a non-UI thread&lt;br /&gt;    void t_Elapsed(object sender, ElapsedEventArgs e)&lt;br /&gt;    {&lt;br /&gt;       _studentId++;&lt;br /&gt;        var student = new Student()&lt;br /&gt;        {&lt;br /&gt;            StudentId = _studentId,&lt;br /&gt;            StudentName = string.Format("M{0}", _studentId)&lt;br /&gt;        };&lt;br /&gt;&lt;br /&gt;        if (_studentId &lt;= 20)&lt;br /&gt;        {&lt;br /&gt;            Observers.ForEach((observer) =&gt; observer.OnNext(student));&lt;br /&gt;        }&lt;br /&gt;        else&lt;br /&gt;        {&lt;br /&gt;            Observers.ForEach((observer) =&gt; observer.OnCompleted());&lt;br /&gt;            t.Stop();&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;    &lt;br /&gt;    //For updates on a non-UI thread&lt;br /&gt;    Timer t = new Timer(1000);&lt;br /&gt;    &lt;br /&gt;    public IDisposable Subscribe(IObserver&amp;lt;Student&amp;gt; observer)&lt;br /&gt;    {&lt;br /&gt;        IDisposable unSubscriber = new Unsubscriber&amp;lt;Student&amp;gt;(Observers, observer);&lt;br /&gt;        if (!Observers.Contains(observer))&lt;br /&gt;        {&lt;br /&gt;            Observers.Add(observer);&lt;br /&gt;        }&lt;br /&gt;        return unSubscriber;&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;It builds just fine but when we run this it results in the following:&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://3.bp.blogspot.com/_fVxKMZVpfzU/TVI9tMX2wdI/AAAAAAAAAy4/9k-DYtJy7Oo/s1600/7.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 162px;" src="http://3.bp.blogspot.com/_fVxKMZVpfzU/TVI9tMX2wdI/AAAAAAAAAy4/9k-DYtJy7Oo/s400/7.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5571583535635415506" /&gt;&lt;/a&gt;&lt;br /&gt;Basically this exception is generated even for the very first Student added to the StudentList. Since &lt;span style="font-style:italic;"&gt;StudentList &lt;/span&gt;is bound to the &lt;span style="font-style:italic;"&gt;ListBox &lt;/span&gt;on the view and UI related elements have affinity to UI thread in WPF, that is why this exception is resulted. Being called from Elapsed event of &lt;span style="font-style:italic;"&gt;System.Timers.Timer&lt;/span&gt;, &lt;span style="font-style:italic;"&gt;OnNext &lt;/span&gt;is being executed on a &lt;span style="font-style:italic;"&gt;ThreadPool thread&lt;/span&gt;.&lt;br /&gt;&lt;br /&gt;As you could guess, we need to find out a way to observe on UI thread. So, even if these updates &lt;span style="font-style:italic;"&gt;OnNext&lt;/span&gt;, &lt;span style="font-style:italic;"&gt;OnCompleted &lt;/span&gt;and &lt;span style="font-style:italic;"&gt;OnError&lt;/span&gt; are resulted in a non-UI thread. The framework should automatically dispatch them in UI thread to be used by observer. This is basically a decision for each subscription i.e. It is possible that some &lt;span style="font-style:italic;"&gt;IObservers&lt;/span&gt;(s) are observing on &lt;span style="font-style:italic;"&gt;UI thread&lt;/span&gt; and others are just fine for a non-UI thread. &lt;br /&gt;&lt;br /&gt;Rx supports such dispatching. I am not sure but it might be using the same mechanism as used by &lt;span style="font-style:italic;"&gt;BackgroundWorker &lt;/span&gt;for executing its &lt;span style="font-style:italic;"&gt;ReportProgress &lt;/span&gt;and &lt;span style="font-style:italic;"&gt;WorkCompleted &lt;/span&gt;events. That uses &lt;span style="font-style:italic;"&gt;DispatcherSynchronizationContext&lt;/span&gt; provided by &lt;span style="font-style:italic;"&gt;ASynchronousOpertionManager&lt;/span&gt;. Let's subscribe on UI thread. In the following code, we are still interested in students with even Ids. Here we are using &lt;span style="font-style:italic;"&gt;ObserveOnDispathcher &lt;/span&gt;method of &lt;span style="font-style:italic;"&gt;Observable &lt;/span&gt;class. This is available in &lt;span style="font-style:italic;"&gt;System.Linq&lt;/span&gt; namespace in &lt;span style="font-style:italic;"&gt;System.Reactive&lt;/span&gt; assembly.&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;public MainWindowViewModel()&lt;br /&gt;{&lt;br /&gt;    _studentList = new ObservableCollection&amp;lt;StudentViewModel&amp;gt;();&lt;br /&gt;&lt;br /&gt;    model = new StudentsModel();&lt;br /&gt;&lt;br /&gt;    //observe on UI thread&lt;br /&gt;    unsubscriber = Observable.ObserveOnDispatcher&amp;lt;Student&amp;gt;(&lt;br /&gt;        (from m in model &lt;br /&gt;         where m.StudentId % 2 == 0&lt;br /&gt;         select m)&lt;br /&gt;         ).Subscribe(this);&lt;br /&gt;    &lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;When we run the application, it runs successfully now. The finalized display is as follows:&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://4.bp.blogspot.com/_fVxKMZVpfzU/TVJA9Qzes5I/AAAAAAAAAzA/gFDPP0jzIPA/s1600/8.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 267px;" src="http://4.bp.blogspot.com/_fVxKMZVpfzU/TVJA9Qzes5I/AAAAAAAAAzA/gFDPP0jzIPA/s400/8.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5571587110237811602" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Download:&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;iframe title ="Preview" scrolling="no" marginheight="0" marginwidth="0" frameborder="0" style="width:98px;height:115px;padding:0;background-color:#fcfcfc;" src="http://cid-b5fee7d7acde5072.office.live.com/embedicon.aspx/MVVM%20Reactive%20Model%202/MVVM^_ReactiveModels^_.zip"&gt;&lt;/iframe&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8085117242240449595-8932532203480715572?l=www.shujaat.net' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.shujaat.net/feeds/8932532203480715572/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8085117242240449595&amp;postID=8932532203480715572&amp;isPopup=true' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/8932532203480715572'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/8932532203480715572'/><link rel='alternate' type='text/html' href='http://www.shujaat.net/2011/02/wpf-iobservable-collection-based.html' title='WPF - IObservable Collection based Reactive Models In MVVM (Rx)'/><author><name>Muhammad Shujaat Siddiqi</name><uri>http://www.blogger.com/profile/02519138704633566929</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://4.bp.blogspot.com/_fVxKMZVpfzU/TVIhNFgXXtI/AAAAAAAAAyI/dsKdZHeEuYo/s72-c/1.jpg' height='72' width='72'/><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8085117242240449595.post-5835532239221000404</id><published>2011-02-06T22:23:00.008-06:00</published><updated>2011-02-08T00:19:28.733-06:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='MVVM'/><category scheme='http://www.blogger.com/atom/ns#' term='Rx'/><category scheme='http://www.blogger.com/atom/ns#' term='wpf'/><category scheme='http://www.blogger.com/atom/ns#' term='IObserver'/><category scheme='http://www.blogger.com/atom/ns#' term='IObservable'/><category scheme='http://www.blogger.com/atom/ns#' term='Reactive extension'/><title type='text'>MVVM and Reactive Models (Using Reactive Extension Rx.Net)</title><content type='html'>In this post we will be discussing the possible usage of Reactive Extension for our models in MVVM. It is also famous with the names &lt;span style="font-style:italic;"&gt;Rx.Net&lt;/span&gt;. As we know that &lt;span style="font-style:italic;"&gt;IEnumerable&lt;/span&gt; based collections are pull based collections. We get an &lt;span style="font-style:italic;"&gt;IEnumerator&lt;/span&gt; from &lt;span style="font-style:italic;"&gt;IEnumerable&lt;/span&gt; using &lt;span style="font-style:italic;"&gt;GetEnumerator&lt;/span&gt; method. Then we keep looping through the enumerator using &lt;span style="font-style:italic;"&gt;MoveNext()&lt;/span&gt; pulling each member and accessing it with &lt;span style="font-style:italic;"&gt;Current &lt;/span&gt;property. We certainly have no other choice, except to work around through events, when a push based mechanism is required for property updates and collection add members availability. Reactive Extension is basically an attempt to provide the same functionality. This makes it a mathematical dual of existing &lt;span style="font-style:italic;"&gt;IEnumerable&lt;/span&gt;. This functionality is introduced in .net 4.0 using two interfaces &lt;span style="font-style:italic;"&gt;IObserver&lt;/span&gt; and &lt;span style="font-style:italic;"&gt;IObservable&lt;/span&gt;. &lt;br /&gt;&lt;br /&gt;We are attempting to exploit the features of these two interfaces to get the benefits of push based updates from our models. Model might be updated due to any updates in the back-end system. We are trying to update these updates using these contract to the &lt;span style="font-style:italic;"&gt;view model&lt;/span&gt;. Currently we use events based mechanism to propagate these changes to the view model which is another implementation of &lt;span style="font-style:italic;"&gt;Observer pattern&lt;/span&gt; in .net.&lt;br /&gt;&lt;br /&gt;Let's create a simple view with two Text Blocks. One TextBlock is to display the &lt;span style="font-style:italic;"&gt;name of Student&lt;/span&gt; and other is to show it's &lt;span style="font-style:italic;"&gt;Id&lt;/span&gt;. As you can see in the code below that they are bound to &lt;span style="font-style:italic;"&gt;StudentName &lt;/span&gt;and &lt;span style="font-style:italic;"&gt;StudentId &lt;/span&gt;properties of &lt;span style="font-style:italic;"&gt;DataContext&lt;/span&gt;.&lt;br /&gt;&lt;pre class="brush: xml; gutter: false;"&gt;&lt;br /&gt;&amp;lt;Window x:Class="WpfApp_MVVM_ReactiveModels.MainWindow"&lt;br /&gt;        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"&lt;br /&gt;        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&lt;br /&gt;        xmlns:local="clr-namespace:WpfApp_MVVM_ReactiveModels"&lt;br /&gt;        Title="MainWindow" Height="350" Width="690"&amp;gt;&lt;br /&gt;    &amp;lt;Window.DataContext&amp;gt;&lt;br /&gt;        &amp;lt;local:MainWindowViewModel /&amp;gt;&lt;br /&gt;    &amp;lt;/Window.DataContext&amp;gt;&lt;br /&gt;    &amp;lt;Grid&amp;gt;&lt;br /&gt;        &amp;lt;TextBlock Height="36" HorizontalAlignment="Left" Margin="272,46,0,0" &lt;br /&gt;                   Name="textBlock1" VerticalAlignment="Top" Width="326" &lt;br /&gt;                   Text="{Binding StudentName}" /&amp;gt;&lt;br /&gt;&lt;br /&gt;        &amp;lt;TextBlock Height="32" HorizontalAlignment="Left" Margin="270,116,0,0" &lt;br /&gt;                   Name="textBlock2" VerticalAlignment="Top" Width="330" &lt;br /&gt;                   Text="{Binding StudentId}" /&amp;gt;&lt;br /&gt;    &amp;lt;/Grid&amp;gt;&lt;br /&gt;&amp;lt;/Window&amp;gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;As shown in the above XAML code, the data context is assigned with a new instance of &lt;span style="font-style:italic;"&gt;MainWindowViewModel&lt;/span&gt;. So this view model is expected to have the properties &lt;span style="font-style:italic;"&gt;StudentName &lt;/span&gt;and &lt;span style="font-style:italic;"&gt;StudentId &lt;/span&gt;so that the text blocks could bind their Text properties to them.&lt;br /&gt;&lt;br /&gt;Let's define the expected view model now. We need to provide change notification support for any updates in &lt;span style="font-style:italic;"&gt;StudentName &lt;/span&gt;and &lt;span style="font-style:italic;"&gt;StudentId &lt;/span&gt;properties to the view. It is provided by implementing &lt;span style="font-style:italic;"&gt;INotifyPropertyChange &lt;/span&gt;interface. It has the only requirement is to provide a &lt;span style="font-style:italic;"&gt;PropertyChanged &lt;/span&gt;event. Now the view model needs to update itself based on the updates in the model. For that, it has to observe the changes in the I. In the constructor, It is subscribing using &lt;span style="font-style:italic;"&gt;Subscribe()&lt;/span&gt; method available in the model. The only requirement to implement IObservable is to implement three methods &lt;span style="font-style:italic;"&gt;OnNext&lt;/span&gt;, &lt;span style="font-style:italic;"&gt;OnCompleted &lt;/span&gt;and &lt;span style="font-style:italic;"&gt;OnError &lt;/span&gt;methods. OnNext provides the new member added the collection. It can very well provide the updated model. We are using it to provide the updated model instance (&lt;span style="font-style:italic;"&gt;Student&lt;/span&gt;). Similarly, &lt;span style="font-style:italic;"&gt;OnError&lt;/span&gt; can be used to communicate and Exception message the the observer. For this simple example, We are simple ignoring the implementation of &lt;span style="font-style:italic;"&gt;OnCompleted &lt;/span&gt;and &lt;span style="font-style:italic;"&gt;OnError &lt;/span&gt; methods. &lt;span style="font-style:italic;"&gt;OnNext()&lt;/span&gt; gives us access to the updated Student object. We are using it to update the view model properties. The updates in the view model's properties are propagated to the view using &lt;span style="font-style:italic;"&gt;WPF Data Binding&lt;/span&gt; system.&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;namespace WpfApp_MVVM_ReactiveModels&lt;br /&gt;{&lt;br /&gt;    using System;&lt;br /&gt;    using System.ComponentModel;&lt;br /&gt;&lt;br /&gt;    class MainWindowViewModel : IObserver&amp;lt;Student&amp;gt;, INotifyPropertyChanged&lt;br /&gt;    {&lt;br /&gt;        //Model&lt;br /&gt;        Student Model;&lt;br /&gt;&lt;br /&gt;        //Constructor&lt;br /&gt;        public MainWindowViewModel()&lt;br /&gt;        {&lt;br /&gt;            Model = new Student();&lt;br /&gt;            this.StudentId = Model.StudentId;&lt;br /&gt;            this.StudentName = Model.StudentName;&lt;br /&gt;            &lt;br /&gt;            //subscribe observer to the Model&lt;br /&gt;            Model.Subscribe(this); &lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        #region Properties&lt;br /&gt;&lt;br /&gt;        string _studentName;&lt;br /&gt;        public string StudentName&lt;br /&gt;        {&lt;br /&gt;            get { return _studentName; }&lt;br /&gt;            set&lt;br /&gt;            {&lt;br /&gt;                _studentName = value;&lt;br /&gt;                onPropertyChanged("StudentName");&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        int _studentId;&lt;br /&gt;        public int StudentId&lt;br /&gt;        {&lt;br /&gt;            get { return _studentId; }&lt;br /&gt;            set&lt;br /&gt;            {&lt;br /&gt;                _studentId = value;&lt;br /&gt;                onPropertyChanged("StudentId");&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        #endregion Properties&lt;br /&gt;&lt;br /&gt;        #region IObserver implementation&lt;br /&gt;&lt;br /&gt;        public void OnCompleted()&lt;br /&gt;        {&lt;br /&gt;            //throw new NotImplementedException();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public void OnError(Exception error)&lt;br /&gt;        {&lt;br /&gt;            //throw new NotImplementedException();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public void OnNext(Student value)&lt;br /&gt;        {&lt;br /&gt;            //throw new NotImplementedException();&lt;br /&gt;            this.StudentId = value.StudentId;&lt;br /&gt;            this.StudentName = value.StudentName;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        #endregion IObserver implementation&lt;br /&gt;&lt;br /&gt;        #region INotifyPropertyChanged implemention&lt;br /&gt;        public event PropertyChangedEventHandler PropertyChanged;&lt;br /&gt;&lt;br /&gt;        private void onPropertyChanged(string propertyName)&lt;br /&gt;        {&lt;br /&gt;            if (PropertyChanged != null)&lt;br /&gt;            {&lt;br /&gt;                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        #endregion INotifyPropertyChanged implemention&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;Now we define our model (&lt;span style="font-style:italic;"&gt;Student&lt;/span&gt;). It has two properties &lt;span style="font-style:italic;"&gt;StudentName &lt;/span&gt;and &lt;span style="font-style:italic;"&gt;StudentId &lt;/span&gt;as expected by the above view model. In order to be observable, we are implementing &lt;span style="font-style:italic;"&gt;IObservable &lt;/span&gt;interface for this. &lt;span style="font-style:italic;"&gt;IObservable &lt;/span&gt;keeps a list of all observers so that they could be notified in case any updates. The only requirement of the contract is &lt;span style="font-style:italic;"&gt;Subscribe &lt;/span&gt;method. This method is supposed to return an &lt;span style="font-style:italic;"&gt;IDisposable&lt;/span&gt;. Disposing this should be unsubscribing this observer.&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;class Student : IObservable&amp;lt;Student&amp;gt;&lt;br /&gt;{&lt;br /&gt;    public string StudentName { get; set; }&lt;br /&gt;    public int StudentId { get; set; }&lt;br /&gt;&lt;br /&gt;    List&amp;lt;IObserver&amp;lt;Student&amp;gt;&amp;gt; observers = new List&amp;lt;IObserver&amp;lt;Student&amp;gt;&amp;gt;();&lt;br /&gt;    Timer t = new Timer(2000);   &lt;br /&gt;&lt;br /&gt;    public Student()&lt;br /&gt;    {&lt;br /&gt;        StudentId = 1;&lt;br /&gt;        StudentName = "Muhammad";&lt;br /&gt;        &lt;br /&gt;        t.Elapsed += new ElapsedEventHandler(t_Elapsed);&lt;br /&gt;        t.Interval = 1000;&lt;br /&gt;        t.Start();&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    void t_Elapsed(object sender, ElapsedEventArgs e)&lt;br /&gt;    {&lt;br /&gt;        this.StudentId++;&lt;br /&gt;        if (StudentId != 20)&lt;br /&gt;        {&lt;br /&gt;            observers.ForEach((observer) =&gt; observer.OnNext(this));&lt;br /&gt;        }&lt;br /&gt;        else&lt;br /&gt;        {&lt;br /&gt;            observers.ForEach((observer) =&gt; observer.OnCompleted());&lt;br /&gt;            t.Stop();&lt;br /&gt;        }        &lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    //implementation of IObservable&lt;br /&gt;    public IDisposable Subscribe(IObserver&amp;lt;Student&amp;gt; observer)&lt;br /&gt;    {            &lt;br /&gt;        if (!observers.Contains(observer))&lt;br /&gt;        {&lt;br /&gt;            observers.Add(observer);&lt;br /&gt;        }&lt;br /&gt;     &lt;br /&gt;        return new Unsubscriber&amp;lt;Student&amp;gt;(observers, observer);&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;In order to simulate the updates, we are using a &lt;span style="font-style:italic;"&gt;Timer &lt;/span&gt;to update the properties. In the &lt;span style="font-style:italic;"&gt;Tick&lt;/span&gt; event handler we are updating &lt;span style="font-style:italic;"&gt;StudentId&lt;/span&gt;.  Until StudentId is lesser than 20, it keeps notifying the observers using &lt;span style="font-style:italic;"&gt;OnNext()&lt;/span&gt; on the observers. After that it notifies them about the completion of all updates using &lt;span style="font-style:italic;"&gt;OnCompleted()&lt;/span&gt; method.&lt;br /&gt;&lt;br /&gt;We define the &lt;span style="font-style:italic;"&gt;UnSubscriber &lt;/span&gt; as used in the above model. It is implementing an &lt;span style="font-style:italic;"&gt;IDisposable&lt;/span&gt;. When it is being constructed, the observer is added to the &lt;span style="font-style:italic;"&gt;_observers&lt;/span&gt; collection. As expected, it is removing the observer from the observer list in the model.&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;class Unsubscriber&lt;T&gt; : IDisposable&lt;br /&gt;{&lt;br /&gt;    private List&amp;lt;IObserver&amp;lt;T&amp;gt;&amp;gt; _observers;&lt;br /&gt;    private IObserver&amp;lt;T&amp;gt; _observer;&lt;br /&gt;&lt;br /&gt;    public Unsubscriber(List&amp;lt;IObserver&amp;lt;T&amp;gt;&amp;gt; observers, IObserver&amp;lt;T&amp;gt; observer)&lt;br /&gt;    {&lt;br /&gt;        this._observers = observers;&lt;br /&gt;        this._observer = observer;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public void Dispose()&lt;br /&gt;    {&lt;br /&gt;        if (_observer != null &amp;&amp; _observers.Contains(_observer))&lt;br /&gt;        {&lt;br /&gt;            _observers.Remove(_observer);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;When we run the application, it is shown as follows:&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://3.bp.blogspot.com/_fVxKMZVpfzU/TVDFEr_mf9I/AAAAAAAAAxo/2cRzDpXXrEA/s1600/1.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 203px;" src="http://3.bp.blogspot.com/_fVxKMZVpfzU/TVDFEr_mf9I/AAAAAAAAAxo/2cRzDpXXrEA/s400/1.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5571169423376941010" /&gt;&lt;/a&gt;&lt;br /&gt;After &lt;span style="font-style:italic;"&gt;OnCompleted()&lt;/span&gt;, the StudentId has the value 19. The view is finally updated as follows:&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://4.bp.blogspot.com/_fVxKMZVpfzU/TVDFEqID1VI/AAAAAAAAAxw/ZFAW8zrW4Ig/s1600/2.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 203px;" src="http://4.bp.blogspot.com/_fVxKMZVpfzU/TVDFEqID1VI/AAAAAAAAAxw/ZFAW8zrW4Ig/s400/2.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5571169422875546962" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Note:&lt;/span&gt;&lt;br /&gt;This is one of the times when you desperately need some feature but restricted due to its non-availability in the language. Unlike Java, C# does not support anonymous inner classes. It just supports anonymous types which can not implement an interface and can encapsulate no methods.&lt;br /&gt;&lt;pre class="brush: csharp; gutter: false;"&gt;&lt;br /&gt;return new IDisposable()&lt;br /&gt;{&lt;br /&gt;    //well java also has this limitation that an inner class can only access final members of enclosing method. In this case observer is not final :(. Let's assume it does. This would be the ideal implementation.&lt;br /&gt;    IObserver&amp;lt;Studen&amp;gt; localObserver = observer;&lt;br /&gt;&lt;br /&gt;    public void Dispose()&lt;br /&gt;    {&lt;br /&gt;        if (localObserver != null &amp;&amp; observers.Contains(localObserver))&lt;br /&gt;        {&lt;br /&gt;            observers.Remove(localObserver);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;As you can see that I have used observers collection of class containing this anonymous class which is a feature of Java anonymous inner classes. This is not supported by C#, Alas!&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Timer event Handlers in other threads:&lt;/span&gt;&lt;br /&gt;In this example we have used &lt;span style="font-style:italic;"&gt;System.Timers.Timer&lt;/span&gt;. As we have discussed earlier that the event handlers for the Elapsed event of this timer is executed on ThreadPool thread.&lt;br /&gt;&lt;br /&gt;&lt;a href="http://shujaatsiddiqi.blogspot.com/2010/10/timers-for-net-applications.html"&gt;http://shujaatsiddiqi.blogspot.com/2010/10/timers-for-net-applications.html&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Because of this&lt;span style="font-style:italic;"&gt; OnNext()&lt;/span&gt;,&lt;span style="font-style:italic;"&gt; OnCompleted()&lt;/span&gt; and &lt;span style="font-style:italic;"&gt;OnError()&lt;/span&gt; are also executed in &lt;span style="font-style:italic;"&gt;ThreadPool &lt;/span&gt;thread.&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://1.bp.blogspot.com/_fVxKMZVpfzU/TVDG5oOoy8I/AAAAAAAAAx4/DI1ZGO3jvKg/s1600/3.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 178px;" src="http://1.bp.blogspot.com/_fVxKMZVpfzU/TVDG5oOoy8I/AAAAAAAAAx4/DI1ZGO3jvKg/s400/3.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5571171432410958786" /&gt;&lt;/a&gt;&lt;br /&gt;Since UI related controls have thread affinity to UI thread then how come we don't have any exception? Basically this is because of implicit dispatching of updates to UI thread by the setters in &lt;span style="font-style:italic;"&gt;INotifyPropertyChanged&lt;/span&gt;. No matter from what thread the updates take place, they are always successfully dispatched to UI thread.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Download:&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;iframe title ="Preview" scrolling="no" marginheight="0" marginwidth="0" frameborder="0" style="width:98px;height:115px;padding:0;background-color:#fcfcfc;" src="http://cid-b5fee7d7acde5072.office.live.com/embedicon.aspx/MVVM%20Reactive%20Model/WpfApp^_MVVM^_ReactiveModels.zip"&gt;&lt;/iframe&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8085117242240449595-5835532239221000404?l=www.shujaat.net' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.shujaat.net/feeds/5835532239221000404/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8085117242240449595&amp;postID=5835532239221000404&amp;isPopup=true' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/5835532239221000404'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8085117242240449595/posts/default/5835532239221000404'/><link rel='alternate' type='text/html' href='http://www.shujaat.net/2011/02/mvvm-and-reactive-models-using-reactive.html' title='
