<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://devlicio.us/utility/FeedStylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>.NET &amp; Funky Fresh : WP7, Tutorial, Caliburn</title><link>http://devlicio.us/blogs/rob_eisenberg/archive/tags/WP7/Tutorial/Caliburn/default.aspx</link><description>Tags: WP7, Tutorial, Caliburn</description><dc:language>en</dc:language><generator>CommunityServer 2008.5 SP1 (Build: 31106.3070)</generator><item><title>Caliburn.Micro Soup to Nuts Part 9–New WP7 Features</title><link>http://devlicio.us/blogs/rob_eisenberg/archive/2011/06/09/caliburn-micro-soup-to-nuts-part-9-new-wp7-features.aspx</link><pubDate>Thu, 09 Jun 2011 17:23:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:67721</guid><dc:creator>Rob Eisenberg</dc:creator><slash:comments>5</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/rob_eisenberg/rsscomments.aspx?PostID=67721</wfw:commentRss><comments>http://devlicio.us/blogs/rob_eisenberg/archive/2011/06/09/caliburn-micro-soup-to-nuts-part-9-new-wp7-features.aspx#comments</comments><description>&lt;p&gt;In version 1.0 we had pretty good support for building apps for WP7, but in v1.1 we&amp;rsquo;ve taken things up a notch. Let&amp;rsquo;s look at the same HelloWP7 sample that we did &lt;a target="_blank" href="http://caliburnmicro.codeplex.com/wikipage?title=Working%20with%20Windows%20Phone%207&amp;amp;referringTitle=Documentation"&gt;previously&lt;/a&gt;, but see how it&amp;rsquo;s been updated to take advantage of our improved tombstoning, launcher/chooser support and strongly typed navigation. You&amp;rsquo;ll also notice that the code is cleaner overall.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Bootstrapper&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Here&amp;rsquo;s the cleaned up boostrapper in v1.1.&lt;/p&gt;
&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;public class HelloWP7Bootstrapper : PhoneBootstrapper {
    PhoneContainer container;

    protected override void Configure() {
        container = new PhoneContainer(RootFrame);

        container.RegisterPhoneServices();
        container.PerRequest&amp;lt;MainPageViewModel&amp;gt;();
        container.PerRequest&amp;lt;PivotPageViewModel&amp;gt;();
        container.PerRequest&amp;lt;TabViewModel&amp;gt;();

        AddCustomConventions();
    }

    static void AddCustomConventions() {
        //ellided
    }

    protected override object GetInstance(Type service, string key) {
        return container.GetInstance(service, key);
    }

    protected override IEnumerable&amp;lt;object&amp;gt; GetAllInstances(Type service) {
        return container.GetAllInstances(service);
    }

    protected override void BuildUp(object instance) {
        container.BuildUp(instance);
    }
}&lt;/pre&gt;
&lt;p&gt;There are two things to notice here. First, we&amp;rsquo;ve removed all the manual Caliburn.Micro service configuration and pushed it into the SimpleContainer. That gives you one line of code to configure the framework if you are using the OOTB container. Speaking of which, we now provide the SimpleContainer officially in the Caliburn.Micro.Extensions assembly. That helps you get started faster. You can always plug your own in, of coarse. In addition to the simplified configuration, notice that the ViewModels for pages are no longer registered using a string key. For v1.1 our ViewModelLocator has been re-implemented to pull VMs from the container by Type rather than key. It now follows the exact same naming strategies as the ViewLocator (but in reverse) and even derives possible interface names so that it resolves VMs from the container correctly. This both improves the consistency of ViewModel location as well as makes the configuration simpler.&lt;/p&gt;
&lt;p&gt;The boostrapper is added to your App.xaml as always:&lt;/p&gt;
&lt;pre name="code" class="xml:nogutter:nocontrols"&gt;&amp;lt;Application x:Class=&amp;quot;Caliburn.Micro.HelloWP7.App&amp;quot;
             xmlns=&amp;quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&amp;quot;
             xmlns:x=&amp;quot;http://schemas.microsoft.com/winfx/2006/xaml&amp;quot;
             xmlns:local=&amp;quot;clr-namespace:Caliburn.Micro.HelloWP7&amp;quot;&amp;gt;
    &amp;lt;Application.Resources&amp;gt;
        &amp;lt;local:HelloWP7Bootstrapper x:Key=&amp;quot;bootstrapper&amp;quot; /&amp;gt;
    &amp;lt;/Application.Resources&amp;gt;
&amp;lt;/Application&amp;gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Important Note About App.xaml.cs&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;If you create your WP7 application using a standard Visual Studio template, the generated App.xaml.cs file will have a lot of code in it. The purpose of this code is to set up the root frame for the application and make sure everything gets initialized properly. Of course, that&amp;#39;s what the bootstrapper&amp;#39;s job is too (and in fact it does a few things better than the out-of-the-box code in addition to configuring CM). So, you don&amp;#39;t need both. When using CM&amp;#39;s PhoneBootstrapper, be sure to clear out all the code from the App.xaml.cs file except for the call to InitializeComponent in the constructor.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;INavigationService&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Let&amp;rsquo;s review what CM&amp;rsquo;s INavigationService&amp;nbsp; does for you. First, remember that WP7 enforces a View-First approach to UI at the platform level. Like it or not, the platform is going to create pages at will and the Frame control is going to conduct your application thusly. You don&amp;rsquo;t get to control that and there are no extensibility points, unlike the Silverlight version of the navigation framework. Rather than fight this, I&amp;rsquo;m going to recommend embracing the View-First approach for Pages in WP7, but maintaining a Model-First composition strategy for the sub-components of those pages and a Model-First approach to coding against the navigation system. In order to bridge this gap, I&amp;rsquo;ve enabled the INavigationService to hook into the native navigation frame&amp;rsquo;s functionality and augment it with the following behaviors:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;When Navigating To a Page&lt;/em&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Use the new ViewModelLocator to conventionally determine the Type of the VM that should be attached to the page being navigated to. Pull that VM by Type out of the container.&lt;/li&gt;
&lt;li&gt;If a VM is found, use the ViewModelBinder to connect the Page to the located ViewModel.&lt;/li&gt;
&lt;li&gt;Examine the Page&amp;rsquo;s QueryString. Look for properties on the VM that match the QueryString parameters and inject them, performing the necessary type coercion.&lt;/li&gt;
&lt;li&gt;If the ViewModel implements the IActivate interface, call its Activate method.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;em&gt;When Navigating Away From a Page&lt;/em&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Detect whether the associated ViewModel implements the IGuardClose interface.&lt;/li&gt;
&lt;li&gt;If IGuardClose is implemented and the app is not being tombstoned or closed, invoke the CanClose method and use its result to optionally cancel page navigation.&lt;sup&gt;1&lt;/sup&gt;&lt;/li&gt;
&lt;li&gt;If the ViewModel can close and implements the IDeactivate interface, call it&amp;rsquo;s Deactivate method. Always pass &amp;ldquo;false&amp;rdquo; to indicate that the VM should deactivate, but not necessarily close. This is because the phone may be deactivating, but not actually tombstoning or closing. There&amp;rsquo;s no way to know.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The behavior of the navigation service allows the correct VM to be hooked up to the page, allows that VM to be notified that it is being navigated to (IActivate), allows it to prevent navigation away from the current page (IGuardClose) and allows it to clean up after itself on navigation away, tombstoning or normal &amp;ldquo;closing&amp;rdquo; of the application (IDeactivate). All these interfaces (and a couple more) are implemented by the Screen class. If you prefer not to inherit from Screen, you can implement any of the interfaces individually of coarse. They provide a nice View-Model-Centric, testable and predictable way of responding to navigation without needing to wire up a ton of event handlers or write important application flow logic in the page&amp;rsquo;s code-behind.&lt;/p&gt;
&lt;p&gt;These hooks into phone navigation enable a really smooth way of interacting with the phone&amp;rsquo;s navigation lifecycle. But now that we have an improved ViewModelLocator that matches exactly the ViewLocator and works on types, we can take things further. In v1.1 we&amp;rsquo;ve introduced support for strongly-typed navigation. Here&amp;rsquo;s what the new MainPageViewModel from the sample looks like using this new feature:&lt;/p&gt;
&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;public class MainPageViewModel {
    readonly INavigationService navigationService;

    public MainPageViewModel(INavigationService navigationService) {
        this.navigationService = navigationService;
    }

    public void GotoPageTwo() {
        navigationService.UriFor&amp;lt;PivotPageViewModel&amp;gt;()
            .WithParam(x =&amp;gt; x.NumberOfTabs, 5)
            .Navigate();
    }
}&lt;/pre&gt;
&lt;p&gt;This allows you to specify a ViewModel to navigate to along with the query string parameters. Since this all happens using generics and lambdas, you can never miss-type a page Uri or mess up your query strings&amp;hellip;.and refactoring will work beautifully.&lt;/p&gt;
&lt;p&gt;For the sake of completeness, here&amp;rsquo;s the page that will be bound to MainPageViewModel:&lt;/p&gt;
&lt;pre name="code" class="xml:nogutter:nocontrols"&gt;&amp;lt;phone:PhoneApplicationPage x:Class=&amp;quot;Caliburn.Micro.HelloWP7.MainPage&amp;quot;
                            xmlns=&amp;quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&amp;quot;
                            xmlns:x=&amp;quot;http://schemas.microsoft.com/winfx/2006/xaml&amp;quot;
                            xmlns:phone=&amp;quot;clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone&amp;quot;
                            xmlns:shell=&amp;quot;clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone&amp;quot;
                            xmlns:cal=&amp;quot;clr-namespace:Caliburn.Micro;assembly=Caliburn.Micro&amp;quot;
                            SupportedOrientations=&amp;quot;Portrait&amp;quot;
                            Orientation=&amp;quot;Portrait&amp;quot;
                            shell:SystemTray.IsVisible=&amp;quot;True&amp;quot;&amp;gt;
    &amp;lt;Grid Background=&amp;quot;Transparent&amp;quot;&amp;gt;
        &amp;lt;Grid.RowDefinitions&amp;gt;
            &amp;lt;RowDefinition Height=&amp;quot;Auto&amp;quot; /&amp;gt;
            &amp;lt;RowDefinition Height=&amp;quot;*&amp;quot; /&amp;gt;
        &amp;lt;/Grid.RowDefinitions&amp;gt;
        &amp;lt;StackPanel Grid.Row=&amp;quot;0&amp;quot;
                    Margin=&amp;quot;24,24,0,12&amp;quot;&amp;gt;
            &amp;lt;TextBlock Text=&amp;quot;WP7 Caliburn.Micro&amp;quot;
                       Style=&amp;#39;{StaticResource PhoneTextNormalStyle}&amp;#39; /&amp;gt;
            &amp;lt;TextBlock Text=&amp;#39;Main Page&amp;#39;
                       Margin=&amp;#39;-3,-8,0,0&amp;#39;
                       Style=&amp;#39;{StaticResource PhoneTextTitle1Style}&amp;#39; /&amp;gt;
        &amp;lt;/StackPanel&amp;gt;

        &amp;lt;Grid Grid.Row=&amp;#39;1&amp;#39;&amp;gt;
            &amp;lt;Button x:Name=&amp;#39;GotoPageTwo&amp;#39;
                    Content=&amp;#39;Goto Page Two&amp;#39; /&amp;gt;
        &amp;lt;/Grid&amp;gt;
    &amp;lt;/Grid&amp;gt;

    &amp;lt;phone:PhoneApplicationPage.ApplicationBar&amp;gt;
        &amp;lt;shell:ApplicationBar IsVisible=&amp;#39;True&amp;#39;&amp;gt;
            &amp;lt;shell:ApplicationBar.Buttons&amp;gt;
                &amp;lt;cal:AppBarButton IconUri=&amp;#39;ApplicationIcon.png&amp;#39;
                                  Text=&amp;#39;Page Two&amp;#39;
                                  Message=&amp;#39;GotoPageTwo&amp;#39; /&amp;gt;
            &amp;lt;/shell:ApplicationBar.Buttons&amp;gt;
        &amp;lt;/shell:ApplicationBar&amp;gt;
    &amp;lt;/phone:PhoneApplicationPage.ApplicationBar&amp;gt;
&amp;lt;/phone:PhoneApplicationPage&amp;gt;&lt;/pre&gt;
&lt;p&gt;There&amp;rsquo;s really nothing new here in v1.1. But I just wanted to remind you that Caliburn.Micro supports Actions on the AppBar&amp;nbsp; as long as you use CM&amp;rsquo;s AppBarButton and AppBarMenuItem :) &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;IPhoneService&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The IPhoneService wraps the phone&amp;rsquo;s frame and provides access to important information and events. We had this service in v1.0 but we&amp;rsquo;ve expanded it in v1.1 to expose a better event model. Those familiar with WP7 know that the phone has a series of events that fire in different circumstances: Launching, Activated, Deactivated and Closing. Unfortunately, these events obscure whether the phone is actually resurrecting from a tombstoned state or simply continuing execution. The current SDK does not make it easy for the developer to actually determine this, so Caliburn.Micro does the heavy lifting for you and provides the following event model:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Launching - Occurs when a fresh instance of the application is launching.&lt;/li&gt;
&lt;li&gt;Activated - Occurs when a previously paused/tombstoned app is resumed/resurrected.&lt;/li&gt;
&lt;li&gt;Deactivated - Occurs when the application is being paused or tombstoned.&lt;/li&gt;
&lt;li&gt;Closing - Occurs when the application is closing.&lt;/li&gt;
&lt;li&gt;Continuing -&amp;nbsp; Occurs when the app is continuing from a temporarily paused state.&lt;/li&gt;
&lt;li&gt;Continued - Occurs after the app has continued from a temporarily paused state.&lt;/li&gt;
&lt;li&gt;Resurrecting - Occurs when the app is &amp;quot;resurrecting&amp;quot; from a tombstoned state.&lt;/li&gt;
&lt;li&gt;Resurrected - Occurs after the app has &amp;quot;resurrected&amp;quot; from a tombstoned state.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Using these new events, you can more intelligently make decisions about whether or not you need to restore data. In the forthcoming Mango release, the platform will provide us information on whether the app is continuing or resurrecting. However, developers working with Caliburn.Micro can have that information now and when Mango arrives, we&amp;rsquo;ll update our implementation to use the new bits. Your code won&amp;rsquo;t have to change.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Tombstoning&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;As you might imagine, our new tombstoning mechanism takes advantage of the new events so that it can more reliably and accurately save/restore important data. Let&amp;rsquo;s have a look at the PivotPageViewModel to see how it interacts with the tombstoning mechanism.&lt;/p&gt;
&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;public class PivotPageViewModel : Conductor&amp;lt;IScreen&amp;gt;.Collection.OneActive {
    readonly Func&amp;lt;TabViewModel&amp;gt; createTab;

    public PivotPageViewModel(Func&amp;lt;TabViewModel&amp;gt; createTab) {
        this.createTab = createTab;
    }

    public int NumberOfTabs { get; set; }

    protected override void OnInitialize() {
        Enumerable.Range(1, NumberOfTabs).Apply(x =&amp;gt; {
            var tab = createTab();
            tab.DisplayName = &amp;quot;Item &amp;quot; + x;
            Items.Add(tab);
        });

        ActivateItem(Items[0]);
    }
}&lt;/pre&gt;
&lt;p&gt;The PivotPageViewModel will receive the number of pivot items to create through it&amp;rsquo;s NumberOfTabs property, which is pushed in from the query string, as mentioned above. It will then add these items to the conductor and activate the first one. If you&amp;rsquo;re familiar with the Pivot and CM&amp;rsquo;s previous sample, you&amp;rsquo;ll notice that our PivotFix is gone. Pivot has a horrible bug that will crash your application if you try to set the SelectedItem or SelectedIndex to an item 3 or greater from either end of the pivot collection, while the Pivot itself is not visible. This makes it really hard to restore this control from a tombstoned state because you have to set the value at the exact right time. Previously we used a PivotFix hack to work around the control&amp;rsquo;s bug, but the new tombstoning mechanism is powerful and extensible enough to just make it work. You&amp;rsquo;ll notice that there are no attributes describing tombstoning behavior. They&amp;rsquo;ve been removed in favor of a poco model inspired by Fluent NHibhernate. If you would rather have the attributes, you can actually build them on top of the new system. The new system is also more reliable than previously and has a lot more options for storage. Let&amp;rsquo;s see the class that describes the tombstoning behavior for PivotPageViewModel:&lt;/p&gt;
&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;public class PivotPageModelStorage : StorageHandler&amp;lt;PivotPageViewModel&amp;gt; {
    public override void Configure() {
        this.ActiveItemIndex()
            .InPhoneState()
            .RestoreAfterViewLoad();
    }
}&lt;/pre&gt;
&lt;p&gt;All you&amp;nbsp; have to do to make a class participate in tombstoning is to inherit from StorageHandler&amp;lt;T&amp;gt;. The PhoneContainer will auto-register anything of this type in the assembly. Just override the Configure method and declare the tombstoning instructions. I&amp;rsquo;ve created some extension methods for common scenarios. Here&amp;rsquo;s what the above declaration states:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;-Persist the Conductor&amp;rsquo;s ActiveItem&amp;rsquo;s index&lt;/li&gt;
&lt;li&gt;-Store the index in PhoneState&lt;/li&gt;
&lt;li&gt;-Restore the value after the associated view has been loaded.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Let&amp;rsquo;s look at the storage handler for the TabViewModel to see some more options:&lt;/p&gt;
&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;public class TabViewModelStorage : StorageHandler&amp;lt;TabViewModel&amp;gt; {
    public override void Configure() {
        Id(x =&amp;gt; x.DisplayName);

        Property(x =&amp;gt; x.Text)
            .InPhoneState()
            .RestoreAfterActivation();
    }
}&lt;/pre&gt;
&lt;p&gt;Here we are specifying an Id because we actually need to persist multiple instances of the same VM. When we restore, we&amp;rsquo;ll need to know how to map the properties back. We&amp;rsquo;re also storing the data in PhoneState, but this time we&amp;rsquo;re not waiting for the view to load, but just waiting for the TabViewModel to be activated by its owning Conductor.&lt;/p&gt;
&lt;p&gt;Out of the box, we also support storing data in AppSettings. For example, if you wanted to same tab to be selected *across application restarts* not just when tombstoned, you could define the PivotPageModelStorage like this:&lt;/p&gt;
&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;public class PivotPageModelStorage : StorageHandler&amp;lt;PivotPageViewModel&amp;gt; {
    public override void Configure() {
        this.ActiveItemIndex()
            .InAppSettings()
            .RestoreAfterViewLoad();
    }
}&lt;/pre&gt;
&lt;p&gt;Pretty easy? All this works by collaborating with the IoC container and keying off of the new event model exposed by the IPhoneService. It&amp;rsquo;s pretty powerful and extensible. You can add your own storage mechanism or define your own restore timing. You can even implement IStorageHandler directly to write completely custom code on a class by class basis. You could easily add a version that inspected classes for custom attributes and built up the configuration, if you like the attribute model better. You can also store whole instances, not just their properties, and have them rehydrated properly and available for ctor injection.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Launchers and Choosers&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Launchers and Choosers are painful to work with if you want to do MVVM. In v1.0 we provided a solution to this. I wasn&amp;rsquo;t happy with its implementation&amp;hellip;it was unpredictable in certain scenarios. Once we established the new phone events, better IoC integration and new tombstoning mechanism, I realized I could build a better launcher/chooser system. Let&amp;rsquo;s take a look at the updated version of TabViewModel in order to see how it works:&lt;/p&gt;
&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;public class TabViewModel : Screen, IHandle&amp;lt;TaskCompleted&amp;lt;PhoneNumberResult&amp;gt;&amp;gt; {
    string text;
    readonly IEventAggregator events;

    public TabViewModel(IEventAggregator events) {
        this.events = events;
    }

    public string Text {
        get { return text; }
        set {
            text = value;
            NotifyOfPropertyChange(() =&amp;gt; Text);
        }
    }

    public void Choose() {
        events.RequestTask&amp;lt;PhoneNumberChooserTask&amp;gt;();
    }

    public void Handle(TaskCompleted&amp;lt;PhoneNumberResult&amp;gt; message) {
        MessageBox.Show(&amp;quot;The result was &amp;quot; + message.Result.TaskResult, DisplayName, MessageBoxButton.OK);
    }

    protected override void OnActivate() {
        events.Subscribe(this);
        base.OnActivate();
    }

    protected override void OnDeactivate(bool close) {
        events.Unsubscribe(this);
        base.OnDeactivate(close);
    }
}&lt;/pre&gt;
&lt;p&gt;The most significant architectural change I made was to re-implement the launcher/chooser mechanism to work on top of the IEventAggregator. Take a look at the Choose method. The RequestTask method is just an extension method of the IEventAggregator that publishes a special event that the framework is subscribed to. The framework then starts the task. When it&amp;rsquo;s completed, the framework publishes an event TaskCompleted&amp;lt;T&amp;gt; where T is the result the the chooser returns. You can register for this in the same VM that published the chooser event or in an entirely different one if you like. In the case of our sample, we have 5 TabViewModels that can launch the same chooser. That&amp;rsquo;s probably not normal, but you can handle this situation in three ways. In our case, the VMs are in a Conductor, and only one of them can be active at a time, so we just Subscribe/Unsubscribe based on the Screen lifecycle so that only the active VM will receive the result. This is a version of &lt;a target="_blank" href="http://codebetter.com/jeremymiller/2007/07/02/build-your-own-cab-12-rein-in-runaway-events-with-the-quot-latch-quot/"&gt;the Latch pattern&lt;/a&gt;. The second way to handle this is through the event state. When you call the RequestTask method you can pass a state object which you can use for identification purposes later. Yes, this will be present even if the chooser causes a tombstone event. The final way is to have a single object that registers for the completed event, decoupling the launching from the completion. Thus multiple VM could launch the same chooser, but only one class would handle the result.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;IWindowManager&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The IWindowManager was actually in v1.0, as a last minute addition. It&amp;rsquo;s a really easy way to show native-looking, custom message boxes or modal dialogs. You can also use it to show popups. We&amp;rsquo;ll talk more about the window manager, on all platforms, in the next post.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Referenced Samples&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Caliburn.Micro.HelloWP7&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Footnotes&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Even though the IGuardClose interface was designed to handle async scenarios, you must use it synchronously in WP7. This is due to a flaw in the design of Silverlight Navigation Framework which doesn&amp;rsquo;t account for async shutdown scenarios.&lt;/li&gt;
&lt;/ol&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=67721" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/Xaml/default.aspx">Xaml</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/WPF_2F00_e/default.aspx">WPF/e</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/Caliburn/default.aspx">Caliburn</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/Featured/default.aspx">Featured</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/Silverlight/default.aspx">Silverlight</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/DSL/default.aspx">DSL</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/RIA/default.aspx">RIA</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/Tutorial/default.aspx">Tutorial</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/MVVM/default.aspx">MVVM</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/UI+Architecture/default.aspx">UI Architecture</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/Caliburn+Micro/default.aspx">Caliburn Micro</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/WP7/default.aspx">WP7</category></item><item><title>Caliburn.Micro Soup to Nuts Part 8–The EventAggregator</title><link>http://devlicio.us/blogs/rob_eisenberg/archive/2011/05/30/caliburn-micro-soup-to-nuts-part-8-the-eventaggregator.aspx</link><pubDate>Mon, 30 May 2011 16:06:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:67406</guid><dc:creator>Rob Eisenberg</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/rob_eisenberg/rsscomments.aspx?PostID=67406</wfw:commentRss><comments>http://devlicio.us/blogs/rob_eisenberg/archive/2011/05/30/caliburn-micro-soup-to-nuts-part-8-the-eventaggregator.aspx#comments</comments><description>&lt;p&gt;In Caliburn.Micro we have a series of supporting services for building presentation tiers. Among them is the EventAggregator, a service which supports in-process publish/subscribe. There are various implementations of this pattern available in other frameworks, but I think you&amp;rsquo;ll find that Caliburn.Micro&amp;rsquo;s implementation sports the cleanest API and the richest set of features. Let&amp;rsquo;s start by having a look at the IEventAggregator interface:&lt;/p&gt;
&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;public interface IEventAggregator {
    void Subscribe(object instance);
    void Unsubscribe(object instance);
    void Publish(object message, Action&amp;lt;System.Action&amp;gt; marshal = null);
}&lt;/pre&gt;
&lt;p&gt;Below we&amp;rsquo;ll dig into how the default implementation of this interface (EventAggregator) works.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Subscribe&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;With the Caliburn.Micro EventAggregator we don&amp;rsquo;t actually leverage events under the covers. Events are prone to memory leaks and it&amp;rsquo;s extremely difficult to avoid them or to write a flawless weak event implementation. Instead, we allow you to subscribe an object instance. Under the covers we hold a weak reference. That makes things quite simple. But, how do we know what messages to subscribe to and what methods to use as callbacks? Well, we follow a declarative model by requiring subscribers to implement an interface which states which message they are interested in and provides the callback method. The interface looks like this:&lt;/p&gt;
&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;public interface IHandle&amp;lt;TMessage&amp;gt; : IHandle {
    void Handle(TMessage message);
}&lt;/pre&gt;
&lt;p&gt;And it&amp;rsquo;s used like this:&lt;/p&gt;
&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;public class MyViewModel : IHandle&amp;lt;SomeMessage&amp;gt;{
    public void Handle(SomeMessage message){
        //do something with the message
    }
}&lt;/pre&gt;
&lt;p&gt;Because we use an interface, you can implement IHandle&amp;lt;T&amp;gt; as many times as you want on a given class. This approach keeps things declarative, strongly-typed and free from memory leaks. You can even use explicit interface implementations to hide the handlers if you desire.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Unsubscribe&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;There&amp;rsquo;s not too much to say about this. When you call this method, we search our list of subscribers and remove the specified instance. You may be wondering why this is even necessary if subscribers are held with weak references to begin with. It turns out that there are a number of cases where you want to control the subscription&amp;rsquo;s activation. Imagine you have a Screen Collection and only the Active Screen is supposed to receive events. In this case, you&amp;rsquo;d want to subscribe when the screen was activated and unsubscribe when it was deactivated. See the v1.1 HelloWP7 sample for an example of how this works with the new Launcher/Choosers mechanism.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Publish&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;As you might expect, calling Publish actually sends a message to all it&amp;rsquo;s subscribers. Here&amp;rsquo;s how you might use it:&lt;/p&gt;
&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;public class MyOtherViewModel{
    IEventAggregator events;

    public MyOtherViewModel(IEventAggregator events){
        this.events = events;
    }

    public void DoSomething(){
        events.Publish(new SomeMessage{
            SomeNumber = 5,
            SomeString = &amp;quot;Blah...&amp;quot;
        });
    }
}&lt;/pre&gt;
&lt;p&gt;Here, we get an instance of the IEventAggregator service via constructor injection. Then, when the DoSomething method is invoked, we publish the SomeMessage message along with its data. Assuming MyViewMododel above had subscribed itself to the aggregator, it would then have it&amp;#39;s Handle method called with the SomeMessage instance. So how does this work? We do this by iterating our list of subscribers to see if any of them implement IHandle&amp;lt;T&amp;gt; where T is assignable from the message that is being published. All the matches that are found then have their handlers called on the UI thread.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Marker Interface&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;IHandle&amp;lt;T&amp;gt; inherits from a marker interface IHandle. This allows the use of casting to determine if an object instance subscribes to any events. This enables simple auto-subscribing if you integrate with an IoC container. Most IoC containers (including the SimpleContainer) provide a hook for being called when a new instance is created. Simply wire for your container&amp;rsquo;s callback, inspect the instance being created to see if it implement IHandle, and if it does, call Subscribe on the event aggregator. Just remember, you probably don&amp;rsquo;t want to use this technique if you need conditional subscription as I described above.&lt;/p&gt;
&lt;h2&gt;New in v1.1&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Custom Publication Marshaling&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Those familiar with v1.0 may notice a few interesting differences in the interface. Among them is the optional &amp;ldquo;marshal&amp;rdquo; parameter of the Publish method. By default messages will be automatically published synchronously on the UI thread. However, this is not always desirable. The optional parameter allows you to provide an action which marshals the publication to a custom thread. By using this extension point, a developer could easily write extension methods such as: PublishOnCurrentThread, PublishOnBackgroundThread or PublishOnUIThreadAsync.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Polymorphic Event Subscriptions&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Above I stated that during publication we check for handlers &amp;ldquo;where T is assignable from the message being published.&amp;rdquo; We do this with reflection in v1.1 rather than casting (v1.0) in order to enable polymorphic event subscriptions. Let me explain what this means by providing an example:&lt;/p&gt;
&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;public interface ICustomerMessage{
    //implementation here
}

public interface ICustomerCreated : ICustomerMessage{
    //implementation here
}

public interface ICustomerDeleted : ICustomerMessage{
    //implementation here
}

public class AnUnrelatedMessage{
    //implementation here
}

public class MyObserver :
    IHandle&amp;lt;object&amp;gt;, 
    IHandle&amp;lt;ICustomerMessage&amp;gt;, 
    IHandle&amp;lt;ICustomerDeleted&amp;gt; {
    
    public void Handle(object message){
        //will handle every message in the application
    }

    public void Handle(ICustomerMessage message){
        //handles ICustomerCreated and ICustomerDeleted
    }

    public void Handle(ICustomerDeleted message){
        //handles only ICustomerDeleted
    }
}&lt;/pre&gt;
&lt;p&gt;This turns out to be very powerful, especially when you need to evolve a system over time.&lt;/p&gt;
&lt;p&gt;You can see the EventAggregator in action and step through some code by opening up the HelloEventAggregator sample under source. This sample creates a ShellViewModel with two child view models. Each child publishes a message that the other child is subscribed to. The ShellViewModel is subscribed to all messages via the polymorphic features of the aggregator. Here&amp;rsquo;s a screen shot after some messages have been published:&lt;/p&gt;
&lt;p&gt;&lt;a href="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/rob_5F00_eisenberg/HelloEventAggregator_5F00_775C276C.png"&gt;&lt;img height="370" width="501" src="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/rob_5F00_eisenberg/HelloEventAggregator_5F00_thumb_5F00_1D51D7C3.png" alt="HelloEventAggregator" border="0" title="HelloEventAggregator" style="background-image:none;border-bottom:0px;border-left:0px;padding-left:0px;padding-right:0px;display:inline;border-top:0px;border-right:0px;padding-top:0px;" /&gt;&lt;/a&gt;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=67406" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/WPF/default.aspx">WPF</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/Xaml/default.aspx">Xaml</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/Caliburn/default.aspx">Caliburn</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/Silverlight/default.aspx">Silverlight</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/RIA/default.aspx">RIA</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/Tutorial/default.aspx">Tutorial</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/MVVM/default.aspx">MVVM</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/UI+Architecture/default.aspx">UI Architecture</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/Caliburn+Micro/default.aspx">Caliburn Micro</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/WP7/default.aspx">WP7</category></item><item><title>Caliburn.Micro Soup to Nuts Part 7 - All About Conventions</title><link>http://devlicio.us/blogs/rob_eisenberg/archive/2010/12/16/caliburn-micro-soup-to-nuts-part-7-all-about-conventions.aspx</link><pubDate>Thu, 16 Dec 2010 20:49:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:63987</guid><dc:creator>Rob Eisenberg</dc:creator><slash:comments>4</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/rob_eisenberg/rsscomments.aspx?PostID=63987</wfw:commentRss><comments>http://devlicio.us/blogs/rob_eisenberg/archive/2010/12/16/caliburn-micro-soup-to-nuts-part-7-all-about-conventions.aspx#comments</comments><description>&lt;p&gt;One of the main features of Caliburn.Micro is manifest in its ability to remove the need for boiler plate code by acting on a series of conventions. Some people love conventions and some hate them. That&amp;rsquo;s why CM&amp;rsquo;s conventions are fully customizable and can even be turned off completely if not desired. If you are going to use conventions, and since they are ON by default, it&amp;rsquo;s good to know what those conventions are and how they work. That&amp;rsquo;s the subject of this article.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;View Resolution (ViewModel-First)&lt;/h2&gt;
&lt;h3&gt;Basics&lt;/h3&gt;
&lt;p&gt;The first convention you are likely to encounter when using CM is related to view resolution. This convention affects any ViewModel-First areas of your application. In ViewModel-First, we have an existing ViewModel that we need to render to the screen. To do this, CM uses a simple naming pattern to find a UserControl&lt;sup&gt;1&lt;/sup&gt; that it should bind to the ViewModel and display. So, what is that pattern? Let&amp;rsquo;s just take a look at ViewLocator.LocateForModelType to find out:&lt;/p&gt;
&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;public static Func&amp;lt;Type, DependencyObject, object, UIElement&amp;gt; LocateForModelType = (modelType, displayLocation, context) =&amp;gt;{
    var viewTypeName = modelType.FullName.Replace(&amp;quot;Model&amp;quot;, string.Empty);
    if(context != null)
    {
        viewTypeName = viewTypeName.Remove(viewTypeName.Length - 4, 4);
        viewTypeName = viewTypeName + &amp;quot;.&amp;quot; + context;
    }

    var viewType = (from assmebly in AssemblySource.Instance
                    from type in assmebly.GetExportedTypes()
                    where type.FullName == viewTypeName
                    select type).FirstOrDefault();

    return viewType == null
        ? new TextBlock { Text = string.Format(&amp;quot;{0} not found.&amp;quot;, viewTypeName) }
        : GetOrCreateViewType(viewType);
};&lt;/pre&gt;
&lt;p&gt;Let&amp;rsquo;s ignore the &amp;ldquo;context&amp;rdquo; variable at first. To derive the view, we make an assumption that you are using the text &amp;ldquo;ViewModel&amp;rdquo; in the naming of your VMs, so we just change that to &amp;ldquo;View&amp;rdquo; everywhere that we find it by removing the word &amp;ldquo;Model&amp;rdquo;. This has the effect of changing both type names and namespaces. So ViewModels.CustomerViewModel would become Views.CustomerView. Or if you are organizing your application by feature: CustomerManagement.CustomerViewModel becomes CustomerManagement.CustomerView. Hopefully, that&amp;rsquo;s pretty straight forward. Once we have the name, we then search for types with that name. We search any assembly you have exposed to CM as searchable via AssemblySource.Instance.&lt;sup&gt;2&lt;/sup&gt; If we find the type, we create an instance (or get one from the IoC container if it&amp;rsquo;s registered) and return it to the caller. If we don&amp;rsquo;t find the type, we generate a view with an appropriate &amp;ldquo;not found&amp;rdquo; message.&lt;/p&gt;
&lt;p&gt;Now, back to that &amp;ldquo;context&amp;rdquo; value. This is how CM supports multiple Views over the same ViewModel. If a context (typically a string or an enum) is provided, we do a further transformation of the name, based on that value. This transformation effectively assumes you have a folder (namespace) for the different views by removing the word &amp;ldquo;View&amp;rdquo; from the end and appending the context instead. So, given a context of &amp;ldquo;Master&amp;rdquo; our ViewModels.CustomerViewModel would become Views.Customer.Master.&lt;/p&gt;
&lt;h3&gt;Other Things To Know&lt;/h3&gt;
&lt;p&gt;Besides instantiation of your View, GetOrCreateViewType will call InitializeComponent on your View (if it exists). This means that for Views created by the ViewLocator, you don&amp;rsquo;t have to have code-behinds at all. You can delete them if that makes you happy :) You should also know that ViewLocator.LocateForModelType is never called directly. It is always called indirectly through ViewLocator.LocateForModel. LocateForModel takes an instance of your ViewModel and returns an instance of your View. One of the functions of LocateForModel is to inspect your ViewModel to see if it implements IViewAware. If so, it will call it&amp;rsquo;s GetView method to see if you have a cached view or if you are handling View creation explicitly. If not, then it passes your ViewModel&amp;rsquo;s type to LocateForModelType.&lt;/p&gt;
&lt;h3&gt;Customization&lt;/h3&gt;
&lt;p&gt;The out-of-the-box convention is pretty simple and based on a number of patterns we&amp;rsquo;ve used and seen others use in the real world. However, by no means are you limited to these simple patterns. You&amp;rsquo;ll notice that all the methods discussed above are implemented as Funcs rather than actual methods. This means that you can customize them by simply replacing them with your own implementations. If you just want to add to the existing behavior, simply store the existing Func in a variable, create a new Func that calls the old and and assign the new Func to ViewLocator.LocateForModelType.&lt;sup&gt;3&lt;/sup&gt;&lt;/p&gt;
&lt;h3&gt;Framework Usage&lt;/h3&gt;
&lt;p&gt;There are three places that the framework uses the ViewLocator; three places where you can expect the view location conventions to be applied. The first place is in Bootstrapper&amp;lt;T&amp;gt;. Here, your root ViewModel is passed to the locator in order to determine how your application&amp;rsquo;s shell should be rendered.&amp;nbsp; In Silverlight this results in the setting or your RootVisual. In WPF, this creates your MainWindow. In fact, in WPF the bootstrapper delegates this to the WindowManager, which brings me to&amp;hellip; The second place the ViewLocator is used is the WindowManager, which calls it to determine how any dialog ViewModels should be rendered. The third and final place that leverages these conventions is the View.Model attached property. Whenever you do ViewModel-First composition rendering by using the View.Model attached property on a UIElement, the locator is invoked to see how that composed ViewModel should be rendered at that location in the UI. You can use the View.Model attached property explicitly in your UI (optionally combining it with the View.Context attached property for contextual rendering), or it can be added by convention, thus causing conventional composition of views to occur. See the section below on property binding conventions.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;ViewModel Resolution (View-First) &lt;/h2&gt;
&lt;h3&gt;Basics&lt;/h3&gt;
&lt;p&gt;Though Caliburn.Micro prefers ViewModel-First development, there are times when you may want to take a View-First approach, especially when working with WP7. In the case where you start with a view, you will likely then need to resolve a ViewModel. We use a similar naming convention for this scenario as we did with view location. Let&amp;rsquo;s take a look at ViewModelLocator.LocateForViewType:&lt;/p&gt;
&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;public static Func&amp;lt;Type, object&amp;gt; LocateForViewType = viewType =&amp;gt;{
    var typeName = viewType.FullName;

    if(!typeName.EndsWith(&amp;quot;View&amp;quot;))
        typeName += &amp;quot;View&amp;quot;;

    var viewModelName = typeName.Replace(&amp;quot;View&amp;quot;, &amp;quot;ViewModel&amp;quot;);
    var key = viewModelName.Substring(viewModelName.LastIndexOf(&amp;quot;.&amp;quot;) + 1);

    return IoC.GetInstance(null, key);
};&lt;/pre&gt;
&lt;p&gt;While with View location we change instances of &amp;ldquo;ViewModel&amp;rdquo; to &amp;ldquo;View&amp;rdquo;, with ViewModel location we change &amp;ldquo;View&amp;rdquo; to &amp;ldquo;ViewModel.&amp;rdquo; The other interesting difference is in how we get the instance of the ViewModel itself. Because your ViewModels may be registered by an interface or a concrete class, we don&amp;rsquo;t pull them from the container by type. Instead we pull them by key, using just the derived name, minus all the namespace stuff.&lt;/p&gt;
&lt;h3&gt;Other Things To Know&lt;/h3&gt;
&lt;p&gt;ViewModelLocator.LocateForViewType is actually never called directly by the framework. It&amp;rsquo;s called internally by ViewModelLocator.LocateForView. LocateForView first checks your View instance&amp;rsquo;s DataContext to see if you&amp;rsquo;ve previous cached or custom created your ViewModel. If the DataContext is null, only then will it call into LocateForViewType. A final thing to note is that automatic InitializeComponent calls are not supported by view first, by its nature.&lt;/p&gt;
&lt;h3&gt;Customization&lt;/h3&gt;
&lt;p&gt;You may not be happy with the way that LocateForViewType retrieves your ViewModel from the IoC container by key. No problem. Simply replace the Func with your own implementation. As you can see, it doesn&amp;rsquo;t really require that much code to map one thing to another.&lt;/p&gt;
&lt;h3&gt;Framework Usage&lt;/h3&gt;
&lt;p&gt;The ViewModelLocator is only used by the WP7 version of the framework. It&amp;rsquo;s used by the FrameAdapter which insures that every time you navigate to a page, it is supplied with the correct ViewModel. It could be easily adapted for use by the Silverlight Navigation Framework if desired.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;ViewModelBinder&lt;/h2&gt;
&lt;h3&gt;Basics&lt;/h3&gt;
&lt;p&gt;When we bind together your View and ViewModel, regardless of whether you use a ViewModel-First or a View-First approach, the ViewModelBinder.Bind method is called. This method sets the Action.Target of the View to the ViewModel and correspondingly sets the DataContext to the same value.&lt;sup&gt;4&lt;/sup&gt; It also checks to see if your ViewModel implements IViewAware, and if so, passes the View to your ViewModel. This allows for a more SupervisingController style design, if that fits your scenario better. The final important thing the ViewModelBinder does is determine if it needs to create any conventional property bindings or actions. To do this, it searches the UI for a list of element candidates for bindings/actions and compares that against the properties and methods of your ViewModel. When a match is found, it creates the binding or the action on your behalf.&lt;/p&gt;
&lt;h3&gt;Other Things To Know&lt;/h3&gt;
&lt;p&gt;On the WP7 platform, if the View you are binding is a PhoneApplicationPage, this service is responsible for wiring up actions to the ApplicationBar&amp;rsquo;s Buttons and Menus. See the &lt;a target="_blank" href="http://caliburnmicro.codeplex.com/wikipage?title=Working%20with%20Windows%20Phone%207&amp;amp;referringTitle=Documentation"&gt;WP7 specific docs&lt;/a&gt; for more information on that.&lt;/p&gt;
&lt;h3&gt;Customization&lt;/h3&gt;
&lt;p&gt;Should you decide that you don&amp;rsquo;t like the behavior of the ViewModelBinder (more details below), it follows the same patterns as the above framework services. It has several Funcs you can replace with your own implementations, such as Bind, BindActions and BindProperties. Probably the most important aspect of customization though, is the ability to turn off the binder&amp;rsquo;s convention features. To do this, set ViewModelBinder.ApplyConventionsByDefault to false. If you want to enable it on a view-by-view basis, you can set the View.ApplyConventions attached property to true on your View. This attached property works both ways. So, if you have conventions on by default, but need to turn them off on a view-by-view basis, you just set this property to false.&lt;/p&gt;
&lt;h3&gt;Framework Usage&lt;/h3&gt;
&lt;p&gt;The ViewModelBinder is used in three places inside of Caliburn.Micro. The first place is inside the implementation of the View.Model attached property. This property takes your ViewModel, locates a view using the ViewLocator and then passes both of them along to the ViewModelBinder. After binding is complete, the View is injected inside the element on which the property is defined. That&amp;rsquo;s the ViewModel-First usage pattern. The second place that uses the ViewModelBinder is inside the implementation of the Bind.Model attached property. This property takes a ViewModel and passes it along with the element on which the property is defined to the ViewModelBinder. In other words, this is View-First, since you have already instantiated the View inline in your Xaml and are then just invoking the binding against a ViewModel. The final place that the ViewModelBinder is used is in the WP7 version of the framework. Inside of the FrameAdapter, when a page is navigated to, the ViewModelLocator is first used to obtain the ViewModel for that page. Then, the ViewModelBinder is uses to connect the ViewModel to the page.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Element Location&lt;/h2&gt;
&lt;h3&gt;Basics&lt;/h3&gt;
&lt;p&gt;Now that you understand the basic role of the ViewModelBinder and where it is used by the framework, I want to dig into the details of how it applies conventions. As mentioned above, the ViewModelBinder &amp;ldquo;searches the UI for a list of &lt;em&gt;element candidates&lt;/em&gt; for bindings/actions and compares that against the properties and methods of your ViewModel.&amp;rdquo; The first step in understanding how this works is knowing how the framework determines which elements in your UI may be candidates for conventions. It does this by using a func on the static ExtensionMethods class called GetNamedElementsInScope.&lt;sup&gt;5&lt;/sup&gt; Basically this method does two things. First, it identifies a scope to search for elements in. This means it walks the tree until it finds a suitable root node, such as a Window, UserControl or element without a parent (indicating that we are inside a DataTemplate). Once it defines the &amp;ldquo;outer&amp;rdquo; borders of the scope, it begins it&amp;rsquo;s second task: locating all elements in that scope that have names. The search is careful to respect an &amp;ldquo;inner&amp;rdquo; scope boundary by not traversing inside of child user controls. The elements that are returned by this function are then used by the ViewModelBinder to apply conventions.&lt;/p&gt;
&lt;h3&gt;Other Things To Know&lt;/h3&gt;
&lt;p&gt;There are a few limitations to what the GetNamedElementsInScope method can accomplish out-of-the-box. It can only search the visual tree, ContentControl.Content and ItemsControl.Items. In WPF, it also searches HeaderContentControl.Header and HeaderedItemsControl.Header. What this means is that things like ContextMenus, Tooltips or anything else that isn&amp;rsquo;t in the visual tree or one of these special locations won&amp;rsquo;t get found when trying to apply conventions.&lt;/p&gt;
&lt;h3&gt;Customization&lt;/h3&gt;
&lt;p&gt;You may not encounter issues related to the above limitations of element location. But if you do, you can easily replace the default implementation with your own. Here&amp;rsquo;s an interesting technique you might choose to use: If the view is a UserControl or Window, instead of walking the tree for elements, use some reflection to discover all private fields that inherit from FrameworkElement. We know that when Xaml files are compiled, a private field is created for everything with an x:Name. Use this to your advantage. You will have to fall back to the existing implementation for DataTemplate UI though. I don&amp;rsquo;t provide this implementation out-of-the-box, because it is not guaranteed to succeed in Silverlight. The reason is due to the fact that Silverlight doesn&amp;rsquo;t allow you to get the value of a private field unless the calling code is the code that defines the field. However, if all of your views are defined in a single assembly, you can easily make the modification I just described by creating your new implementation in the same assembly as the views. Furthermore, if you have a multi-assembly project, you could write a little bit of plumbing code that would allow the GetNamedElementsInScope Func to find the assembly-specific implementation which could actually perform the reflection.&lt;sup&gt;6&lt;/sup&gt;&lt;/p&gt;
&lt;h3&gt;Framework Usage&lt;/h3&gt;
&lt;p&gt;I&amp;rsquo;ve already mentioned that element location occurs when the ViewModelBinder attempts to bind properties or methods by convention. But, there is a second place that uses this functionality: the Parser. Whenever you use Message.Attach and your action contains parameters, the message parser has to find the elements that you are using as parameter inputs. It would seem that we could just do a simple FindName, but FindName is case-sensitive. As a result, we have to use our custom implementation which does a case-insensitive search. This ensures that the same semantics for binding are used in both places.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Action Matching&lt;/h2&gt;
&lt;h3&gt;Basics&lt;/h3&gt;
&lt;p&gt;The next thing the ViewModelBinder does after locating the elements for convention bindings is inspect them for matches to methods on the ViewModel. It does this by using a bit of reflection to get the public methods of the ViewModel. It then loops over them looking for a case-insensitive name match with an element. If a match is found, and there aren&amp;rsquo;t any pre-existing Interaction.Triggers on the element, an action is attached. The check for pre-existing triggers is used to prevent the convention system from creating duplicate actions to what the developer may have explicitly declared in the markup. To be on the safe side, if you have declared any triggers on the matched element, it is skipped.&lt;/p&gt;
&lt;h3&gt;Other Things To Know&lt;/h3&gt;
&lt;p&gt;The conventional actions are created by setting the Message.Attach attached property on the element. Let&amp;rsquo;s look at how that is built up:&lt;/p&gt;
&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;var message = method.Name;
var parameters = method.GetParameters();

if(parameters.Length &amp;gt; 0)
{
    message += &amp;quot;(&amp;quot;;

    foreach(var parameter in parameters)
    {
        var paramName = parameter.Name;
        var specialValue = &amp;quot;$&amp;quot; + paramName.ToLower();

        if(MessageBinder.SpecialValues.Contains(specialValue))
            paramName = specialValue;

        message += paramName + &amp;quot;,&amp;quot;;
    }

    message = message.Remove(message.Length - 1, 1);
    message += &amp;quot;)&amp;quot;;
}

Log.Info(&amp;quot;Added convention action for {0} as {1}.&amp;quot;, method.Name, message);
Message.SetAttach(foundControl, message);&lt;/pre&gt;
&lt;p&gt;As you can see, we build a string representing the message. This string contains only the action part of the message; no event is declared. You can also see that it loops through the parameters of the method so that they are included in the action. If the parameter name is the same as a special parameter value, we make sure to append the &amp;ldquo;$&amp;rdquo; to it so that it will be recognized correctly by the Parser and later by the MessageBinder when the action is invoked.&lt;/p&gt;
&lt;p&gt;When the Message.Attach property is set, the Parser immediately kicks in to convert the string message into some sort of TriggerBase with an associated ActionMessage. Because we don&amp;rsquo;t declare an event as part of the message, the Parser looks up the default Trigger for the type of element that the message is being attached to. For example, if the message was being attached to a Button, then we would get an EventTrigger with it&amp;rsquo;s Event set to Click. This information is configured through the ConventionManager with reasonable defaults out-of-the-box. See the sections on ConventionManager and ElementConventions below for more information on that. The ElementConvention is used to create the Trigger and then the parser converts the action information into an ActionMessage. The two are connected together and then added to the Interaction.Triggers collection of the element.&lt;/p&gt;
&lt;h3&gt;Customization&lt;/h3&gt;
&lt;p&gt;ViewModelBinder.BindActions is a Func and thus can be entirely replaced if desired. Adding to or changing the ElementConventions via the ConventionManager will also effect how actions are put together. More on that below.&lt;/p&gt;
&lt;h3&gt;Framework Usage&lt;/h3&gt;
&lt;p&gt;BindActions is used exclusively by the ViewModelBinder.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Property Matching&lt;/h2&gt;
&lt;h3&gt;Basics&lt;/h3&gt;
&lt;p&gt;Once action binding is complete, we move on to property binding. It follows a similar process by looping through the named elements and looking for case-insensitive name matches on properties. Once a match is found, we then get the ElementConventions from the ConventionManager so we can determine just how databinding on that element should occur. The ElementConvention defines an ApplyBinding Func that takes the view model type, property path, property info, element instance, and the convention itself. This Func is responsible for creating the binding on the element using all the contextual information provided. The neat thing is that we can have custom binding behaviors for each element if we want. CM defines a basic implementation of ApplyBinding for most elements, which lives on the ConventionManager. It&amp;rsquo;s called SetBinding and looks like this:&lt;/p&gt;
&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;public static Func&amp;lt;Type, string, PropertyInfo, FrameworkElement, ElementConvention, bool&amp;gt; SetBinding =
    (viewModelType, path, property, element, convention) =&amp;gt; {
        var bindableProperty = convention.GetBindableProperty(element);
        if(HasBinding(element, bindableProperty))
            return false;

        var binding = new Binding(path);

        ApplyBindingMode(binding, property);
        ApplyValueConverter(binding, bindableProperty, property);
        ApplyStringFormat(binding, convention, property);
        ApplyValidation(binding, viewModelType, property);
        ApplyUpdateSourceTrigger(bindableProperty, element, binding);

        BindingOperations.SetBinding(element, bindableProperty, binding);

        return true;
    };&lt;/pre&gt;
&lt;p&gt;The first thing this method does is get the dependency property that should be bound by calling GetBindableProperty on the ElementConvention. Next we check to see if there is already a binding set for that property. If there is, we don&amp;rsquo;t want to overwrite it. The developer is probably doing something special here, so we return false indicating that a binding has not been added. Assuming no binding exists, this method then basically delegates to other methods on the ConventionManager for the details of binding application. Hopefully that part makes sense. Once the binding is fully constructed we add it to the element and return true indicating that the convention was applied.&lt;/p&gt;
&lt;p&gt;There&amp;rsquo;s another important aspect to property matching that I haven&amp;rsquo;t yet mentioned. We can match on deep property paths by convention as well. So, let&amp;rsquo;s say that you have a Customer property on your ViewModel that has a FirstName property you want to bind a Textbox to. Simply give the TextBox an x:Name of &amp;ldquo;Customer_FirstName&amp;rdquo; The ViewModelBinder will do all the work to make sure that that is a valid property and will pass the correct view model type, property info and property path along to the ElementConvention&amp;rsquo;s ApplyBinding func.&lt;/p&gt;
&lt;h3&gt;Other Things To Know&lt;/h3&gt;
&lt;p&gt;I mentioned above that &amp;ldquo;CM defines a basic implementation of ApplyBinding for most elements.&amp;rdquo; It also defines several custom implementations of the ApplyBinding Func for elements that are typically associated with specific usage patterns or composition. For WPF and Silverlight, there are custom binding behaviors for ItemsControl and Selector. In addition to binding the ItemsSource on an ItemsControl, the ApplyBinding func also inspects the ItemTemplate, DisplayMemberPath and ItemTemplateSelector (WPF) properties. If none of these are set, then the framework knows that since you haven&amp;rsquo;t specified a renderer for the items, it should add one conventionally.&lt;sup&gt;7&lt;/sup&gt; So, we set the ItemTemplate to a default DataTemplate. Here&amp;rsquo;s what it looks like:&lt;/p&gt;
&lt;pre name="code" class="xml:nogutter:nocontrols"&gt;&amp;lt;DataTemplate xmlns=&amp;quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&amp;quot;
              xmlns:cal=&amp;quot;clr-namespace:Caliburn.Micro;assembly=Caliburn.Micro&amp;quot;&amp;gt;
    &amp;lt;ContentControl cal:View.Model=&amp;quot;{Binding}&amp;quot; 
                    VerticalContentAlignment=&amp;quot;Stretch&amp;quot;
                    HorizontalContentAlignment=&amp;quot;Stretch&amp;quot; /&amp;gt;
&amp;lt;/DataTemplate&amp;gt;&lt;/pre&gt;
&lt;p&gt;Since this template creates a ContentControl with a View.Model attached property, we create the possibility of rich composition for ItemsControls. So, whatever the Item is, the View.Model attached property allows us to invoke the ViewModel-First workflow: locate the view for the item, pass the item and the view to the ViewModelBinder (which in turn sets it&amp;rsquo;s own conventions, possibly invoking more composition) and then take the view and inject it into the ContentControl. Selectors have the same behavior as ItemsControls, but with an additional convention around the SelectedItem property. Let&amp;rsquo;s say that your Selector is called Items. We follow the above conventions first by binding ItemsSource to Items and detecting whether or not we need to add a default DataTemplate. Then, we check to see if the SelectedItem property has been bound. If not, we look for three candidate properties on the ViewModel that could be bound to SelectedItem: ActiveItem, SelectedItem and CurrentItem. If we find one of these, we add the binding. So, the pattern here is that we first call ConventionManager.Singularize on the collection property&amp;rsquo;s name. In this case &amp;ldquo;Items&amp;rdquo; becomes &amp;ldquo;Item&amp;rdquo; Then we call ConventionManager.DerivePotentialSelectionNames which prepends &amp;ldquo;Active&amp;rdquo; &amp;ldquo;Selected&amp;rdquo; and &amp;ldquo;Current&amp;rdquo; to &amp;ldquo;Item&amp;rdquo; to make the three candidates above. Then, we create a binding if we find one of these on the ViewModel. For WPF, we have a special ApplyBinding behavior for the TabControl.&lt;sup&gt;8&lt;/sup&gt; It takes on all the conventions of Selector (setting it&amp;rsquo;s ContentTemplate instead of ItemTemplate to the DefaultDataTemplate), plus an additional convention for the tab header&amp;rsquo;s content. If the TabControl&amp;rsquo;s DisplayMemberPath is not set and the ViewModel implements IHaveDisplayName, then we set it&amp;rsquo;s ItemTemplate to the DefaultHeaderTemplate, which looks like this:&lt;/p&gt;
&lt;pre name="code" class="xml:nogutter:nocontrols"&gt;&amp;lt;DataTemplate xmlns=&amp;quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&amp;quot;&amp;gt;
    &amp;lt;TextBlock Text=&amp;quot;{Binding DisplayName, Mode=TwoWay}&amp;quot; /&amp;gt;
&amp;lt;/DataTemplate&amp;gt;&lt;/pre&gt;
&lt;p&gt;So, for a named WPF TabControl we can conventionally bind in the list of tabs (ItemsSource), the tab item&amp;rsquo;s name (ItemTemplate), the content for each tab (ContentTemplate) and keep the selected tab synchronized with the model (SelectedItem). That&amp;rsquo;s not bad for one line of Xaml like this:&lt;/p&gt;
&lt;pre name="code" class="xml:nogutter:nocontrols"&gt;&amp;lt;TabControl x:Name=&amp;quot;Items&amp;quot; /&amp;gt;&lt;/pre&gt;
&lt;p&gt;In addition to the special cases listed above, we have one more that is important: ContentControl. In this case, we don&amp;rsquo;t supply a custom ApplyBinding Func, but we do supply a custom GetBindableProperty Func. For ContentControl, when we go to determine which property to bind to, we inspect the ContentTemplate and ContentTemplateSelector (WPF). If they are both null, you haven&amp;rsquo;t specified a renderer for your model. Therefore, we assume that you want to use the ViewModel-First workflow. We implement this by having the GetBindableProperty Func return the View.Model attached property as the property to be bound. In all other cases ContentControl would be bound on the Content property. By selecting the View.Model property in the absence of a ContentTemplate, we enable rich composition.&lt;/p&gt;
&lt;p&gt;I hope you will find that these special cases make sense when you think about them. As always, if you don&amp;rsquo;t like them, you can change them&amp;hellip;&lt;/p&gt;
&lt;h3&gt;Customization&lt;/h3&gt;
&lt;p&gt;As you might imagine, the BindProperties functionality is completely customizable by replacing the Func on the ViewModelBinder. For example, if you like the idea of Action conventions but not Property conventions, you could just replace this Func with one that doesn&amp;rsquo;t do anything. However, it&amp;rsquo;s likely that you will want more fine grained control. Fortunately, nearly every aspect of the ConventionManager or of a particular ElementConvention is customizable. More details about the ConventionManager are below.&lt;/p&gt;
&lt;p&gt;One of the common ways you will configure conventions is by adding new conventions to the system. Most commonly this will be in adding the Silverlight toolkit controls or the WP7 toolkit controls. Here&amp;rsquo;s an example of how you would set up an advanced convention for the WP7 Pivot control which would make it work like the WPF TabControl:&lt;/p&gt;
&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;ConventionManager.AddElementConvention&amp;lt;Pivot&amp;gt;(Pivot.ItemsSourceProperty, &amp;quot;SelectedItem&amp;quot;, &amp;quot;SelectionChanged&amp;quot;).ApplyBinding =
    (viewModelType, path, property, element, convention) =&amp;gt; {
        ConventionManager
            .GetElementConvention(typeof(ItemsControl))
            .ApplyBinding(viewModelType, path, property, element, convention);
        ConventionManager
            .ConfigureSelectedItem(element, Pivot.SelectedItemProperty, viewModelType, path);
        ConventionManager
            .ApplyHeaderTemplate(element, Pivot.HeaderTemplateProperty, viewModelType);
    };&lt;/pre&gt;
&lt;p&gt;Pretty cool?&lt;/p&gt;
&lt;h3&gt;Framework Usage&lt;/h3&gt;
&lt;p&gt;BindProperties is used exclusively by the ViewModelBinder.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;ConventionManager&lt;/h2&gt;
&lt;p&gt;If you&amp;rsquo;ve read this far, you know that the ConventionManager is leveraged heavily by the Action and Property binding mechanisms. It is the gateway to fine-tuning the majority of the convention behavior in the framework. What follows is a list of the replaceable Funcs and Properties which you can use to customize the conventions of the framework:&lt;/p&gt;
&lt;h3&gt;Properties&lt;/h3&gt;
&lt;p&gt;BooleanToVisibilityConverter &amp;ndash; The default IValueConverter used for converting Boolean to Visibility and back. Used by ApplyValueConverter.&lt;/p&gt;
&lt;p&gt;IncludeStaticProperties - Indicates whether or not static properties should be included during convention name matching. False by default.&lt;/p&gt;
&lt;p&gt;DefaultItemTemplate &amp;ndash; Used when an ItemsControl or ContentControl needs a DataTemplate.&lt;/p&gt;
&lt;p&gt;DefaultHeaderTemplate &amp;ndash; Used by ApplyHeaderTemplate when the TabControl needs a header template.&lt;/p&gt;
&lt;h3&gt;Funcs&lt;/h3&gt;
&lt;p&gt;Singularize &amp;ndash; Turns a word from its plural form to its singular form. The default implementation is really basic and just strips the trailing &amp;lsquo;s&amp;rsquo;.&lt;/p&gt;
&lt;p&gt;DerivePotentialSelectionNames &amp;ndash; Given a base collection name, returns a list of possible property names representing the selection. Uses Singularize.&lt;/p&gt;
&lt;p&gt;SetBinding &amp;ndash; The default implementation of ApplyBinding used by ElementConventions (more info below). Changing this will change how all conventional bindings are applied. Uses the following Funcs internally:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;HasBinding - Determines whether a particular dependency property already has a binding on the provided element. If a binding already exists, SetBinding is aborted.&lt;/li&gt;
&lt;li&gt;ApplyBindingMode - Applies the appropriate binding mode to the binding.&lt;/li&gt;
&lt;li&gt;ApplyValidation - Determines whether or not and what type of validation to enable on the binding.&lt;/li&gt;
&lt;li&gt;ApplyValueConverter - Determines whether a value converter is is needed and applies one to the binding. It only checks for BooleanToVisibility conversion by default.&lt;/li&gt;
&lt;li&gt;ApplyStringFormat - Determines whether a custom string format is needed and applies it to the binding. By default, if binding to a DateTime, uses the format &amp;quot;{0:MM/dd/yyyy}&amp;quot;.&lt;/li&gt;
&lt;li&gt;ApplyUpdateSourceTrigger - Determines whether a custom update source trigger should be applied to the binding. For WPF, always sets to UpdateSourceTrigger=PropertyChanged. For Silverlight, calls ApplySilverlightTriggers.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Methods&lt;/h3&gt;
&lt;p&gt;AddElementConvention &amp;ndash; Adds or replaces an ElementConvention.&lt;/p&gt;
&lt;p&gt;GetElementConvention &amp;ndash; Gets the convention for a particular element type. If not found, searches the type hierarchy for a match.&lt;/p&gt;
&lt;p&gt;ConfigureSelectedItem &amp;ndash; Configures the SelectedItem convention on an element.&lt;/p&gt;
&lt;p&gt;ApplyHeaderTemplate &amp;ndash; Applies the header template convention to an element.&lt;/p&gt;
&lt;p&gt;ApplySilverlightTriggers &amp;ndash; For TextBox and PasswordBox, wires the appropriate events to binding updates in order to simulate WPF&amp;rsquo;s UpdateSourceTrigger=PropertyChanged.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;ElementConvention&lt;/h2&gt;
&lt;p&gt;ElementConventions can be added or replaced through ConventionManager.AddElementConvention. But, it&amp;rsquo;s important to know what these conventions are and how they are used throughout the framework. At the very bottom of this article is a code listing showing how all the elements are configured out-of-the-box. Here are the Properties and Funcs of the ElementConvention class with brief explanations:&lt;/p&gt;
&lt;h3&gt;Properties&lt;/h3&gt;
&lt;p&gt;ElementType &amp;ndash; The type of element to which the convention applies.&lt;/p&gt;
&lt;p&gt;ParameterProperty &amp;ndash; When using Message.Attach to declare an action, if a parameter that refers to an element is specified, but the property of that element is not, the ElementConvention will be looked up and the ParameterProperty will be used. For example, if we have this markup:&lt;/p&gt;
&lt;pre name="code" class="xml:nogutter:nocontrols"&gt;&amp;lt;TextBox x:Name=&amp;quot;something&amp;quot; /&amp;gt;
&amp;lt;Button cal:Message.Attach=&amp;quot;MyMethod(something)&amp;quot; /&amp;gt;&lt;/pre&gt;
&lt;p&gt;When the Button&amp;rsquo;s ActionMessage is created, we look up &amp;ldquo;something&amp;rdquo;, which is a TextBox. We get the ElementConvention for TextBox which has its ParameterProperty set to &amp;ldquo;Text.&amp;rdquo; Therefore, we create the parameter for MyMethod from something.Text.&lt;/p&gt;
&lt;h3&gt;Funcs&lt;/h3&gt;
&lt;p&gt;GetBindableProperty &amp;ndash; Gets the property for the element which should be used in convention binding.&lt;/p&gt;
&lt;p&gt;CreateTrigger &amp;ndash; When Message.Attach is used to declare an Action, and the specific event is not specified, the ElementConvention will be looked up and the CreateTrigger Func will be called to create the Interaction.Trigger. For example in the Xaml above, when the ActionMessage is created for the Button, the Button&amp;rsquo;s ElementConvention will be looked up and its CreateTrigger Func will be called. In this case, the ElementConvention returns an EventTrigger configured to use the Click event.&lt;/p&gt;
&lt;p&gt;ApplyBinding &amp;ndash; As described above, when conventional databinding occurs, the element we are binding has its ElementConvention looked up and it&amp;rsquo;s ApplyBinding func is called. By default this just passes through to ConventionManager.SetBinding. But certain elements (see above&amp;hellip;or below) customize this in order to enable more powerful composition scenarios.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Footnotes&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;The WindowManager uses the ViewLocator under the covers. It inspects types to see if they are UserControl or Window/ChildWindow. If they are not, it automatically creates a parent Window/ChildWindow. So, you can choose to create your dialog views either as a UserControl or Window/ChildWindow in this particular scenario and the framework will take care of the rest. I typically make views UserControls when I can because that makes them a bit more reusable. &lt;/li&gt;
&lt;li&gt;The bootstrapper is responsible for making sure that your application&amp;rsquo;s assembly is added to the AssemblySource, but you can add any additional assemblies by overriding the Bootstrapper&amp;rsquo;s SelectAssemblies method and returning the full list. You can also add additional assemblies to this collection at any time during application execution. So, if you are dynamically downloading modules that contain more views, you can handle that scenario pretty easily. &lt;/li&gt;
&lt;li&gt;This pattern is borrowed from Javascript and I felt it generally made extensibility simpler for the most common use cases. &lt;/li&gt;
&lt;li&gt;Recall that in Caliburn.Micro DataContext has the purpose of specifying to what instance databinding expressions are resolved and Action.Target specifies the instance that handles an Action. Thus, DataContext and Action.Target are allowed to vary independently of one another. By default, whenever the Action.Target is set, the DataContext is set to the same value though. To change this you can set DataContext explicitly to a different value or more commonly, you can use the Action.TargetWithoutContext attached property to set only the Action.Target without affecting the DataContext. &lt;/li&gt;
&lt;li&gt;GetNamedElementsInScope used to be an extension method. However, it became apparent that developers wanted to customize the implementation. So, I made it into a Func. For lack of a better place to put it, it still lives on the ExtensionMethods class. &lt;/li&gt;
&lt;li&gt;Well, I assume this would work. I haven&amp;rsquo;t actually tried it though. &lt;/li&gt;
&lt;li&gt;If your item is a ValueType or a String we don&amp;rsquo;t generate a default DataTemplate. We assume that you want to use the default ToString rendering that the platform provides.&lt;/li&gt;
&lt;li&gt;We don&amp;rsquo;t have this convention in Silverlight because A. TabControl is not part of the core framework and B. Silverlight&amp;rsquo;s TabControl is broken for databinding and has been for two versions of the framework without a fix. Please vote this issue up &lt;a href="http://silverlight.codeplex.com/workitem/3604"&gt;http://silverlight.codeplex.com/workitem/3604&lt;/a&gt; It was reported about a year and a half ago and is not yet fixed.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Out-Of-The-Box Element Conventions&lt;/h2&gt;
&lt;p&gt;Following is the full code-listing showing how the built-in controls have their ElementConventions configured out-of-the-box:&lt;/p&gt;
&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;#if SILVERLIGHT
AddElementConvention&amp;lt;HyperlinkButton&amp;gt;(HyperlinkButton.ContentProperty, &amp;quot;DataContext&amp;quot;, &amp;quot;Click&amp;quot;);
AddElementConvention&amp;lt;PasswordBox&amp;gt;(PasswordBox.PasswordProperty, &amp;quot;Password&amp;quot;, &amp;quot;PasswordChanged&amp;quot;);
#else
AddElementConvention&amp;lt;PasswordBox&amp;gt;(PasswordBox.DataContextProperty, &amp;quot;DataContext&amp;quot;, &amp;quot;PasswordChanged&amp;quot;);
AddElementConvention&amp;lt;Hyperlink&amp;gt;(Hyperlink.DataContextProperty, &amp;quot;DataContext&amp;quot;, &amp;quot;Click&amp;quot;);
AddElementConvention&amp;lt;RichTextBox&amp;gt;(RichTextBox.DataContextProperty, &amp;quot;DataContext&amp;quot;, &amp;quot;TextChanged&amp;quot;);
AddElementConvention&amp;lt;Menu&amp;gt;(Menu.ItemsSourceProperty,&amp;quot;DataContext&amp;quot;, &amp;quot;Click&amp;quot;);
AddElementConvention&amp;lt;MenuItem&amp;gt;(MenuItem.ItemsSourceProperty, &amp;quot;DataContext&amp;quot;, &amp;quot;Click&amp;quot;);
AddElementConvention&amp;lt;Label&amp;gt;(Label.ContentProperty, &amp;quot;Content&amp;quot;, &amp;quot;DataContextChanged&amp;quot;);
AddElementConvention&amp;lt;Slider&amp;gt;(Slider.ValueProperty, &amp;quot;Value&amp;quot;, &amp;quot;ValueChanged&amp;quot;);
AddElementConvention&amp;lt;Expander&amp;gt;(Expander.IsExpandedProperty, &amp;quot;IsExpanded&amp;quot;, &amp;quot;Expanded&amp;quot;);
AddElementConvention&amp;lt;StatusBar&amp;gt;(StatusBar.ItemsSourceProperty, &amp;quot;DataContext&amp;quot;, &amp;quot;Loaded&amp;quot;);
AddElementConvention&amp;lt;ToolBar&amp;gt;(ToolBar.ItemsSourceProperty, &amp;quot;DataContext&amp;quot;, &amp;quot;Loaded&amp;quot;);
AddElementConvention&amp;lt;ToolBarTray&amp;gt;(ToolBarTray.VisibilityProperty, &amp;quot;DataContext&amp;quot;, &amp;quot;Loaded&amp;quot;);
AddElementConvention&amp;lt;TreeView&amp;gt;(TreeView.ItemsSourceProperty, &amp;quot;SelectedItem&amp;quot;, &amp;quot;SelectedItemChanged&amp;quot;);
AddElementConvention&amp;lt;TabControl&amp;gt;(TabControl.ItemsSourceProperty, &amp;quot;ItemsSource&amp;quot;, &amp;quot;SelectionChanged&amp;quot;)
    .ApplyBinding = (viewModelType, path, property, element, convention) =&amp;gt; {
        if(!SetBinding(viewModelType, path, property, element, convention))
            return;

        var tabControl = (TabControl)element;
        if(tabControl.ContentTemplate == null &amp;amp;&amp;amp; tabControl.ContentTemplateSelector == null &amp;amp;&amp;amp; property.PropertyType.IsGenericType) {
            var itemType = property.PropertyType.GetGenericArguments().First();
            if(!itemType.IsValueType &amp;amp;&amp;amp; !typeof(string).IsAssignableFrom(itemType))
                tabControl.ContentTemplate = DefaultItemTemplate;
        }

        ConfigureSelectedItem(element, Selector.SelectedItemProperty, viewModelType, path);

        if(string.IsNullOrEmpty(tabControl.DisplayMemberPath))
            ApplyHeaderTemplate(tabControl, TabControl.ItemTemplateProperty, viewModelType);
    };
AddElementConvention&amp;lt;TabItem&amp;gt;(TabItem.ContentProperty, &amp;quot;DataContext&amp;quot;, &amp;quot;DataContextChanged&amp;quot;);
AddElementConvention&amp;lt;Window&amp;gt;(Window.DataContextProperty, &amp;quot;DataContext&amp;quot;, &amp;quot;Loaded&amp;quot;);
#endif
AddElementConvention&amp;lt;UserControl&amp;gt;(UserControl.VisibilityProperty, &amp;quot;DataContext&amp;quot;, &amp;quot;Loaded&amp;quot;);
AddElementConvention&amp;lt;Image&amp;gt;(Image.SourceProperty, &amp;quot;Source&amp;quot;, &amp;quot;Loaded&amp;quot;);
AddElementConvention&amp;lt;ToggleButton&amp;gt;(ToggleButton.IsCheckedProperty, &amp;quot;IsChecked&amp;quot;, &amp;quot;Click&amp;quot;);
AddElementConvention&amp;lt;ButtonBase&amp;gt;(ButtonBase.ContentProperty, &amp;quot;DataContext&amp;quot;, &amp;quot;Click&amp;quot;);
AddElementConvention&amp;lt;TextBox&amp;gt;(TextBox.TextProperty, &amp;quot;Text&amp;quot;, &amp;quot;TextChanged&amp;quot;);
AddElementConvention&amp;lt;TextBlock&amp;gt;(TextBlock.TextProperty, &amp;quot;Text&amp;quot;, &amp;quot;DataContextChanged&amp;quot;);
AddElementConvention&amp;lt;Selector&amp;gt;(Selector.ItemsSourceProperty, &amp;quot;SelectedItem&amp;quot;, &amp;quot;SelectionChanged&amp;quot;)
    .ApplyBinding = (viewModelType, path, property, element, convention) =&amp;gt; {
        if (!SetBinding(viewModelType, path, property, element, convention))
            return;

        ConfigureSelectedItem(element, Selector.SelectedItemProperty,viewModelType, path);
        ConfigureItemsControl((ItemsControl)element, property);
    };
AddElementConvention&amp;lt;ItemsControl&amp;gt;(ItemsControl.ItemsSourceProperty, &amp;quot;DataContext&amp;quot;, &amp;quot;Loaded&amp;quot;)
    .ApplyBinding = (viewModelType, path, property, element, convention) =&amp;gt; {
        if (!SetBinding(viewModelType, path, property, element, convention))
            return;

        ConfigureItemsControl((ItemsControl)element, property);
    };
AddElementConvention&amp;lt;ContentControl&amp;gt;(ContentControl.ContentProperty, &amp;quot;DataContext&amp;quot;, &amp;quot;Loaded&amp;quot;).GetBindableProperty =
    delegate(DependencyObject foundControl) {
        var element = (ContentControl)foundControl;
#if SILVERLIGHT
        return element.ContentTemplate == null &amp;amp;&amp;amp; !(element.Content is DependencyObject)
            ? View.ModelProperty
            : ContentControl.ContentProperty;
#else
        return element.ContentTemplate == null &amp;amp;&amp;amp; element.ContentTemplateSelector == null &amp;amp;&amp;amp; !(element.Content is DependencyObject)
            ? View.ModelProperty
            : ContentControl.ContentProperty;
#endif
    };
AddElementConvention&amp;lt;Shape&amp;gt;(Shape.VisibilityProperty, &amp;quot;DataContext&amp;quot;, &amp;quot;MouseLeftButtonUp&amp;quot;);
AddElementConvention&amp;lt;FrameworkElement&amp;gt;(FrameworkElement.VisibilityProperty, &amp;quot;DataContext&amp;quot;, &amp;quot;Loaded&amp;quot;);&lt;/pre&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=63987" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/WPF/default.aspx">WPF</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/Xaml/default.aspx">Xaml</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/databinding/default.aspx">databinding</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/WPF_2F00_e/default.aspx">WPF/e</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/Caliburn/default.aspx">Caliburn</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/Featured/default.aspx">Featured</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/Silverlight/default.aspx">Silverlight</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/RIA/default.aspx">RIA</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/Tutorial/default.aspx">Tutorial</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/MVVM/default.aspx">MVVM</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/UI+Architecture/default.aspx">UI Architecture</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/Caliburn+Micro/default.aspx">Caliburn Micro</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/WP7/default.aspx">WP7</category></item><item><title>Caliburn.Micro Soup to Nuts Part 6d – A “Billy Hollis” Hybrid Shell</title><link>http://devlicio.us/blogs/rob_eisenberg/archive/2010/11/18/caliburn-micro-soup-to-nuts-part-6d-a-billy-hollis-hybrid-shell.aspx</link><pubDate>Thu, 18 Nov 2010 21:36:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:63478</guid><dc:creator>Rob Eisenberg</dc:creator><slash:comments>13</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/rob_eisenberg/rsscomments.aspx?PostID=63478</wfw:commentRss><comments>http://devlicio.us/blogs/rob_eisenberg/archive/2010/11/18/caliburn-micro-soup-to-nuts-part-6d-a-billy-hollis-hybrid-shell.aspx#comments</comments><description>&lt;p&gt;&lt;a href="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/rob_5F00_eisenberg/HelloScreensSolution_5F00_567419C1.jpg"&gt;&lt;img height="484" width="246" src="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/rob_5F00_eisenberg/HelloScreensSolution_5F00_thumb_5F00_41F15AF4.jpg" align="right" alt="HelloScreensSolution" border="0" title="HelloScreensSolution" style="background-image:none;border-right-width:0px;margin:0px 6px 6px 0px;padding-left:0px;padding-right:0px;display:inline;float:right;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;padding-top:0px;" /&gt;&lt;/a&gt;Up until now I&amp;rsquo;ve been focusing on fairly simple usage of Screens and Conductors. In this article, I want to show something a bit more sophisticated. This sample is based loosely on the ideas demonstrated by Billy Hollis in &lt;a target="_blank" href="http://www.dnrtv.com/default.aspx?showNum=115"&gt;this well-known DNR TV episode&lt;/a&gt;.&amp;nbsp; Rather than take the time to explain what the UI does, &lt;a target="_blank" href="http://vimeo.com/16975621"&gt;have a look at this short video for a brief visual explanation&lt;/a&gt; (apologies for the audio level).&lt;/p&gt;
&lt;p&gt;Ok, now that you&amp;rsquo;ve seen what it does, let&amp;rsquo;s look at how it&amp;rsquo;s put together. As you can see from the screenshot, I&amp;rsquo;ve chosen to organize the project by features: Customers, Orders, Settings, etc. In most projects I prefer to do something like this rather than organizing by &amp;ldquo;technical&amp;rdquo; groupings, such as Views and ViewModels. If I have a complex feature, then I might break that down into those areas.&lt;/p&gt;
&lt;p&gt;I&amp;rsquo;m not going to go line-by-line through this sample. It&amp;rsquo;s better if you take the time to look through it and figure out how things work yourself. But, I do want to point out a few interesting implementation details.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;ViewModel Composition&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;One of the most important features of Screens and Conductors in Caliburn.Micro is that they are an implementation of &lt;a target="_blank" href="http://en.wikipedia.org/wiki/Composite_pattern"&gt;the Composite Pattern&lt;/a&gt;, making them easy to compose together in different configurations. Generally speaking, composition is one of the most important aspects of object oriented programming and learning how to use it in your presentation tier can yield great benefits. To see how composition plays a role in this particular sample, lets look at two screenshots. The first shows the application with the CustomersWorkspace in view, editing a specific Customer&amp;rsquo;s Address. The second screen is the same, but with its View/ViewModel pairs rotated three-dimensionally, so you can see how the UI is composed.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Editing a Customer&amp;rsquo;s Address&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/rob_5F00_eisenberg/Composition_5F00_03F7CA36.png"&gt;&lt;img height="484" width="621" src="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/rob_5F00_eisenberg/Composition_5F00_thumb_5F00_5BE7ABC7.png" alt="Composition" border="0" title="Composition" style="background-image:none;border-right-width:0px;padding-left:0px;padding-right:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;padding-top:0px;" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Editing a Customer&amp;rsquo;s Address (3D Breakout)&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/rob_5F00_eisenberg/Composition_2D00_3d_2D00_01_5F00_54CB0000.png"&gt;&lt;img height="484" width="621" src="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/rob_5F00_eisenberg/Composition_2D00_3d_2D00_01_5F00_thumb_5F00_687A7A45.png" alt="Composition-3d-01" border="0" title="Composition-3d-01" style="background-image:none;border-right-width:0px;padding-left:0px;padding-right:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;padding-top:0px;" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;In this application, the ShellViewModel is a Conductor&amp;lt;IWorkspace&amp;gt;.Collection.OneActive. It is visually represented by the Window Chrome, Header and bottom Dock. The Dock has buttons, one for each IWorkspace that is being conducted. Clicking on a particular button makes the Shell activate that particular workspace. Since the ShellView has a TransitioningContentControl bound to the ActiveItem, the activated workspace is injected and it&amp;rsquo;s view is shown at that location. In this case, it&amp;rsquo;s the CustomerWorkspaceViewModel that is active.&amp;nbsp; It so happens that the CustomerWorkspaceViewModel inherits from Conductor&amp;lt;CustomerViewModel&amp;gt;.Collection.OneActive. There are two contextual views for this ViewModel (see below). In the screenshot above, we are showing the details view. The details view also has a TransitioningContentControl bound to the CustomerWorkspaceViewModel&amp;rsquo;s ActiveItem, thus causing the current CustomerViewModel to be composed in along with its view. The CustomerViewModel has the ability to show local modal dialogs (they are only modal to that specific custom record, not anything else). This is managed by an instance of DialogConductor, which is a property on CustomerViewModel. The view for the DialogConductor overlays the CustomerView, but is only visible (via a value converter) if the DialogConductor&amp;rsquo;s ActiveItem is not null. In the state depicted above, the DialogConductor&amp;rsquo;s ActiveItem is set to an instance of AddressViewModel, thus the modal dialog is displayed with the AddressView and the underlying CustomerView is disabled. The entire shell framework used in this sample works in this fashion and is entirely extensible simply by implementing IWorkspace. CustomerViewModel and SettingsViewModel are two different implementations of this interface you can dig into.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Multiple Views over the Same ViewModel&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;You may not be aware of this, but Caliburn.Micro can display multiple Views over the same ViewModel. This is supported by setting the View.Context attached property on the View/ViewModel&amp;rsquo;s injection site. Here&amp;rsquo;s an example from the default CustomerWorkspaceView:&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;pre name="code" class="xml:nogutter:nocontrols"&gt;&amp;lt;clt:TransitioningContentControl cal:View.Context=&amp;quot;{Binding State, Mode=TwoWay}&amp;quot;
                                 cal:View.Model=&amp;quot;{Binding}&amp;quot; 
                                 Style=&amp;#39;{StaticResource specialTransition}&amp;#39;/&amp;gt;&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;There is a lot of other Xaml surrounding this to form the chrome of the CustomerWorkspaceView, but the content region is the most noteworthy part of the view. Notice that we are binding the View.Context attached property to the State property on the CustomerWorkspaceViewModel. This allows us to dynamically change out views based on the value of that property. Because this is all hosted in the TransitioningContentControl, we get a nice transition whenever the view changes. This technique is used to switch the CustomerWorkspaceViewModel from a &amp;ldquo;Master&amp;rdquo; view, where it displays all open CustomerViewModels, a search UI and a New button, to a &amp;ldquo;Detail&amp;rdquo; view, where it displays the currently activated CustomerViewModel along with it&amp;rsquo;s specific view (composed in). In order for CM to find these contextual views, you need a namespace based on the ViewModel name, minus the words &amp;ldquo;View&amp;rdquo; and &amp;ldquo;Model&amp;rdquo;, with some Views named corresponding to the Context. For example, when the framework looks for the Detail view of Caliburn.Micro.HelloScreens.Customers.CustomersWorkspaceViewModel, it&amp;rsquo;s going to look for Caliburn.Micro.HelloScreens.Customers.CustomersWorkspace.Detail That&amp;rsquo;s the out-of-the-box naming convention. If that doesn&amp;rsquo;t work for you, you can simply customize the ViewLocator.LocateForModelType func.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Custom IConductor Implementation&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Although Caliburn.Micro provides the developer with default implementations of IScreen and IConductor. It&amp;rsquo;s easy to implement your own. In the case of this sample, I needed a dialog manager that could be modal to a specific part of the application without affecting other parts. Normally, the default Conductor&amp;lt;T&amp;gt; would work, but I discovered I needed to fine-tune shutdown sequence, so I implemented my own. Let&amp;rsquo;s take a look at that:&lt;/p&gt;
&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;[Export(typeof(IDialogManager)), PartCreationPolicy(CreationPolicy.NonShared)]
public class DialogConductorViewModel : PropertyChangedBase, IDialogManager, IConductor {
    readonly Func&amp;lt;IMessageBox&amp;gt; createMessageBox;

    [ImportingConstructor]
    public DialogConductorViewModel(Func&amp;lt;IMessageBox&amp;gt; messageBoxFactory) {
        createMessageBox = messageBoxFactory;
    }

    public IScreen ActiveItem { get; private set; }

    public IEnumerable GetConductedItems() {
        return ActiveItem != null ? new[] { ActiveItem } : new object[0];
    }

    public void ActivateItem(object item) {
        ActiveItem = item as IScreen;

        var child = ActiveItem as IChild&amp;lt;IConductor&amp;gt;;
        if(child != null)
            child.Parent = this;

        if(ActiveItem != null)
            ActiveItem.Activate();

        NotifyOfPropertyChange(() =&amp;gt; ActiveItem);
        ActivationProcessed(this, new ActivationProcessedEventArgs { Item = ActiveItem, Success = true });
    }

    public void CloseItem(object item) {
        var guard = item as IGuardClose;
        if(guard != null) {
            guard.CanClose(result =&amp;gt; {
                if(result)
                    CloseActiveItemCore();
            });
        }
        else CloseActiveItemCore();
    }

    object IConductor.ActiveItem {
        get { return ActiveItem; }
        set { ActivateItem(value); }
    }

    public event EventHandler&amp;lt;ActivationProcessedEventArgs&amp;gt; ActivationProcessed = delegate { };

    public void ShowDialog(IScreen dialogModel) {
        ActivateItem(dialogModel);
    }

    public void ShowMessageBox(string message, string title = null, MessageBoxOptions options = MessageBoxOptions.Ok, Action&amp;lt;IMessageBox&amp;gt; callback = null) {
        var box = createMessageBox();

        box.DisplayName = title ?? &amp;quot;Hello Screens&amp;quot;;
        box.Options = options;
        box.Message = message;

        if(callback != null)
            box.Deactivated += delegate { callback(box); };

        ActivateItem(box);
    }

    void CloseActiveItemCore() {
        var oldItem = ActiveItem;
        ActivateItem(null);
        oldItem.Deactivate(true);
    }
}&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Strictly speaking, I didn&amp;rsquo;t actually need to implement IConductor to make this work (since I&amp;rsquo;m not composing it into anything). But I chose to do this in order to represent the role this class was playing in the system and keep things as architecturally consistent as possible. The implementation itself is pretty straight forward. Mainly, a conductor needs to make sure to Activate/Deactivate its items correctly and to properly update the ActiveItem property. I also created a couple of simple methods for showing dialogs and message boxes which are exposed through the IDialogManager interface. This class is registered as NonShared with MEF so that each portion of the application that wants to display local modals will get its own instance and be able to maintain its own state, as demonstrated with the CustomerViewModel discussed above.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Custom ICloseStrategy&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Possibly one of the coolest features of this sample is how we control application shutdown. Since IShell inherits IGuardClose, in the Bootstrapper we just override DisplayRootView and wire Silverlight&amp;rsquo;s MainWindow.Closing event to call IShell.CanClose:&lt;/p&gt;
&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;protected override void DisplayRootView() {
    base.DisplayRootView();

    if (Application.IsRunningOutOfBrowser) {
        mainWindow = Application.MainWindow;
        mainWindow.Closing += MainWindowClosing;
    }
}

void MainWindowClosing(object sender, ClosingEventArgs e) {
    if (actuallyClosing)
        return;

    e.Cancel = true;

    Execute.OnUIThread(() =&amp;gt; {
        var shell = IoC.Get&amp;lt;IShell&amp;gt;();

        shell.CanClose(result =&amp;gt; {
            if(result) {
                actuallyClosing = true;
                mainWindow.Close();
            }
        });
    });
}&lt;/pre&gt;
&lt;p&gt;The ShellViewModel inherits this functionality through its base class Conductor&amp;lt;IWorkspace&amp;gt;.Collection.OneActive. Since all the built-in conductors have a CloseStrategy, we can create conductor specific mechanisms for shutdown and plug them in easily. Here&amp;rsquo;s how we plug in our custom strategy:&lt;/p&gt;
&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;[Export(typeof(IShell))]
public class ShellViewModel : Conductor&amp;lt;IWorkspace&amp;gt;.Collection.OneActive, IShell
{
    readonly IDialogManager dialogs;

    [ImportingConstructor]
    public ShellViewModel(IDialogManager dialogs, [ImportMany]IEnumerable&amp;lt;IWorkspace&amp;gt; workspaces) {
        this.dialogs = dialogs;
        Items.AddRange(workspaces);
        CloseStrategy = new ApplicationCloseStrategy();
    }

    public IDialogManager Dialogs {
        get { return dialogs; }
    }
}&lt;/pre&gt;
&lt;p&gt;And here&amp;rsquo;s the implementation of that strategy:&lt;/p&gt;
&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;public class ApplicationCloseStrategy : ICloseStrategy&amp;lt;IWorkspace&amp;gt; {
    IEnumerator&amp;lt;IWorkspace&amp;gt; enumerator;
    bool finalResult;
    Action&amp;lt;bool, IEnumerable&amp;lt;IWorkspace&amp;gt;&amp;gt; callback;

    public void Execute(IEnumerable&amp;lt;IWorkspace&amp;gt; toClose, Action&amp;lt;bool, IEnumerable&amp;lt;IWorkspace&amp;gt;&amp;gt; callback) {
        enumerator = toClose.GetEnumerator();
        this.callback = callback;
        finalResult = true;

        Evaluate(finalResult);
    }

    void Evaluate(bool result)
    {
        finalResult = finalResult &amp;amp;&amp;amp; result;

        if (!enumerator.MoveNext() || !result)
            callback(finalResult, new List&amp;lt;IWorkspace&amp;gt;());
        else
        {
            var current = enumerator.Current;
            var conductor = current as IConductor;
            if (conductor != null)
            {
                var tasks = conductor.GetConductedItems()
                    .OfType&amp;lt;IHaveShutdownTask&amp;gt;()
                    .Select(x =&amp;gt; x.GetShutdownTask())
                    .Where(x =&amp;gt; x != null);

                var sequential = new SequentialResult(tasks.GetEnumerator());
                sequential.Completed += (s, e) =&amp;gt; {
                    if(!e.WasCancelled)
                    Evaluate(!e.WasCancelled);
                };
                sequential.Execute(new ActionExecutionContext());
            }
            else Evaluate(true);
        }
    }
}&lt;/pre&gt;
&lt;p&gt;The interesting thing I did here was to reuse the IResult functionality for async shutdown of the application. Here&amp;rsquo;s how the custom strategy uses it:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Check each IWorkspace to see if it is an IConductor.&lt;/li&gt;
&lt;li&gt;If true, grab all the conducted items which implement the application-specific interface IHaveShutdownTask.&lt;/li&gt;
&lt;li&gt;Retrieve the shutdown task by calling GetShutdownTask. It will return null if there is no task, so filter those out.&lt;/li&gt;
&lt;li&gt;Since the shutdown task is an IResult, pass all of these to a SequentialResult and begin enumeration.&lt;/li&gt;
&lt;li&gt;The IResult can set ResultCompletionEventArgs.WasCanceled to true to cancel the application shutdown.&lt;/li&gt;
&lt;li&gt;Continue through all workspaces until finished or cancellation occurs.&lt;/li&gt;
&lt;li&gt;If all IResults complete successfully, the application will be allowed to close.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The CustomerViewModel and OrderViewModel use this mechanism to display a modal dialog if there is dirty data. But, you could also use this for any number of async tasks. For example, suppose you had some long running process that you wanted to prevent shutdown of the application. This would work quite nicely for that too.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;This concludes our short mini-series on Screens and Conductors. I hope I have provided enough theory, documentation and samples to get you going in the right direction. That said, if you don&amp;rsquo;t understand these concepts or don&amp;rsquo;t see the problems in your app that these were intended to solve, then don&amp;rsquo;t use them. Screens/Conductors are best used when you encounter the sorts of engineering difficulties that they were intended for. Simply inheriting willy-nilly from these base classes will likely add unnecessary complexity to your application. As always, use every feature &lt;em&gt;intentionally&lt;/em&gt; to solve a specific problem&amp;hellip;not just because it&amp;rsquo;s there &lt;img src="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/rob_5F00_eisenberg/wlEmoticon_2D00_smile_5F00_33707BC6.png" alt="Smile" class="wlEmoticon wlEmoticon-smile" style="border-bottom-style:none;border-left-style:none;border-top-style:none;border-right-style:none;" /&gt; If in doubt, avoid Screens/Conductors. When the need arises, you&amp;rsquo;ll know what they are and where to use them.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Next Up: All About Conventions&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=63478" width="1" height="1"&gt;</description><enclosure url="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Components.PostAttachments/00.00.06.34.78/Caliburn.Micro.HelloScreens.zip" length="206682" type="application/x-zip-compressed" /><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/WPF/default.aspx">WPF</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/Xaml/default.aspx">Xaml</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/databinding/default.aspx">databinding</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/WPF_2F00_e/default.aspx">WPF/e</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/Caliburn/default.aspx">Caliburn</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/Featured/default.aspx">Featured</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/Silverlight/default.aspx">Silverlight</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/RIA/default.aspx">RIA</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/Tutorial/default.aspx">Tutorial</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/MEF/default.aspx">MEF</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/MVVM/default.aspx">MVVM</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/UI+Architecture/default.aspx">UI Architecture</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/Caliburn+Micro/default.aspx">Caliburn Micro</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/WP7/default.aspx">WP7</category></item><item><title>Caliburn.Micro Soup to Nuts Part 6c – Simple MDI with Screen Collections</title><link>http://devlicio.us/blogs/rob_eisenberg/archive/2010/10/19/caliburn-micro-soup-to-nuts-part-6c-simple-mdi-with-screen-collections.aspx</link><pubDate>Tue, 19 Oct 2010 20:51:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:62933</guid><dc:creator>Rob Eisenberg</dc:creator><slash:comments>5</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/rob_eisenberg/rsscomments.aspx?PostID=62933</wfw:commentRss><comments>http://devlicio.us/blogs/rob_eisenberg/archive/2010/10/19/caliburn-micro-soup-to-nuts-part-6c-simple-mdi-with-screen-collections.aspx#comments</comments><description>&lt;p&gt;Let&amp;rsquo;s look at another example: this time a simple MDI shell that uses &amp;ldquo;Screen Collections.&amp;rdquo; As you can see, once again, I have kept things pretty small and simple:&lt;/p&gt;
&lt;p&gt;&lt;a href="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/rob_5F00_eisenberg/SimpleMdiProject_5F00_35A88333.jpg"&gt;&lt;img height="162" width="244" src="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/rob_5F00_eisenberg/SimpleMdiProject_5F00_thumb_5F00_1E7D08B5.jpg" alt="SimpleMdiProject" border="0" title="SimpleMdiProject" style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;p&gt;Here&amp;rsquo;s a screenshot of the application when it&amp;rsquo;s running:&lt;/p&gt;
&lt;p&gt;&lt;a href="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/rob_5F00_eisenberg/SimpleMdiScreenshot_5F00_24C3DF43.jpg"&gt;&lt;img height="210" width="244" src="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/rob_5F00_eisenberg/SimpleMdiScreenshot_5F00_thumb_5F00_1FE12B87.jpg" alt="SimpleMdiScreenshot" border="0" title="SimpleMdiScreenshot" style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Here we have a simple WPF application with a series of tabs. Clicking the &amp;ldquo;Open Tab&amp;rdquo; button does the obvious. Clicking the &amp;ldquo;X&amp;rdquo; inside the tab will close that particular tab (also, probably obvious). Let&amp;rsquo;s dig into the code by looking at our ShellViewModel:    &lt;/p&gt;
&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;public class ShellViewModel : Conductor&amp;lt;IScreen&amp;gt;.Collection.OneActive {
    int count = 1;

    public void OpenTab() {
        ActivateItem(new TabViewModel {
            DisplayName = &amp;quot;Tab &amp;quot; + count++
        });
    }
}&lt;/pre&gt;
&lt;p&gt;Since we want to maintain a list of open items, but only keep one item active at a time, we use &lt;em&gt;Conductor&amp;lt;T&amp;gt;.Collection.OneActive&lt;/em&gt; as our base class. Note that, different from our previous example, I am actually constraining the type of the conducted item to &lt;em&gt;IScreen&lt;/em&gt;. There&amp;rsquo;s not really a technical reason for this in this sample, but this more closely mirrors what I would actually do in a real application. The OpenTab method simply creates an instance of a TabViewModel and sets its &lt;em&gt;DisplayName&lt;/em&gt; property (from &lt;em&gt;IScreen&lt;/em&gt;) so that it has a human-readable, unique name. Let&amp;rsquo;s think through the logic for the interaction between the conductor and its screens in several key scenarios:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Opening the First Item&lt;/em&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Adds the item to the Items collection.&lt;/li&gt;
&lt;li&gt;Checks the item for IActivate and invokes it if present.&lt;/li&gt;
&lt;li&gt;Sets the item as the ActiveItem.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;em&gt;Opening an Additional Item&lt;/em&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Checks the current ActiveItem for IDeactivate and invokes if present. &lt;em&gt;False &lt;/em&gt;is passed to indicate that it should be deactivated only, and not closed.&lt;/li&gt;
&lt;li&gt;Checks the new item to see if it already exists in the Items collection. If not, it is added to the collection. Otherwise, the existing item is returned.&lt;/li&gt;
&lt;li&gt;Checks the item for IActivate and invokes if present.&lt;/li&gt;
&lt;li&gt;Sets the new item as the ActiveItem.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;em&gt;Closing an Existing Item&lt;/em&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Passes the item to the CloseStrategy to determine if it can be closed (by default it looks for IGuardClose). If not, the action is cancelled.&lt;/li&gt;
&lt;li&gt;Checks to see if the closing item is the current ActiveItem. If so, determine which item to activate next and follow steps from &amp;ldquo;Opening an Additional Item.&amp;rdquo;&lt;/li&gt;
&lt;li&gt;Checks to see if the closing item is IDeactivate. If so, invoke with &lt;em&gt;true&lt;/em&gt; to indicate that it should be deactivated and closed.&lt;/li&gt;
&lt;li&gt;Remove the item from the Items collection.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Those are the main scenarios. Hopefully you can see some of the differences from a Conductor without a collection and understand why those differences are there. Let&amp;rsquo;s see how the ShellView renders:&lt;/p&gt;
&lt;pre name="code" class="xml:nogutter:nocontrols"&gt;&amp;lt;Window x:Class=&amp;quot;Caliburn.Micro.SimpleMDI.ShellView&amp;quot;
        xmlns=&amp;quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&amp;quot;
        xmlns:x=&amp;quot;http://schemas.microsoft.com/winfx/2006/xaml&amp;quot;
        xmlns:cal=&amp;quot;http://www.caliburnproject.org&amp;quot;
        Width=&amp;quot;640&amp;quot;
        Height=&amp;quot;480&amp;quot;&amp;gt;
    &amp;lt;DockPanel&amp;gt;
        &amp;lt;Button x:Name=&amp;quot;OpenTab&amp;quot;
                Content=&amp;quot;Open Tab&amp;quot; 
                DockPanel.Dock=&amp;quot;Top&amp;quot; /&amp;gt;
        &amp;lt;TabControl x:Name=&amp;quot;Items&amp;quot;&amp;gt;
            &amp;lt;TabControl.ItemTemplate&amp;gt;
                &amp;lt;DataTemplate&amp;gt;
                    &amp;lt;StackPanel Orientation=&amp;quot;Horizontal&amp;quot;&amp;gt;
                        &amp;lt;TextBlock Text=&amp;quot;{Binding DisplayName}&amp;quot; /&amp;gt;
                        &amp;lt;Button Content=&amp;quot;X&amp;quot;
                                cal:Message.Attach=&amp;quot;CloseItem($dataContext)&amp;quot; /&amp;gt;
                    &amp;lt;/StackPanel&amp;gt;
                &amp;lt;/DataTemplate&amp;gt;
            &amp;lt;/TabControl.ItemTemplate&amp;gt;
        &amp;lt;/TabControl&amp;gt;
    &amp;lt;/DockPanel&amp;gt;
&amp;lt;/Window&amp;gt;&lt;/pre&gt;
&lt;p&gt;As you can see we are using a WPF TabControl. CM&amp;rsquo;s conventions will bind its ItemsSource to the Items collection and its SelectedItem to the ActiveItem. It will also add a default ContentTemplate which will be used to compose in the ViewModel/View pair for the ActiveItem. Conventions can also supply an ItemTemplate since our tabs all implement IHaveDisplayName (through Screen), but I&amp;rsquo;ve opted to override that by supplying my own to enable closing the tabs. We&amp;rsquo;ll talk more in depth about conventions in a later article. For completeness, here are the trivial implementations of TabViewModel along with its view:&lt;/p&gt;
&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;namespace Caliburn.Micro.SimpleMDI {
    public class TabViewModel : Screen {}
}&lt;/pre&gt;
&lt;pre name="code" class="xml:nogutter:nocontrols"&gt;&amp;lt;UserControl x:Class=&amp;quot;Caliburn.Micro.SimpleMDI.TabView&amp;quot;
             xmlns=&amp;quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&amp;quot;
             xmlns:x=&amp;quot;http://schemas.microsoft.com/winfx/2006/xaml&amp;quot;&amp;gt;
    &amp;lt;StackPanel Orientation=&amp;quot;Horizontal&amp;quot;&amp;gt;
        &amp;lt;TextBlock Text=&amp;quot;This is the view for &amp;quot;/&amp;gt;
        &amp;lt;TextBlock x:Name=&amp;quot;DisplayName&amp;quot; /&amp;gt;
        &amp;lt;TextBlock Text=&amp;quot;.&amp;quot; /&amp;gt;
    &amp;lt;/StackPanel&amp;gt;
&amp;lt;/UserControl&amp;gt;&lt;/pre&gt;
&lt;p&gt;I&amp;rsquo;ve tried to keep it simple so far, but that&amp;rsquo;s not the case for our next sample. In preparation, you might want to at least think through or try to do these things:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Get rid of the generic TabViewModel. You wouldn&amp;rsquo;t really do something like this in a real application. Create a couple of custom view models and views. Wire things up so that you can open different view models in the conductor. Confirm that you see the correct view in the tab control when each view model is activated.&lt;/li&gt;
&lt;li&gt;Rebuild this sample in Silverlight. Unfortunately, Silverlight&amp;rsquo;s TabControl is utterly broken and cannot fully leverage databinding. Instead, try using a horizontal ListBox as the tabs and a ContentControl as the tab content. Put these in a DockPanel and use some naming conventions and you will have the same affect as a TabControl.&lt;/li&gt;
&lt;li&gt;Create a toolbar view model. Add an IoC container and register the ToolBarViewModel as a singleton. Add it to the ShellViewModel and ensure that it is rendered in the ShellView (remember you can use a named ContentControl for this). Next, have the ToolBarViewModel injected into each of the TabViewModels. Write code in the TabViewModel OnActivate and OnDeactivate to add/remove contextual items from the toolbar when the particular TabViewModel is activated. BONUS: Create a DSL for doing this which doesn&amp;rsquo;t require explicit code in the OnDeactivate override. HINT: Use the events.&lt;/li&gt;
&lt;li&gt;Take the SimpleMDI sample and the SimpleNavigation sample and compose them together. Either add the MDI Shell as a PageViewModel in the Navigation Sample or add the Navigation Shell as a Tab in the MDI Sample.&lt;/li&gt;
&lt;/ul&gt;
&lt;ol&gt;
&lt;/ol&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=62933" width="1" height="1"&gt;</description><enclosure url="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Components.PostAttachments/00.00.06.29.33/Caliburn.Micro.SimpleMDI.zip" length="10739" type="application/x-zip-compressed" /><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/WPF/default.aspx">WPF</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/Xaml/default.aspx">Xaml</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/databinding/default.aspx">databinding</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/WPF_2F00_e/default.aspx">WPF/e</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/Caliburn/default.aspx">Caliburn</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/Featured/default.aspx">Featured</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/Silverlight/default.aspx">Silverlight</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/RIA/default.aspx">RIA</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/Tutorial/default.aspx">Tutorial</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/MVVM/default.aspx">MVVM</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/UI+Architecture/default.aspx">UI Architecture</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/Caliburn+Micro/default.aspx">Caliburn Micro</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/WP7/default.aspx">WP7</category></item><item><title>Caliburn.Micro Soup to Nuts Part 6b – Simple Navigation with Conductors</title><link>http://devlicio.us/blogs/rob_eisenberg/archive/2010/10/12/caliburn-micro-soup-to-nuts-part-6b-simple-navigation-with-conductors.aspx</link><pubDate>Tue, 12 Oct 2010 15:38:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:62792</guid><dc:creator>Rob Eisenberg</dc:creator><slash:comments>3</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/rob_eisenberg/rsscomments.aspx?PostID=62792</wfw:commentRss><comments>http://devlicio.us/blogs/rob_eisenberg/archive/2010/10/12/caliburn-micro-soup-to-nuts-part-6b-simple-navigation-with-conductors.aspx#comments</comments><description>&lt;p&gt;&lt;a href="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/rob_5F00_eisenberg/SimpleNavigationProject_5F00_67C2FB8A.jpg"&gt;&lt;img height="222" width="244" src="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/rob_5F00_eisenberg/SimpleNavigationProject_5F00_thumb_5F00_3EBAED3F.jpg" align="right" alt="SimpleNavigationProject" border="0" title="SimpleNavigationProject" style="border-right-width:0px;margin:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" /&gt;&lt;/a&gt;Previously, we discussed the theory and basic APIs for Screens and Conductors in Caliburn.Micro. Now I would like to walk through the first of several samples. This particular sample demonstrates how to set up a simple navigation-style shell using Conductor&amp;lt;T&amp;gt; and two &amp;ldquo;Page&amp;rdquo; view models. As you can see from the project structure, we have the typical pattern of Bootstrapper and ShellViewModel. In order to keep this sample as simple as possible, I&amp;rsquo;m not even using an IoC container with the Bootstrapper. Let&amp;rsquo;s look at the ShellViewModel first. It inherits from Conductor&amp;lt;object&amp;gt; and is implemented as follows:&lt;/p&gt;
&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;public class ShellViewModel : Conductor&amp;lt;object&amp;gt; {
    public ShellViewModel() {
        ShowPageOne();
    }

    public void ShowPageOne() {
        ActivateItem(new PageOneViewModel());
    }

    public void ShowPageTwo() {
        ActivateItem(new PageTwoViewModel());
    }
}&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Here is the corresponding ShellView:&lt;/p&gt;
&lt;pre name="code" class="xml:nogutter:nocontrols"&gt;&amp;lt;UserControl x:Class=&amp;quot;Caliburn.Micro.SimpleNavigation.ShellView&amp;quot;
             xmlns=&amp;quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&amp;quot;
             xmlns:x=&amp;quot;http://schemas.microsoft.com/winfx/2006/xaml&amp;quot;
             xmlns:tc=&amp;quot;clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Toolkit&amp;quot;&amp;gt;
    &amp;lt;tc:DockPanel&amp;gt;
        &amp;lt;StackPanel Orientation=&amp;quot;Horizontal&amp;quot;
                    HorizontalAlignment=&amp;quot;Center&amp;quot;
                    tc:DockPanel.Dock=&amp;quot;Top&amp;quot;&amp;gt;
            &amp;lt;Button x:Name=&amp;quot;ShowPageOne&amp;quot;
                    Content=&amp;quot;Show Page One&amp;quot; /&amp;gt;
            &amp;lt;Button x:Name=&amp;quot;ShowPageTwo&amp;quot;
                    Content=&amp;quot;Show Page Two&amp;quot; /&amp;gt;
        &amp;lt;/StackPanel&amp;gt;

        &amp;lt;ContentControl x:Name=&amp;quot;ActiveItem&amp;quot; /&amp;gt;
    &amp;lt;/tc:DockPanel&amp;gt;
&amp;lt;/UserControl&amp;gt;&lt;/pre&gt;
&lt;p&gt;Notice that the ShellViewModel has two methods, each of which passes a view model instance to the &lt;em&gt;ActivateItem&lt;/em&gt; method. Recall from our earlier discussion that &lt;em&gt;ActivateItem&lt;/em&gt; is a method on &lt;em&gt;Conductor&amp;lt;T&amp;gt;&lt;/em&gt; which will switch the &lt;em&gt;ActiveItem&lt;/em&gt; property of the conductor to this instance and push the instance through the activation stage of the screen lifecycle (if it supports it by implementing &lt;em&gt;IActivate&lt;/em&gt;). Recall also, that if &lt;em&gt;ActiveItem&lt;/em&gt; is already set to an instance, then before the new instance is set, the previous instance will be checked for an implementation of &lt;em&gt;IGuardClose&lt;/em&gt; which may or may not cancel switching of the &lt;em&gt;ActiveItem&lt;/em&gt;. Assuming the current &lt;em&gt;ActiveItem&lt;/em&gt; can close, the conductor will then push it through the deactivation stage of the lifecycle, passing true to the &lt;em&gt;Deactivate&lt;/em&gt; method to indicate that the view model should also be closed. This is all it takes to create a navigation application in Caliburn.Micro. The &lt;em&gt;ActiveItem&lt;/em&gt; of the conductor represents the &amp;ldquo;current page&amp;rdquo; and the conductor manages the transitions from one page to the other. This is all done in a ViewModel-First fashion since its the conductor and it&amp;rsquo;s child view models that are driving the navigation and not the &amp;ldquo;views.&amp;rdquo;&lt;/p&gt;
&lt;p&gt;Once the basic Conductor structure is in place, it&amp;rsquo;s quite easy to get it rendering. The ShellView demonstrates this. All we have to do is place a ContentControl in the view. By naming it &amp;ldquo;ActiveItem&amp;rdquo; our data binding conventions kick in. The convention for ContentControl is a bit interesting. If the item we are binding to is not a value type and not a string, then we assume that the Content is a ViewModel. So, instead of binding to the Content property as we would in the other cases, we actually set up a binding with CM&amp;rsquo;s custom attached property: View.Model. This property causes CM&amp;rsquo;s &lt;em&gt;ViewLocator&lt;/em&gt; to look up the appropriate view for the view model and CM&amp;rsquo;s &lt;em&gt;ViewModelBinder&lt;/em&gt; to bind the two together. Once that is complete, we pop the view into the ContentControl&amp;rsquo;s Content property. This single convention is what enables the powerful, yet simple ViewModel-First composition in the framework.&lt;/p&gt;
&lt;p&gt;For completeness, let&amp;rsquo;s take a look at the PageOneViewModel and PageTwoViewModel:&lt;/p&gt;
&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;public class PageOneViewModel {}

public class PageTwoViewModel : Screen {
    protected override void OnActivate() {
        MessageBox.Show(&amp;quot;Page Two Activated&amp;quot;); //Don&amp;#39;t do this in a real VM.
        base.OnActivate();
    }
}&lt;/pre&gt;
&lt;p&gt;Along with their views:&lt;/p&gt;
&lt;pre name="code" class="xml:nogutter:nocontrols"&gt;&amp;lt;UserControl x:Class=&amp;quot;Caliburn.Micro.SimpleNavigation.PageOneView&amp;quot;
             xmlns=&amp;quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&amp;quot;
             xmlns:x=&amp;quot;http://schemas.microsoft.com/winfx/2006/xaml&amp;quot;&amp;gt;
    &amp;lt;TextBlock FontSize=&amp;quot;32&amp;quot;&amp;gt;Page One&amp;lt;/TextBlock&amp;gt;
&amp;lt;/UserControl&amp;gt;

&amp;lt;UserControl x:Class=&amp;quot;Caliburn.Micro.SimpleNavigation.PageTwoView&amp;quot;
             xmlns=&amp;quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&amp;quot;
             xmlns:x=&amp;quot;http://schemas.microsoft.com/winfx/2006/xaml&amp;quot;&amp;gt;
    &amp;lt;TextBlock FontSize=&amp;quot;32&amp;quot;&amp;gt;Page Two&amp;lt;/TextBlock&amp;gt;
&amp;lt;/UserControl&amp;gt;&lt;/pre&gt;
&lt;p&gt;I&amp;rsquo;ve intentionally kept this bare bones so that it&amp;rsquo;s easy to play around with and see how these pieces work together. It&amp;rsquo;s not the slightest bit impressive, but here&amp;rsquo;s what it looks like:&lt;/p&gt;
&lt;p&gt;&lt;a href="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/rob_5F00_eisenberg/PageTwo_5F00_4501C3CD.jpg"&gt;&lt;img height="228" width="244" src="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/rob_5F00_eisenberg/PageTwo_5F00_thumb_5F00_752B9F41.jpg" alt="PageTwo" border="0" title="PageTwo" style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;p&gt;I&amp;rsquo;d like to point out a few final things. Notice that PageOneViewModel is just a POCO, but PageTwoViewModel inherits from &lt;em&gt;Screen&lt;/em&gt;. Remember that the conductors in CM don&amp;rsquo;t place any constraints on what can be conducted. Rather, they check each instance for support of the various fine-grained lifecycle instances at the necessary times. So, when &lt;em&gt;ActivateItem&lt;/em&gt; is called for PageTwoViewModel, it will first check PageOneViewModel to see if it implements &lt;em&gt;IGuardClose&lt;/em&gt;. Since it does not, it will attempt to close it. It will then check to see if it implements &lt;em&gt;IDeactivate&lt;/em&gt;. Since it does not, it will just proceed to activate the new item. First it checks if the new item implements &lt;em&gt;IChild&amp;lt;IConductor&amp;gt;.&lt;/em&gt; Since &lt;em&gt;Screen&lt;/em&gt; does, it hooks up the hierarchical relationship. Next, it will check PageTwoViewModel to see if it implements &lt;em&gt;IActivate&lt;/em&gt;. Since &lt;em&gt;Screen&lt;/em&gt; does, the code in my &lt;em&gt;OnActivate&lt;/em&gt; method will then run. Finally, it will set the &lt;em&gt;ActiveItem&lt;/em&gt; property on the conductor and raise the appropriate events. Here&amp;rsquo;s an important consequence of this that should be remembered: The activation is a ViewModel-specific lifecycle process and doesn&amp;rsquo;t guarantee anything about the state of the View. Many times, even though your ViewModel has been activated, it&amp;rsquo;s view may not yet be visible. You will see this when you run the sample. The MessageBox will show when the activation occurs, but the view for page two will not yet be visible. Remember, if you have any activation logic that is dependent on the view being already loaded, you should override &lt;em&gt;Screen.OnViewLoaded&lt;/em&gt; instead of/in combination with &lt;em&gt;OnActivate&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;Stay tuned, more samples to come&amp;hellip;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=62792" width="1" height="1"&gt;</description><enclosure url="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Components.PostAttachments/00.00.06.27.92/Caliburn.Micro.SimpleNavigation.zip" length="8209" type="application/x-zip-compressed" /><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/WPF/default.aspx">WPF</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/Xaml/default.aspx">Xaml</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/databinding/default.aspx">databinding</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/WPF_2F00_e/default.aspx">WPF/e</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/.NET+3.5/default.aspx">.NET 3.5</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/Caliburn/default.aspx">Caliburn</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/Featured/default.aspx">Featured</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/Silverlight/default.aspx">Silverlight</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/RIA/default.aspx">RIA</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/Tutorial/default.aspx">Tutorial</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/MVVM/default.aspx">MVVM</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/UI+Architecture/default.aspx">UI Architecture</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/Caliburn+Micro/default.aspx">Caliburn Micro</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/WP7/default.aspx">WP7</category></item><item><title>Caliburn.Micro Soup to Nuts Part 6a – Screens, Conductors and Composition</title><link>http://devlicio.us/blogs/rob_eisenberg/archive/2010/10/08/caliburn-micro-soup-to-nuts-part-6a-screens-conductors-and-composition.aspx</link><pubDate>Fri, 08 Oct 2010 20:59:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:62714</guid><dc:creator>Rob Eisenberg</dc:creator><slash:comments>4</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/rob_eisenberg/rsscomments.aspx?PostID=62714</wfw:commentRss><comments>http://devlicio.us/blogs/rob_eisenberg/archive/2010/10/08/caliburn-micro-soup-to-nuts-part-6a-screens-conductors-and-composition.aspx#comments</comments><description>&lt;p&gt;Actions, Coroutines and Conventions tend to draw the most attention to Caliburn.Micro, but the Screens and Conductors piece is probably most important to understand if you want your UI to be engineered well. It&amp;rsquo;s particularly important if you want to leverage composition. The terms Screen, Screen Conductor and Screen Collection have more &lt;a target="_blank" href="http://www.jeremydmiller.com/ppatterns/Default.aspx"&gt;recently been codified by Jeremy Miller during his work on the book &amp;quot;Presentation Patterns&amp;quot; for Addison Wesley&lt;/a&gt;. While these patterns are primarily used in CM by inheriting ViewModels from particular base classes, its important to think of them as &lt;em&gt;roles&lt;/em&gt; rather than as View-Models. In fact, depending on your architecture, a Screen could a be a UserControl, Presenter or ViewModel. That&amp;rsquo;s getting a little ahead of ourselves though. First, let&amp;rsquo;s talk about what these things are in general.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Screen&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;This is the simplest construct to understand. You might think of it as a&amp;nbsp; stateful unit of work existing within the presentation tier of an application. It&amp;rsquo;s independent from the application shell. The shell may display many different screens, some even at the same time. The shell may display lots of widgets as well, but these are not part of any screen. Some screen examples might be a modal dialog for application settings, a code editor window in Visual Studio or a page in a browser. You probably have a pretty good intuitive sense about this.&lt;/p&gt;
&lt;p&gt;Often times a screen has a lifecycle associated with it which allows the screen to perform custom activation and deactivation logic. This is what Jeremy calls the &lt;a target="_blank" href="http://www.jeremydmiller.com/ppatterns/PageNotFound.aspx?Page=ScreenActivator"&gt;ScreenActivator&lt;/a&gt;. For example, take the Visual Studio code editor window. If you are editing a C# code file in one tab, then you switch to a tab containing an XML document, you will notice that the toolbar icons change. Each one of those screens has custom activation/deactivation logic that enables it to setup/teardown the application toolbars such that they provide the appropriate icons based on the active screen. In simple scenarios, the ScreenActivator is often the same class as the Screen. However, you should remember that these are two separate roles. If a particular screen has complex activation logic, it may be necessary to factor the ScreenActivator into its own class in order to reduce the complexity of the Screen. This is particularly important if you have an application with many different screens, but all with the same activation/deactivation logic.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Screen Conductor&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Once you introduce the notion of a &lt;a target="_blank" href="http://www.jeremydmiller.com/ppatterns/ScreenActivationLifecycle.ashx"&gt;Screen Activation Lifecycle&lt;/a&gt; into your application, you need some way to enforce it. This is the role of the &lt;a target="_blank" href="http://www.jeremydmiller.com/ppatterns/ScreenConductor.ashx"&gt;ScreenConductor&lt;/a&gt;.&amp;nbsp; When you show a screen, the conductor makes sure it is properly activated. If you are transitioning away from a screen, it makes sure it gets deactivated. There&amp;rsquo;s another scenario that&amp;rsquo;s important as well. Suppose that you have a screen which contains unsaved data and someone tries to close that screen or even the application. The ScreenConductor, which is already enforcing deactivation, can help out by implementing &lt;a target="_blank" href="http://www.jeremydmiller.com/ppatterns/ApplicationShutdown.ashx"&gt;Graceful Shutdown&lt;/a&gt;. In the same way that your Screen might implement an interface for activation/deactivation, it may also implement some interface which allows the conductor to ask it &amp;ldquo;Can you close?&amp;rdquo; This brings up an important point: in some scenarios deactivating a screen is the same as closing a screen and in others, it is different. For example, in Visual Studio, it doesn&amp;rsquo;t close documents when you switch from tab to tab. It just activates/deactivates them. You have to explicitly close the tab. That is what triggers the graceful shutdown logic. However, in a navigation based application, navigating away from a page would definitely cause deactivation, but it might also cause that page to close. It all depends on your specific application&amp;rsquo;s architecture and it&amp;rsquo;s something you should think carefully about.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Screen Collection &lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;In an application like Visual Studio, you would not only have a ScreenConductor managing activation, deactivation, etc., but would also have a &lt;a target="_blank" href="http://www.jeremydmiller.com/ppatterns/ScreenCollection.ashx"&gt;ScreenCollection&lt;/a&gt; maintaining the list of currently opened screens or documents. By adding this piece of the puzzle, we can also solve the issue of deactivation vs. close. Anything that is in the ScreenCollection remains open, but only one of those items is active at a time. In an MDI-style application like VS, the conductor would manage switching the active screen between members of the ScreenCollection. Opening a new document would add it to the ScreenCollection and switch it to the active screen.&amp;nbsp; Closing a document would not only deactivate it, but would remove it from the ScreenCollection. All that would be dependent on whether or not it answers the question &amp;ldquo;Can you close?&amp;rdquo; positively. Of course, after the document is closed, the conductor needs to decide which of the other items in the ScreenCollection should become the next active document.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;There are lots of different ways to implement these ideas. You could inherit from a TabControl and implement an IScreenConductor interface and build all the logic directly in the control. Add that to your IoC container and you&amp;rsquo;re off and running. You could implement an IScreen interface on a custom UserControl or you could implement it as a POCO used as a base for &lt;a target="_blank" href="http://www.jeremydmiller.com/ppatterns/SupervisingController.ashx"&gt;Supervising Controllers&lt;/a&gt;. ScreenCollection could be a custom collection with special logic for maintaining the active screen, or it could just be a simple IList&amp;lt;IScreen&amp;gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Caliburn.Micro Implementations&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;These concepts are implemented in CM through various interfaces and base classes which can be used mostly(1) to build ViewModels. Let&amp;rsquo;s take a look at them:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Screens&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;In Caliburn.Micro we have broken down the notion of screen activation into several interfaces:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;em&gt;IActivate&lt;/em&gt; &amp;ndash; Indicates that the implementer requires activation. This interface provides an &lt;em&gt;Activate&lt;/em&gt; method, an &lt;em&gt;IsActive&lt;/em&gt; property and an &lt;em&gt;Activated&lt;/em&gt; event which should be raised when activation occurs. &lt;/li&gt;
&lt;li&gt;&lt;em&gt;IDeactivate&lt;/em&gt; &amp;ndash; Indicates that the implementer requires deactivation. This interface has a &lt;em&gt;Deactivate&lt;/em&gt; method which takes a &lt;em&gt;bool&lt;/em&gt; property indicating whether to close the screen in addition to deactivating it. It also has two events: &lt;em&gt;AttemptingDeactivation&lt;/em&gt;, which should be raised before deactivation and &lt;em&gt;Deactivated&lt;/em&gt; which should be raised after deactivation. &lt;/li&gt;
&lt;li&gt;&lt;em&gt;IGuardClose&lt;/em&gt; &amp;ndash; Indicates that the implementer may need to cancel a close operation. It has one method: &lt;em&gt;CanClose&lt;/em&gt;. This method is designed with an async pattern, allowing complex logic such as async user interaction to take place while making the close decision. The caller will pass an&lt;em&gt; Action&amp;lt;bool&amp;gt;&lt;/em&gt; to the &lt;em&gt;CanClose&lt;/em&gt; method. The implementer should call the action when guard logic is complete. Pass &lt;em&gt;true&lt;/em&gt; to indicate that the implementer can close, &lt;em&gt;false&lt;/em&gt; otherwise. &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In addition to these core lifecycle interfaces, we have a few others to help in creating consistency between presentation layer classes:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;em&gt;IHaveDisplayName&lt;/em&gt; &amp;ndash; Has a single property called &lt;em&gt;DisplayName&lt;/em&gt; &lt;/li&gt;
&lt;li&gt;&lt;em&gt;INotifyPropertyChangedEx&lt;/em&gt; &amp;ndash; This interface inherits from the standard &lt;em&gt;INotifyPropertyChanged&lt;/em&gt; and augments it with additional behaviors. It adds an &lt;em&gt;IsNotifying&lt;/em&gt; property which can be used to turn off/on all change notification, a &lt;em&gt;NotifyOfPropertyChange&lt;/em&gt; method which can be called to raise a property change and a &lt;em&gt;Refresh&lt;/em&gt; method which can be used to refresh all bindings on the object. &lt;/li&gt;
&lt;li&gt;&lt;em&gt;IObservableCollection&amp;lt;T&amp;gt;&lt;/em&gt; &amp;ndash; Composes the following interfaces: &lt;em&gt;IList&amp;lt;T&amp;gt;&lt;/em&gt;, &lt;em&gt;INotifyPropertyChangedEx&lt;/em&gt; and &lt;em&gt;INotifyCollectionChanged&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;&lt;em&gt;IChild&amp;lt;T&amp;gt;&lt;/em&gt; &amp;ndash; Implemented by elements that are part of a hierarchy or that need a reference to an owner. It has one property named &lt;em&gt;Parent&lt;/em&gt;. &lt;/li&gt;
&lt;li&gt;&lt;em&gt;IViewAware&lt;/em&gt; &amp;ndash; Implemented by classes which need to be made aware of the view that they are bound to. It has an &lt;em&gt;AttachView&lt;/em&gt; method which is called by the framework when it binds the view to the instance. It has a &lt;em&gt;GetView&lt;/em&gt; method which the framework calls before creating a view for the instance. This enables caching of complex views or even complex view resolution logic. Finally, it has an event which should be raised when a view is attached to the instance called &lt;em&gt;ViewAttached&lt;/em&gt;. &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Because certain combinations are so common, we have some convenience interfaces and base classes:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;em&gt;PropertyChangedBase&lt;/em&gt; &amp;ndash; Implements &lt;em&gt;INotifyPropertyChangedEx&lt;/em&gt; (and thus &lt;em&gt;INotifyPropertyChanged&lt;/em&gt;). It provides a lambda-based &lt;em&gt;NotifyOfPropertyChange&lt;/em&gt; method in addition to the standard string mechanism, enabling strongly-typed change notification. Also, all property change events are automatically marshaled to the UI thread.(2)&lt;/li&gt;
&lt;li&gt;&lt;em&gt;BindableCollection&lt;/em&gt; &amp;ndash; Implements&lt;em&gt; IObservableCollection&amp;lt;T&amp;gt;&lt;/em&gt; by inheriting from the standard &lt;em&gt;ObservableCollection&amp;lt;T&amp;gt;&lt;/em&gt; and adding the additional behavior specified by &lt;em&gt;INotifyPropertyChangedEx&lt;/em&gt;. Also, this class ensures that all property change and collection change events occur on the UI thread.(2)&lt;/li&gt;
&lt;li&gt;&lt;em&gt;IScreen&lt;/em&gt; &amp;ndash; This interface composes several other interfaces: &lt;em&gt;IHaveDisplayName&lt;/em&gt;, &lt;em&gt;IActivate&lt;/em&gt;, &lt;em&gt;IDeactivate&lt;/em&gt;, &lt;em&gt;IGuardClose&lt;/em&gt; and &lt;em&gt;INotifyPropertyChangedEx&lt;/em&gt; &lt;/li&gt;
&lt;li&gt;&lt;em&gt;Screen&lt;/em&gt; &amp;ndash; Inherits from &lt;em&gt;PropertyChangedBase&lt;/em&gt; and implements the &lt;em&gt;IScreen&lt;/em&gt; interface. Additionally, &lt;em&gt;IChild&amp;lt;IConductor&amp;gt;&lt;/em&gt; and &lt;em&gt;IViewAware&lt;/em&gt; are implemented. &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;What this all means is that you will probably inherit most of your view models from either &lt;em&gt;PropertyChangedBase&lt;/em&gt; or &lt;em&gt;Screen&lt;/em&gt;. Generally speaking, you would use &lt;em&gt;Screen&lt;/em&gt; if you need any of the activation features and &lt;em&gt;PropertyChangedBase&lt;/em&gt; for everything else. CM&amp;rsquo;s default &lt;em&gt;Screen&lt;/em&gt; implementation has a few additional features as well and makes it easy to hook into the appropriate parts of the lifecycle:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;em&gt;OnInitialize&lt;/em&gt; &amp;ndash; Override this method to add logic which should execute only the first time that the screen is activated. After initialization is complete, &lt;em&gt;IsInitialized&lt;/em&gt; will be &lt;em&gt;true&lt;/em&gt;.&lt;/li&gt;
&lt;li&gt;&lt;em&gt;OnActivate&lt;/em&gt; &amp;ndash; Override this method to add logic which should execute every time the screen is activated. After activation is complete, &lt;em&gt;IsActive&lt;/em&gt; will be &lt;em&gt;true&lt;/em&gt;.&lt;/li&gt;
&lt;li&gt;&lt;em&gt;OnDeactivate&lt;/em&gt; &amp;ndash; Override this method to add custom logic which should be executed whenever the screen is deactivated or closed. The &lt;em&gt;bool&lt;/em&gt; property will indicated if the deactivation is actually a close. After deactivation is complete, &lt;em&gt;IsActive&lt;/em&gt; will be &lt;em&gt;false&lt;/em&gt;.&lt;/li&gt;
&lt;li&gt;&lt;em&gt;CanClose&lt;/em&gt; &amp;ndash; The default implementation always allows closing. Override this method to add custom guard logic.&lt;/li&gt;
&lt;li&gt;&lt;em&gt;OnViewLoaded&lt;/em&gt; &amp;ndash; Since &lt;em&gt;Screen&lt;/em&gt; implements &lt;em&gt;IViewAware&lt;/em&gt;, it takes this as an opportunity to let you know when your view&amp;rsquo;s Loaded event is fired. Use this if you are following a SupervisingController or PassiveView style and you need to work with the view. This is also a place to put view model logic which may be dependent on the presence of a view even though you may not be working with the view directly.&lt;/li&gt;
&lt;li&gt;&lt;em&gt;TryClose&lt;/em&gt; &amp;ndash; Call this method to close the screen. If the screen is being controlled by a &lt;em&gt;Conductor&lt;/em&gt;, it asks the &lt;em&gt;Conductor&lt;/em&gt; to initiate the shutdown process for the &lt;em&gt;Screen&lt;/em&gt;. If the &lt;em&gt;Screen&lt;/em&gt; is not controlled by a &lt;em&gt;Conductor&lt;/em&gt;, but exists independently (perhaps because it was shown using the &lt;em&gt;WindowManager&lt;/em&gt;), this method attempts to close the view. In both scenarios the &lt;em&gt;CanClose&lt;/em&gt; logic will be invoked and if allowed, &lt;em&gt;OnDeactivate&lt;/em&gt; will be called with a value of &lt;em&gt;true&lt;/em&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;So, just to re-iterate: if you need a lifecycle, inherit from &lt;em&gt;Screen&lt;/em&gt;; otherwise inherit from &lt;em&gt;PropertyChangedBase&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Conductors&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;As I mentioned above, once you introduce lifecycle, you need something to enforce it. In Caliburn.Micro, this role is represented by the &lt;em&gt;IConductor&lt;/em&gt; interface which has the following members:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;em&gt;ActiveItem&lt;/em&gt; &amp;ndash; A property that indicates what item the conductor is currently tracking as active.&lt;/li&gt;
&lt;li&gt;&lt;em&gt;GetConductedItems&lt;/em&gt; &amp;ndash; Call this method to return a list of all the items that the conductor is tracking. If the conductor is using a &amp;ldquo;screen collection,&amp;rdquo; this returns all the &amp;ldquo;screens,&amp;rdquo; otherwise this only returns &lt;em&gt;ActiveItem&lt;/em&gt;.&lt;/li&gt;
&lt;li&gt;&lt;em&gt;ActivateItem&lt;/em&gt; &amp;ndash; Call this method to activate a particular item. It will also add it to the currently conducted items if the conductor is using a &amp;ldquo;screen collection.&amp;rdquo;&lt;/li&gt;
&lt;li&gt;&lt;em&gt;CloseItem&lt;/em&gt; &amp;ndash; Call this method to close a particular item. It will also remove it from the currently conducted items if the conductor is using a &amp;ldquo;screen collection.&amp;rdquo;&lt;/li&gt;
&lt;li&gt;&lt;em&gt;ActivationProcessed&lt;/em&gt; &amp;ndash; Raised when the conductor has processed the activation of an item. It indicates whether or not the activation was successful.(3)&lt;/li&gt;
&lt;li&gt;&lt;em&gt;INotifyPropertyChangedEx&lt;/em&gt; &amp;ndash; This interface is composed into &lt;em&gt;IConductor&lt;/em&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;You may have noticed that CM&amp;rsquo;s &lt;em&gt;IConductor&lt;/em&gt; interface uses the term &amp;ldquo;item&amp;rdquo; rather than &amp;ldquo;screen&amp;rdquo; and that I was putting the term &amp;ldquo;screen collection&amp;rdquo; in quotes. The reason for this is that CM&amp;rsquo;s conductor implementations do not require the item being conducted to implement &lt;em&gt;IScreen&lt;/em&gt; or any particular interface. Conducted items can be POCOs. Rather than enforcing the use of &lt;em&gt;IScreen&lt;/em&gt;, each of the conductor implementations is generic, with no constraints on the type. As the conductor is asked to activate/deactivate/close/etc each of the items it is conducting, it checks them individually for the following fine-grained interfaces: &lt;em&gt;IActivate&lt;/em&gt;, &lt;em&gt;IDeactive&lt;/em&gt;, &lt;em&gt;IGuardClose&lt;/em&gt; and &lt;em&gt;IChild&amp;lt;IConductor&amp;gt;. &lt;/em&gt;In practice, I usually inherit conducted items from &lt;em&gt;Screen&lt;/em&gt;, but this gives you the flexibility to use your own base class, or to only implement the interfaces for the lifecycle events you care about on a per-class basis. You can even have a conductor tracking heterogeneous items, some of which inherit from &lt;em&gt;Screen&lt;/em&gt; and others that implement specific interfaces or none at all.&lt;/p&gt;
&lt;p&gt;Out of the box CM has two implementations of &lt;em&gt;IConductor&lt;/em&gt;, one that works with a &amp;ldquo;screen collection&amp;rdquo; and one that does not. We&amp;rsquo;ll look at the conductor without the collection first. &lt;/p&gt;
&lt;p&gt;&lt;em&gt;Conductor&amp;lt;T&amp;gt;&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;This simple conductor implements the majority of &lt;em&gt;IConductor&amp;rsquo;s&lt;/em&gt; members through explicit interface mechanisms and adds strongly typed versions of the same methods which are available publicly. This allows working with conductors generically through the interface as well as in a strongly typed fashion based on the items they are conducting. The &lt;em&gt;Conductor&amp;lt;T&amp;gt;&lt;/em&gt; treats deactivation and closing synonymously. Since the Conductor&amp;lt;T&amp;gt; does not maintain a &amp;ldquo;screen collection,&amp;rdquo; the activation of each new item causes both the deactivation and close of the previously active item. The actual logic for determining whether or not the conducted item can close can be complex due to the async nature of &lt;em&gt;IGuardClose&lt;/em&gt; and the fact that the conducted item may or may not implement this interface.&amp;nbsp; Therefore, the conductor delegates this to an &lt;em&gt;ICloseStrategy&amp;lt;T&amp;gt;&lt;/em&gt; which handles this and tells the conductor the results of the inquiry. Most of the time you&amp;rsquo;ll be fine with the &lt;em&gt;DefaultCloseStrategy&amp;lt;T&amp;gt;&lt;/em&gt; that is provided automatically, but should you need to change things (perhaps &lt;em&gt;IGuardClose&lt;/em&gt; is not sufficient for your purposes) you can set the &lt;em&gt;CloseStrategy&lt;/em&gt; property on &lt;em&gt;Conductor&amp;lt;T&amp;gt;&lt;/em&gt; to your own custom strategy.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Conductor&amp;lt;T&amp;gt;.Collection.OneActive&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;This implementation has all the features of &lt;em&gt;Conductor&amp;lt;T&amp;gt;&lt;/em&gt; but also adds the notion of a &amp;ldquo;screen collection.&amp;rdquo; Since conductors in CM can conduct any type of class, this collection is exposed through an &lt;em&gt;IObservableCollection&amp;lt;T&amp;gt;&lt;/em&gt; called &lt;em&gt;Items&lt;/em&gt; rather than Screens. As a result of the presence of the &lt;em&gt;Items&lt;/em&gt; collection, deactivation and closing of conducted items are not treated synonymously. When a new item is activated, the previous active item is deactivated only and it remains in the &lt;em&gt;Items&lt;/em&gt; collection. To close an item with this conductor, you must explicitly call its &lt;em&gt;CloseItem&lt;/em&gt; method.(4) When an item is closed and that item was the active item, the conductor must then determine which item should be activated next. Be default, this is the item before the previous active item in the list. If you need to change this behavior, you can override &lt;em&gt;DetermineNextItemToActivate&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;There are two very important details about both of CMs &lt;em&gt;IConductor&lt;/em&gt; implementations that I have not mentioned yet. First, they both inherit from &lt;em&gt;Screen&lt;/em&gt;. This is a key feature of these implementations because it creates a composite pattern between screens and conductors. So, let&amp;rsquo;s say you are building a basic navigation-style application. Your shell would be an instance of &lt;em&gt;Conductor&amp;lt;IScreen&amp;gt;&lt;/em&gt; because it shows one &lt;em&gt;Screen&lt;/em&gt; at a time and doesn&amp;rsquo;t maintain a collection. But, let&amp;rsquo;s say that one of those screens was very complicated and needed to have a multi-tabbed interface requiring lifecycle events for each tab. Well, that particular screen could inherit from &lt;em&gt;Conductor&amp;lt;T&amp;gt;.Collection.OneActive&lt;/em&gt;. The shell need not be concerned with the complexity of the individual screen. One of those screens could even be a UserControl that implemented &lt;em&gt;IScreen &lt;/em&gt;instead of a ViewModel if that&amp;rsquo;s what was required. The second important detail is a consequence of the first. Since all OOTB implementations of &lt;em&gt;IConductor&lt;/em&gt; inherit from &lt;em&gt;Screen&lt;/em&gt; it means that they too have a lifecycle and that lifecycle cascades to whatever items they are conducting. So, if a conductor is deactivated, it&amp;rsquo;s &lt;em&gt;ActiveItem&lt;/em&gt; will be deactivated as well. If you try to close a conductor, it&amp;rsquo;s going to only be able to close if all of the items it conducts can close. This turns out to be a very powerful feature. There&amp;rsquo;s one aspect about this that I&amp;rsquo;ve noticed frequently trips up developers. If you activate an item in a conductor that is itself not active, that item won&amp;rsquo;t actually be activated until the conductor gets activated. This makes sense when you think about it, but can occasionally cause hair pulling.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Quasi-Conductors&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Not everything in CM that can be a screen is rooted inside of a Conductor. For example, what about the your root view model? If it&amp;rsquo;s a conductor, who is activating it? Well, that&amp;rsquo;s one of the jobs that the &lt;em&gt;Bootstrapper&lt;/em&gt; performs. The &lt;em&gt;Bootstrapper&lt;/em&gt; itself is not a conductor, but it understands the fine-grained lifecycle interfaces discussed above and ensures that your root view model is treated with the respect it deserves. The &lt;em&gt;WindowManager&lt;/em&gt; works in a similar way(5) by acting a little like a conductor for the purpose of enforcing the lifecycle of your modal (and modeless - WPF only) windows. So, lifecycle isn&amp;rsquo;t magical. All your screens/conductors must be either rooted in a conductor or managed by the &lt;em&gt;Bootstrapper&lt;/em&gt; or &lt;em&gt;WindowManager&lt;/em&gt; to work properly; otherwise you are going to need to manage the lifecycle yourself.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;View-First&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;If you are working with WP7 or using the Silverlight Navigation Framework, you may be wondering if/how you can leverage screens and conductors. So far, I&amp;rsquo;ve been assuming a primarily ViewModel-First approach to shell engineering. But the WP7 platform enforces a View-First approach by controlling page navigation. The same is true of the SL Nav framework. In these cases, the Phone/Nav Framework acts like a conductor. In order to make this play well with ViewModels, the WP7 version of CM has a &lt;em&gt;FrameAdapter&lt;/em&gt; which hooks into the &lt;em&gt;NavigationService&lt;/em&gt;. This adapter, which is set up by the &lt;em&gt;PhoneBootstrapper&lt;/em&gt;, understands the same fine-grained lifecycle interfaces that conductors do and ensures that they are called on your ViewModels at the appropriate points during navigation. You can even cancel the phone&amp;rsquo;s page navigation by implementing &lt;em&gt;IGuardClose&lt;/em&gt; on your ViewModel. While the &lt;em&gt;FrameAdapter&lt;/em&gt; is only part of the WP7 version of CM, it should be easily portable to Silverlight should you wish to use it in conjunction with the Silverlight Navigation Framework.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Ok. That&amp;rsquo;s a ton of theory and API explanation without any samples. Unacceptable. But, I&amp;rsquo;m tired of writing this article. So, you&amp;rsquo;ll just have to wait for the next part. I&amp;rsquo;ve got several screens/conductors samples to show, each one a little more complex (and interesting) than the one before. Stay tuned. It won&amp;rsquo;t be long.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Footnotes&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;1. These classes can also be used very easily to create a SupervisingController or even a PassiveView design if so desired. Normally, using these classes as view models will suffice, but since the base implementations &lt;em&gt;Screen&lt;/em&gt;, &lt;em&gt;Conductor&amp;lt;T&amp;gt;&lt;/em&gt; and &lt;em&gt;Conductor&amp;lt;T&amp;gt;.Collection.OneActive&lt;/em&gt; all implement &lt;em&gt;IViewAware&lt;/em&gt;, it&amp;rsquo;s easy to get a reference to the view and take one of these alternative approaches. Additionally, since all Caliburn.Micro code depends only on the interfaces, you could easily implement &lt;em&gt;IConductor&lt;/em&gt; on top of a docking window manager or some other complex control or service.&lt;/p&gt;
&lt;p&gt;2. Even though these classes do automatic UI thread marshalling, they are still safe to use in a unit test. Under the covers, these classes use CM&amp;rsquo;s &lt;em&gt;Execute.OnUIThread&lt;/em&gt; utility method. This method calls a custom action to do the thread marshalling which is setup by the &lt;em&gt;Bootstrapper&lt;/em&gt;. If you are working with these classes without running the &lt;em&gt;Bootstrapper&lt;/em&gt; (as would be the case with testing), a default action is used which does not do any marshalling.&lt;/p&gt;
&lt;p&gt;3. If activation would cause the closing of the &lt;em&gt;ActiveItem&lt;/em&gt;, such as it would with &lt;em&gt;Conductor&amp;lt;T&amp;gt;,&lt;/em&gt; and the active item&amp;rsquo;s &lt;em&gt;CanClose&lt;/em&gt; returned false, then activation of the new item would not succeed. The current item would remain active.&lt;/p&gt;
&lt;p&gt;4. Or if the item inherits from &lt;em&gt;Screen,&lt;/em&gt; you can call the &lt;em&gt;Screen&amp;rsquo;s&lt;/em&gt; &lt;em&gt;TryClose&lt;/em&gt; method, which actually just calls &lt;em&gt;Parent.CloseItem&lt;/em&gt; passing itself as the item to be closed.&lt;/p&gt;
&lt;p&gt;5. In fact the WPF version of the Bootstrapper uses the WindowManager internally to show your MainWindow. I&amp;rsquo;ll have a whole article on the WindowManager coming soon.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=62714" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/WPF/default.aspx">WPF</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/WPF_2F00_e/default.aspx">WPF/e</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/Caliburn/default.aspx">Caliburn</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/Featured/default.aspx">Featured</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/Silverlight/default.aspx">Silverlight</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/RIA/default.aspx">RIA</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/Tutorial/default.aspx">Tutorial</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/MVVM/default.aspx">MVVM</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/UI+Architecture/default.aspx">UI Architecture</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/Caliburn+Micro/default.aspx">Caliburn Micro</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/WP7/default.aspx">WP7</category></item><item><title>Caliburn.Micro Soup to Nuts Pt. 5 – IResult and Coroutines</title><link>http://devlicio.us/blogs/rob_eisenberg/archive/2010/08/21/caliburn-micro-soup-to-nuts-part-5-iresult-and-coroutines.aspx</link><pubDate>Sat, 21 Aug 2010 18:31:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:61612</guid><dc:creator>Rob Eisenberg</dc:creator><slash:comments>5</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/rob_eisenberg/rsscomments.aspx?PostID=61612</wfw:commentRss><comments>http://devlicio.us/blogs/rob_eisenberg/archive/2010/08/21/caliburn-micro-soup-to-nuts-part-5-iresult-and-coroutines.aspx#comments</comments><description>&lt;p&gt;Before our &lt;a target="_blank" href="http://devlicio.us/blogs/rob_eisenberg/archive/2010/08/07/caliburn-micro-soup-to-nuts-pt-4-working-with-windows-phone-7.aspx"&gt;WP7 detour&lt;/a&gt;, we were deep &lt;a target="_blank" href="http://devlicio.us/blogs/rob_eisenberg/archive/2010/07/17/caliburn-micro-soup-to-nuts-pt-3-all-about-actions.aspx"&gt;in the thick of Actions&lt;/a&gt;. I mentioned that there was one more compelling feature of the Actions concept called Coroutines. If you haven&amp;rsquo;t heard that term before, here&amp;rsquo;s what &lt;a target="_blank" href="http://en.wikipedia.org/wiki/Coroutine"&gt;wikipedia&lt;/a&gt;* has to say:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;In &lt;a href="http://en.wikipedia.org/wiki/Computer_science"&gt;computer science&lt;/a&gt;, &lt;strong&gt;coroutines&lt;/strong&gt; are program components that generalize &lt;a href="http://en.wikipedia.org/wiki/Subroutine"&gt;subroutines&lt;/a&gt; to allow multiple entry points for suspending and resuming execution at certain locations. Coroutines are well-suited for implementing more familiar program components such as &lt;a href="http://en.wikipedia.org/wiki/Cooperative_multitasking"&gt;cooperative tasks&lt;/a&gt;, &lt;a href="http://en.wikipedia.org/wiki/Iterator"&gt;iterators&lt;/a&gt;,&lt;a href="http://en.wikipedia.org/wiki/Lazy_evaluation"&gt;infinite lists&lt;/a&gt; and &lt;a href="http://en.wikipedia.org/wiki/Pipeline_(software)"&gt;pipes&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Here&amp;rsquo;s one way you can thing about it: Imagine being able to execute a method, then pause it&amp;rsquo;s execution on some statement, go do something else, then come back and resume execution where you left off. This technique is extremely powerful in task-based programming, especially when those tasks need to run asynchronously. For example, let&amp;rsquo;s say we have a ViewModel that needs to call a web service asynchronously, then it needs to take the results of that, do some work on it and call another web service asynchronously. Finally, it must then display the result in a modal dialog and respond to the user&amp;rsquo;s dialog selection with another asynchronous task. Accomplishing this with the standard event-driven async model is not a pleasant experience. However, this is a simple task to accomplish by using coroutines. The problem&amp;hellip;C# doesn&amp;rsquo;t implement coroutines natively. Fortunately, we can (sort of) build them on top of iterators.&lt;/p&gt;
&lt;p&gt;There are two things necessary to take advantage of this feature in Caliburn.Micro: First, implement the IResult interface on some class, representing the task you wish to execute; Second, yield instances of IResult from an Action.** Let&amp;rsquo;s make this more concrete. Say we had a Silverlight application where we wanted to dynamically download and show screens not part of the main package. First we would probably want to show a &amp;ldquo;Loading&amp;rdquo; indicator, then asynchronously download the external package, next hide the &amp;ldquo;Loading&amp;rdquo; indicator and finally navigate to a particular screen inside the dynamic module. Here&amp;rsquo;s what the code would look like if your first screen wanted to use coroutines to navigate to a dynamically loaded second screen:&lt;/p&gt;
&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;using System.Collections.Generic;
using System.ComponentModel.Composition;

[Export(typeof(ScreenOneViewModel))]
public class ScreenOneViewModel
{
    public IEnumerable&amp;lt;IResult&amp;gt; GoForward()
    {
        yield return Loader.Show(&amp;quot;Downloading...&amp;quot;);
        yield return new LoadCatalog(&amp;quot;Caliburn.Micro.Coroutines.External.xap&amp;quot;);
        yield return Loader.Hide();
        yield return new ShowScreen(&amp;quot;ExternalScreen&amp;quot;);
    }
}&lt;/pre&gt;
&lt;p&gt;First, notice that the Action &amp;ldquo;GoForward&amp;rdquo; has a return type of IEnumerable&amp;lt;IResult&amp;gt;. This is critical for using coroutines. The body of the method has four yield statements. Each of these yields is returning an instance of IResult. The first is a result to show the &amp;ldquo;Downloading&amp;rdquo; indicator, the second to download the xap asynchronously, the third to hide the &amp;ldquo;Downloading&amp;rdquo; message and the fourth to show a new screen from the downloaded xap.&amp;nbsp; After each yield statement, the compiler will &amp;ldquo;pause&amp;rdquo; the execution of this method until that particular task completes. The first, third and fourth tasks are synchronous, while the second is asynchronous.&amp;nbsp; But the yield syntax allows you to write all the code in a sequential fashion, preserving the original workflow as a much more readable and declarative structure. To understand a bit more how this works, have a look at the IResult interface:&lt;/p&gt;
&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;public interface IResult
{
    void Execute(ActionExecutionContext context);
    event EventHandler&amp;lt;ResultCompletionEventArgs&amp;gt; Completed;
}&lt;/pre&gt;
&lt;p&gt;It&amp;rsquo;s a fairly simple interface to implement. Simply write your code in the &amp;ldquo;Execute&amp;rdquo; method and be sure to raise the &amp;ldquo;Completed&amp;rdquo; event when you are done, whether it be a synchronous or an asynchronous task. Because coroutines occur inside of an Action, we provide you with an ActionExecutionContext useful in building UI-related IResult implementations. This allows the ViewModel a way to declaratively state it intentions in controlling the view without having any reference to a View or the need for interaction-based unit testing. Here&amp;rsquo;s what the ActionResultContext looks like:&lt;/p&gt;
&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;public class ActionExecutionContext
{
    public ActionMessage Message;
    public FrameworkElement Source;
    public object EventArgs;
    public object Target;
    public DependencyObject View;
    public MethodInfo Method;
    public Func&amp;lt;bool&amp;gt; CanExecute;
    public object this[string key];
}&lt;/pre&gt;
&lt;p&gt;And here&amp;rsquo;s an explanation of what all these properties mean:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Message &amp;ndash; The original ActionMessage that caused the invocation of this IResult.&lt;/li&gt;
&lt;li&gt;Source &amp;ndash; The FrameworkElement that triggered the execution of the Action.&lt;/li&gt;
&lt;li&gt;EventArgs &amp;ndash; Any event arguments associated with the trigger of the Action.&lt;/li&gt;
&lt;li&gt;Target &amp;ndash; The class instance on which the actual Action method exists.&lt;/li&gt;
&lt;li&gt;View &amp;ndash; The view associated with the Target.&lt;/li&gt;
&lt;li&gt;Method &amp;ndash; The MethodInfo specifying which method to invoke on the Target instance.&lt;/li&gt;
&lt;li&gt;CanExecute &amp;ndash; A function that returns true if the Action can be invoked, false otherwise.&lt;/li&gt;
&lt;li&gt;Key Index: A place to store/retrieve any additional metadata which may be used by extensions to the framework.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Bearing that in mind, I wrote a naive Loader IResult that searches the VisualTree looking for the first instance of a BusyIndicator to use to display a loading message. Here&amp;rsquo;s the implementation:&lt;/p&gt;
&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;using System;
using System.Windows;
using System.Windows.Controls;

public class Loader : IResult
{
    readonly string message;
    readonly bool hide;

    public Loader(string message)
    {
        this.message = message;
    }

    public Loader(bool hide)
    {
        this.hide = hide;
    }

    public void Execute(ActionExecutionContext context)
    {
        var view = context.View as FrameworkElement;
        while(view != null)
        {
            var busyIndicator = view as BusyIndicator;
            if(busyIndicator != null)
            {
                if(!string.IsNullOrEmpty(message))
                    busyIndicator.BusyContent = message;
                busyIndicator.IsBusy = !hide;
                break;
            }

            view = view.Parent as FrameworkElement;
        }

        Completed(this, new ResultCompletionEventArgs());
    }

    public event EventHandler&amp;lt;ResultCompletionEventArgs&amp;gt; Completed = delegate { };

    public static IResult Show(string message = null)
    {
        return new Loader(message);
    }

    public static IResult Hide()
    {
        return new Loader(true);
    }
}&lt;/pre&gt;
&lt;p&gt;See how I took advantage of context.View? This opens up a lot of possibilities while maintaining separation between the view and the view model. Just to list a few interesting things you could do with IResult implementations: show a message box, show a VM-based modal dialog, show a VM-based Popup at the user&amp;rsquo;s mouse position, play an animation, show File Save/Load dialogs, place focus on a particular UI element based on VM properties rather than controls, etc. Of coarse, one of the biggest opportunities is calling web services. Let&amp;rsquo;s look at how you might do that, but by using a slightly different scenario, dynamically downloading a xap:&lt;/p&gt;
&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.ReflectionModel;
using System.Linq;

public class LoadCatalog : IResult
{
    static readonly Dictionary&amp;lt;string, DeploymentCatalog&amp;gt; Catalogs = new Dictionary&amp;lt;string, DeploymentCatalog&amp;gt;();
    readonly string uri;

    [Import]
    public AggregateCatalog Catalog { get; set; }

    public LoadCatalog(string relativeUri)
    {
        uri = relativeUri;
    }

    public void Execute(ActionExecutionContext context)
    {
        DeploymentCatalog catalog;

        if(Catalogs.TryGetValue(uri, out catalog))
            Completed(this, new ResultCompletionEventArgs());
        else
        {
            catalog = new DeploymentCatalog(uri);
            catalog.DownloadCompleted += (s, e) =&amp;gt;{
                if(e.Error == null)
                {
                    Catalogs[uri] = catalog;
                    Catalog.Catalogs.Add(catalog);
                    catalog.Parts
                        .Select(part =&amp;gt; ReflectionModelServices.GetPartType(part).Value.Assembly)
                        .Where(assembly =&amp;gt; !AssemblySource.Instance.Contains(assembly))
                        .Apply(x =&amp;gt; AssemblySource.Instance.Add(x));
                }
                else Loader.Hide().Execute(context);

                Completed(this, new ResultCompletionEventArgs {
                    Error = e.Error,
                    WasCancelled = false
                });
            };

            catalog.DownloadAsync();
        }
    }

    public event EventHandler&amp;lt;ResultCompletionEventArgs&amp;gt; Completed = delegate { };
}&lt;/pre&gt;
&lt;p&gt;In case it wasn&amp;rsquo;t clear, this sample is using MEF. Furthermore, we are taking advantage of the DeploymentCatalog created for Silverlight 4.&amp;nbsp; You don&amp;rsquo;t really need to know a lot about MEF or DeploymentCatalog to get the takeaway. Just take note of the fact that we wire for the DownloadCompleted event and make sure to fire the IResult.Completed event in its handler. This is what enables the async pattern to work. We also make sure to check the error and pass that along in the ResultCompletionEventArgs. Speaking of that, here&amp;rsquo;s what that class looks like:&lt;/p&gt;
&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;public class ResultCompletionEventArgs : EventArgs
{
    public Exception Error;
    public bool WasCancelled;
}&lt;/pre&gt;
&lt;p&gt;Caliburn.Micro&amp;rsquo;s enumerator checks these properties after it get&amp;rsquo;s called back from each IResult. If there is either an error or WasCancelled is set to true, we stop execution. You can use this to your advantage. Let&amp;rsquo;s say you create an IResult for the OpenFileDialog. You could check the result of that dialog, and if the user canceled it, set WasCancelled on the event args. By doing this, you can write an action that assumes that if the code following the Dialog.Show executes, the user must have selected a file. This sort of technique can simplify the logic in such situations. Obviously, you could use the same technique for the SaveFileDialog or any confirmation style message box if you so desired. My favorite part of the LoadCatalog implementation shown above, is that the original implementation was written by a CM user! Thanks janoveh for this awesome submission! As a side note, one of the things we added to the CM project site is &lt;a target="_blank" href="http://caliburnmicro.codeplex.com/documentation"&gt;a &amp;ldquo;Recipes&amp;rdquo; section&lt;/a&gt;. We are going to be adding more common solutions such as this to that area in the coming months. So, it will be a great place to check for cool plugins and customizations to the framework.***&lt;/p&gt;
&lt;p&gt;Another thing you can do is create a series of IResult implementations built around your application&amp;rsquo;s shell. That is what the ShowScreen result used above does. Here is its implementation:&lt;/p&gt;
&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;using System;
using System.ComponentModel.Composition;

public class ShowScreen : IResult
{
    readonly Type screenType;
    readonly string name;

    [Import]
    public IShell Shell { get; set; }

    public ShowScreen(string name)
    {
        this.name = name;
    }

    public ShowScreen(Type screenType)
    {
        this.screenType = screenType;
    }

    public void Execute(ActionExecutionContext context)
    {
        var screen = !string.IsNullOrEmpty(name)
            ? IoC.Get&amp;lt;object&amp;gt;(name)
            : IoC.GetInstance(screenType, null);

        Shell.ActivateItem(screen);
        Completed(this, new ResultCompletionEventArgs());
    }

    public event EventHandler&amp;lt;ResultCompletionEventArgs&amp;gt; Completed = delegate { };

    public static ShowScreen Of&amp;lt;T&amp;gt;()
    {
        return new ShowScreen(typeof(T));
    }
}&lt;/pre&gt;
&lt;p&gt;This bring up another important feature of IResult. Before CM executes a result, it passes it through the IoC.BuildUp method allowing your container the opportunity to push dependencies in through the properties. This allows you to create them normally within your view models, while still allowing them to take dependencies on application services. In this case, we depend on IShell. You could also have your container injected, but in this case I chose to use the IoC static class internally. As a general rule, you should avoid pulling things from the container directly. However, I think it is acceptable when done inside of infrastructure code such as a ShowScreen IResult.&lt;/p&gt;
&lt;p&gt;I hope this gives some explanation and creative ideas for what can be accomplished with IResult. Be sure to check out the sample application attached. There&amp;rsquo;s a few other interesting things in there as well.&lt;/p&gt;
&lt;p&gt;* When I went to look up the &amp;ldquo;official&amp;rdquo; definition on wikipedia I was interested to see what it had to say about implementations in various languages. Scrolling down to the section on C#&amp;hellip;Caliburn was listed! Fun stuff. &lt;/p&gt;
&lt;p&gt;** You can also return a single instance of IResult without using IEnuermable&amp;lt;IResult&amp;gt; if you just want a simple way to execute a single task.&lt;/p&gt;
&lt;p&gt;*** If you want a sample of a truly awesome plugin we will be adding to the recipes section soon, &lt;a target="_blank" href="http://marcoamendola.wordpress.com/2010/08/10/a-caliburn-micro-recipe-filters/"&gt;check this out!&lt;/a&gt;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=61612" width="1" height="1"&gt;</description><enclosure url="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Components.PostAttachments/00.00.06.16.12/Caliburn.Micro.Coroutines.zip" length="26128" type="application/x-zip-compressed" /><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/WPF/default.aspx">WPF</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/WPF_2F00_e/default.aspx">WPF/e</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/Caliburn/default.aspx">Caliburn</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/Featured/default.aspx">Featured</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/Silverlight/default.aspx">Silverlight</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/DSL/default.aspx">DSL</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/RIA/default.aspx">RIA</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/Tutorial/default.aspx">Tutorial</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/MEF/default.aspx">MEF</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/MVVM/default.aspx">MVVM</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/UI+Architecture/default.aspx">UI Architecture</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/Caliburn+Micro/default.aspx">Caliburn Micro</category><category domain="http://devlicio.us/blogs/rob_eisenberg/archive/tags/WP7/default.aspx">WP7</category></item></channel></rss>