<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
    <channel>
        <title>MVVM - SeeSharp</title>
        <description>A C# development blog</description>
        <link>/Tags/MVVM/RSS</link>
        <language>en</language>
        <image>
            <url>http://www.hightech.ir/favicon.png</url>
            <title>SeeSharp</title>
            <link>/Tags/MVVM/RSS</link>
            <width>64</width>
            <height>64</height>
        </image>
        <item>
            <dc:creator>HEskandari</dc:creator>
            <title>WPF Application with Caliburn - Part Three</title>
            <description>&lt;p&gt;
	This is the 3rd part of the serie where in &lt;a href=&quot;http://www.hightech.ir/SeeSharp/WPF-Application-With-Caliburn-Part-Two&quot;&gt;previous&lt;/a&gt; post we saw how to develop WPF applications using Caliburn Framework. In this post, we&amp;#39;ll see some more advanced usage where our shell instead of being just limited to displaying single view at a time, can have multiple ones in a Tabbed user interface.&lt;/p&gt;
&lt;p&gt;
	&lt;em&gt;Note: I&amp;#39;m still using v1.1 of &lt;a href=&quot;http://caliburnproject.org/&quot;&gt;Caliburn framework&lt;/a&gt;. In this version naming are more toward &lt;a href=&quot;http://msdn.microsoft.com/en-us/magazine/cc188690.aspx&quot;&gt;MVP&lt;/a&gt; pattern but the framework can be used to implement WPF and Silverlight applications in both &lt;a href=&quot;http://en.wikipedia.org/wiki/Model-view-presenter&quot;&gt;MVP&lt;/a&gt; and &lt;a href=&quot;http://en.wikipedia.org/wiki/Model_View_ViewModel&quot;&gt;MVVM&lt;/a&gt; patterns. Next version of Caliburn will have better namings that are not design pattern specific. If you are using later versions of the framework, classes may have quite different namings.&lt;br /&gt;
	&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;
	&lt;span class=&quot;subtitle&quot;&gt;Basic Shell&lt;/span&gt;&lt;br /&gt;
	To recap, creating a basic shell in WPF using MVVM pattern that benefits Caliburn framework was fairly simple. You needed to create a View which is basically a UserControl for the shell and place a &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.windows.controls.contentcontrol.aspx&quot;&gt;ContentControl&lt;/a&gt; in it which will be the placeholder for other views to open in. For the ViewModel part, there was a couple of base class to choose from but so far we&amp;#39;ve used &lt;a href=&quot;http://caliburn.codeplex.com/wikipage?title=IPresenter%20Component%20Model&quot;&gt;PresenterManager&lt;/a&gt; which can host and display single &amp;quot;Presenter&amp;quot;.&lt;/p&gt;
&lt;pre class=&quot;brush:xml&quot;&gt;
&amp;lt;UserControl x:Class=&amp;quot;iSales.Views.ShellView&amp;quot;&amp;gt;
    &amp;lt;DockPanel LastChildFill=&amp;quot;True&amp;quot;&amp;gt;
	
        &amp;lt;ToolBar DockPanel.Dock=&amp;quot;Top&amp;quot;&amp;gt;
            &amp;lt;Button cal:Message.Attach=&amp;quot;[Event Click] = [Action ShowCustomers]&amp;quot; Content=&amp;quot;Customers&amp;quot; /&amp;gt;
            &amp;lt;Button cal:Message.Attach=&amp;quot;[Event Click] = [Action ShowOrders]&amp;quot; Content=&amp;quot;Orders&amp;quot; /&amp;gt;
        &amp;lt;/ToolBar&amp;gt;

        &amp;lt;ContentControl cal:View.Model=&amp;quot;{Binding CurrentPresenter}&amp;quot; /&amp;gt;
		
    &amp;lt;/DockPanel&amp;gt;
&amp;lt;/UserControl&amp;gt;

&lt;/pre&gt;
&lt;p&gt;
	&lt;span class=&quot;subtitle&quot;&gt;Tabbed Interface&lt;/span&gt;&lt;br /&gt;
	Let&amp;#39;s create a more sophesticate UI that allows us host multiple views at the same time. You may know that it is originally not possible to do MDI interface in WPF (there were community implementations though) however it would be possible to achieve similar results using a TabControl.&lt;/p&gt;
&lt;p&gt;
	To convert our single-view to a tabbed-view there are two things to do. First we should change the base class of our ShellViewModel to &amp;quot;MultiPresenterManager&amp;quot; instead of &amp;quot;PresenterManager&amp;quot;, then we need to change the UI part (ShellView) to host a collection of &amp;quot;IPresenters&amp;quot; in a tabbed interface. To change the UI, remove the ContentControl and add a TabControl with its ItemsSource bound to &amp;quot;Presenters&amp;quot; property and SelectedItem bound to &amp;quot;CurrentPresenter&amp;quot; property. So far it all comes down to one line of code change on the UI:&lt;/p&gt;
&lt;pre class=&quot;brush:csharp&quot;&gt;
&amp;lt;TabControl ItemsSource=&amp;quot;{Binding Presenters}&amp;quot; SelectedItem=&amp;quot;{Binding Path=CurrentPresenter}&amp;quot; /&amp;gt;

&lt;/pre&gt;
&lt;p style=&quot;text-align: center;&quot;&gt;
	&lt;img alt=&quot;Initial Tabbed View&quot; src=&quot;http://www.hightech.ir/Images/BlogPics/Caliburn_PartThree_InitialTabbedView.png&quot; style=&quot;width: 516px; height: 338px;&quot; /&gt;&lt;/p&gt;
&lt;p&gt;
	As you can see the picture above, it is not what we expected, or is it? You may have guessed what is missing. We need to provide two things to the TabControl: A template for Header part where tab item&amp;#39;s header will be displayed, and another template for the content part of the tab item where our view will be displayed. For the header part, Caliburn already has a property named &amp;quot;DisplayName&amp;quot; which is designed to do just that.&lt;/p&gt;
&lt;pre class=&quot;brush:xml&quot;&gt;
&amp;lt;TabControl ItemsSource=&amp;quot;{Binding Presenters}&amp;quot; 
            SelectedItem=&amp;quot;{Binding Path=CurrentPresenter}&amp;quot;&amp;gt;
	
    &amp;lt;TabControl.ItemTemplate&amp;gt;
        &amp;lt;DataTemplate&amp;gt;
            &amp;lt;ContentControl Content=&amp;quot;{Binding DisplayName}&amp;quot;/&amp;gt;
        &amp;lt;/DataTemplate&amp;gt;
    &amp;lt;/TabControl.ItemTemplate&amp;gt;
	
    &amp;lt;TabControl.ContentTemplate&amp;gt;
        &amp;lt;DataTemplate&amp;gt;
            &amp;lt;ContentControl cal:View.Model=&amp;quot;{Binding}&amp;quot; /&amp;gt;
        &amp;lt;/DataTemplate&amp;gt;
    &amp;lt;/TabControl.ContentTemplate&amp;gt;
	
&amp;lt;/TabControl&amp;gt;
&lt;/pre&gt;
&lt;p&gt;
	The result is a more elegant user interface and our tab control displays and hosts our presenters correctly.&lt;/p&gt;
&lt;p style=&quot;text-align: center;&quot;&gt;
	&lt;img alt=&quot;Tabbed View&quot; src=&quot;http://www.hightech.ir/Images/BlogPics/Caliburn_PartThree_WorkingTabbedView.png&quot; style=&quot;width: 516px; height: 338px;&quot; /&gt;&lt;/p&gt;
&lt;p&gt;
	&lt;span class=&quot;subtitle&quot;&gt;Closing Tabs&lt;/span&gt;&lt;br /&gt;
	If you have noticed, one piece of the puzzle is still missing. How do we close a view once we have opened it? Let&amp;#39;s retemplate our ItemTemplate in the TabControl and add button with a glyph that will close the Presenter once clicked. First let&amp;#39;s add a method in our ShellView to close the passed presenter.&lt;/p&gt;
&lt;pre class=&quot;brush:csharp&quot;&gt;
using Caliburn.PresentationFramework.ApplicationModel;

public class ShellViewModel : MultiPresenterManager, IShellViewModel
{
    public void ShutdownPresenter(IPresenter presenter)
    {
        this.Shutdown(presenter);
    }
}
&lt;/pre&gt;
&lt;p&gt;
	Notice the &amp;quot;Using&amp;quot; keyword. There is an extension method for shutdown so we&amp;#39;re importing the extension method with using keyword and just pass the presenter to be shutdown. Here&amp;#39;s our complete new template:&lt;/p&gt;
&lt;pre class=&quot;brush:xml&quot;&gt;
&amp;lt;DataTemplate&amp;gt;
    &amp;lt;ContentControl&amp;gt;
        &amp;lt;DockPanel&amp;gt;
            &amp;lt;Button Style=&amp;quot;{StaticResource {x:Static ToolBar.ButtonStyleKey}}&amp;quot; 
                Visibility=&amp;quot;{Binding CanShutdown, Mode=TwoWay, Converter={StaticResource VisibilityConverter}}&amp;quot;
                cal:Message.Attach=&amp;quot;[Event Click] = [Action ShutdownPresenter($datacontext)]&amp;quot;
		DockPanel.Dock=&amp;quot;Right&amp;quot;&amp;gt;
                    &amp;lt;Path Stretch=&amp;quot;Fill&amp;quot; StrokeThickness=&amp;quot;0.5&amp;quot; 
                          Stroke=&amp;quot;#FF333333&amp;quot; Fill=&amp;quot;#FF969696&amp;quot; 
                          Data=&amp;quot;F1 M 2.28484e-007,1.33331L 1.33333,0L 4.00001,2.66669L 6.66667,6.10352e-005L 8,1.33331L 5.33334,4L 8,6.66669L 6.66667,8L 4,5.33331L 1.33333,8L 1.086e-007,6.66669L 2.66667,4L 2.28484e-007,1.33331 Z &amp;quot; 
                          HorizontalAlignment=&amp;quot;Stretch&amp;quot; 
                          VerticalAlignment=&amp;quot;Stretch&amp;quot;/&amp;gt;
            &amp;lt;/Button&amp;gt;
            &amp;lt;TextBlock Text=&amp;quot;{Binding DisplayName}&amp;quot; /&amp;gt;
        &amp;lt;/DockPanel&amp;gt;
    &amp;lt;/ContentControl&amp;gt;
&amp;lt;/DataTemplate&amp;gt;
&lt;/pre&gt;
&lt;p&gt;
	Did you see the part where we are attaching a Message to the Click event of the button? In Caliburn you can attach a method of your ViewModel to the UI element. What&amp;#39;s cool about it (well there are many cool things about it) is that you can even pass the DataContext around and Caliburn will do the necessary casting for you so in our case, DataContext of the Button will be cast as an IPresenter and will be injected to the method when user clicks on the close button.&lt;/p&gt;
&lt;p style=&quot;text-align: center;&quot;&gt;
	&lt;img alt=&quot;Final Outcome&quot; src=&quot;http://www.hightech.ir/Images/BlogPics/Caliburn_PartThree_ElegantTabbedInterface.png&quot; style=&quot;width: 516px; height: 338px;&quot; /&gt;&lt;/p&gt;
&lt;p&gt;
	One thing that you may experience when closing the Shell view (Main Window), is that by doing so, shell will give all the open presenters a chance to clean up and close gracefully. In case a presenter is not in a closeable state, the close operation on the entire application will be cancelled.&lt;/p&gt;
&lt;p&gt;
	That&amp;#39; all there is to it. Now we have an elegant tabbed UI where user can open and close each tab separately. You can grab the source code of this part from &lt;a href=&quot;http://www.hightech.ir/Files/Tabbed-Interface-With-Caliburn.zip&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;</description>
            <link>http://www.hightech.ir/SeeSharp/WPF-Applications-with-Caliburn-Part-Three</link>
            <guid isPermaLink="true">http://www.hightech.ir/SeeSharp/WPF-Applications-with-Caliburn-Part-Three</guid>
            <pubDate>Tue, 22 Jun 2010 00:00:00 GMT</pubDate>
            <category>MVVM</category>
            <category>WPF</category>
            <category>Caliburn</category>
        </item>
        <item>
            <dc:creator>HEskandari</dc:creator>
            <title>Best implementation of INotifyPropertyChange ever</title>
            <description>&lt;p&gt;
	Back in May 2008, I found a way to use Linq expression to fire notification change, and just after that on &lt;a href=&quot;http://www.hightech.ir/SeeSharp/enhanced-inotifypropertychanged-revisited&quot;&gt;September 2008&lt;/a&gt;, changing the &lt;a href=&quot;http://www.hightech.ir/SeeSharp/enhanced-inotifypropertychanged&quot;&gt;first implementation&lt;/a&gt; to benefit extension methods, things looked a lot easier and more C# 3.0 style. But now to think of it, the best implementation of &lt;a href=&quot;http://www.google.com/url?q=http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx&amp;amp;sa=U&amp;amp;ei=mXXVS8TwLIT3-AbfjuGxDA&amp;amp;ct=res&amp;amp;ved=0CAcQFjAA&amp;amp;cd=1&amp;amp;usg=AFQjCNHFxI3k_ut-K6-b2iWg6nkRiwXSNg&quot;&gt;INotifyPropertyChange&lt;/a&gt; would be not to implement it at all! Is this possible?&lt;br /&gt;
	&lt;br /&gt;
	If you&amp;#39;re a &lt;a href=&quot;http://www.google.com/url?q=http://en.wikipedia.org/wiki/Windows_Presentation_Foundation&amp;amp;sa=U&amp;amp;ei=qXXVS9HTJsGz-Qa_yuSYDA&amp;amp;ct=res&amp;amp;ved=0CAUQFjAA&amp;amp;cd=1&amp;amp;usg=AFQjCNHliurH1B4lFJQQC_dzrKY36ScNFA&quot;&gt;WPF&lt;/a&gt; or &lt;a href=&quot;http://www.google.com/url?q=http://en.wikipedia.org/wiki/Microsoft_Silverlight&amp;amp;sa=U&amp;amp;ei=tXXVS9XOCIHz-QbUkviiDA&amp;amp;ct=res&amp;amp;ved=0CB4QFjAE&amp;amp;cd=5&amp;amp;usg=AFQjCNEe44N0AYDM5y0loXJtoj5GrUmVMA&quot;&gt;Silverlight&lt;/a&gt; programmer, you probably aready know that to make data binding work on simple &lt;a href=&quot;http://www.google.com/url?q=http://en.wikipedia.org/wiki/Plain_Old_CLR_Object&amp;amp;sa=U&amp;amp;ei=ynXVS6f3B9jV-QbhvMi_DA&amp;amp;ct=res&amp;amp;ved=0CBcQFjAC&amp;amp;cd=3&amp;amp;usg=AFQjCNFDnbTNaT28Q5WpEb3ATAphgjKTww&quot;&gt;POCO&lt;/a&gt; objects, you need to implement INotifyPropertyChange interface on your POCO class. This is a trivial interface which has a public event. When property value changes, it is your job to notify interested parties about this change and WPF / SL engine is one of the interested parties and will update the UIElement that is bound to that property automatically. How to do that is actually easy too, but a lot of repetitive boiler-plate code should be written:&lt;/p&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public class Customer
{
}

public class CustomerViewModel : INotifyPropertyChanged
{
    private Customer _currentCustomer;
    public virtual Customer CurrentCustomer
    {
        get { return _currentCustomer; }
        set
        {
            _currentCustomer = value;
            RaisePropertyChanged(&amp;quot;CurrentCustomer&amp;quot;);
        }
    }

    private void RaisePropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if(handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    
    public event PropertyChangedEventHandler PropertyChanged;
}
&lt;/pre&gt;
&lt;p&gt;
	Yuck! Even using LINQ and Extension methods just changes the untyped property name to its typed equivalent but the amount of code written hardly changes.&lt;br /&gt;
	&lt;br /&gt;
	Let&amp;#39;s see how we can just create an automatic property and make it notify the property change event, without doing all these stuff. In short, let us see how to make this red test turn green:&lt;/p&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
[TestFixture]
public class AutomaticNotificationFixture
{
    [Test]
    public void Notification_Change_Is_Added_Automatically()
    {
        var vm = new CustomerViewModel();

        var notification = vm as INotifyPropertyChanged;

        Assert.That(notification, Is.Not.Null);
    }

    [Test]
    public void Can_Notify_Automatically()
    {
        var vm = new CustomerViewModel();
        string changedProperty = null;

        ((INotifyPropertyChanged) vm).PropertyChanged += (s, e) =&amp;gt; changedProperty = e.PropertyName;
        vm.CurrentCustomer = new Customer();

        Assert.That(changedProperty, Is.Not.Null);
        Assert.That(changedProperty, Is.EqualTo(&amp;quot;CurrentCustomer&amp;quot;));
    }

    public class Customer
    {
    }

    public class CustomerViewModel
    {
        public virtual Customer CurrentCustomer
        {
            get; set;
        }
    }
}
&lt;/pre&gt;
&lt;p&gt;
	Not possible at first look, eh? If you&amp;#39;re familiar with DynamicProxy tools, you can well see the perfect usage here. In short, using a dynamic proxy library, we could implement an interface on our type at runtime, so we could inject the INotifyPropertyChange behavior into our ViewModel here. This is a pretty powerful toy which allows you any kind of behavior into your objects with minimal effort.&lt;/p&gt;
&lt;p&gt;
	Let&amp;#39;s create a ViewModelFactory for ourselves that just does that:&lt;/p&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public class ViewModelFactory
{
    private static readonly ProxyGenerator ProxyGenerator = new ProxyGenerator();

    public static T Create&amp;lt;T&amp;gt;()
    {
        return (T)Create(typeof(T));
    }

    public static object Create(Type type)
    {
        return ProxyGenerator.CreateClassProxy(type, new[]
        {
            typeof(INotifyPropertyChanged), 
        }, 
        new NotifyPropertyChangedInterceptor());
    }
}
&lt;/pre&gt;
&lt;p&gt;
	We need to create an Interceptor for our behavior too. Interceptor as the name implies, will be called on our class at runtime and gives us a chance to run a piece of code before and / or after a call is made on our object.&lt;/p&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public class NotifyPropertyChangedInterceptor : IInterceptor
{
    private PropertyChangedEventHandler _subscribers = delegate { };

    public void Intercept(IInvocation invocation)
    {
        if (invocation.Method.DeclaringType == typeof(INotifyPropertyChanged))
        {
            HandleSubscription(invocation);
            return;
        }

        invocation.Proceed();

        if (invocation.Method.Name.StartsWith(&amp;quot;set_&amp;quot;))
        {
            FireNotificationChanged(invocation);
        }
    }

    private void HandleSubscription(IInvocation invocation)
    {
        var handler = (PropertyChangedEventHandler)invocation.Arguments[0];

        if (invocation.Method.Name.StartsWith(&amp;quot;add_&amp;quot;))
        {
            _subscribers += handler;
        }
        else
        {
            _subscribers -= handler;
        }
    }

    private void FireNotificationChanged(IInvocation invocation)
    {
        var propertyName = invocation.Method.Name.Substring(4);
        _subscribers(invocation.InvocationTarget, new PropertyChangedEventArgs(propertyName));
    }
}
&lt;/pre&gt;
&lt;p&gt;
	As you can see, the IInvocation interface contains the method that is being executed so we can see if it is an event subscription, a property getter/setter or a method call and act respectivly.&lt;/p&gt;
&lt;p&gt;
	Now we only need to create our ViewModel classes via our factory so let&amp;#39;s refactor our test code to this and see the tests pass.&lt;/p&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
var vm = ViewModelFactory.Create&amp;lt;CustomerViewModel&amp;gt;();
&lt;/pre&gt;
&lt;p&gt;
	How does this fit to your application? It goes without saying that you can not create instances of your ViewModels and need to get new instances via this factory, but if you&amp;#39;re using a presentation framework like &lt;a href=&quot;http://caliburn.codeplex.com/&quot;&gt;Caluburn&lt;/a&gt;, or using dependency injection containers like &lt;a href=&quot;http://www.google.com/url?q=http://www.castleproject.org/container/&amp;amp;sa=U&amp;amp;ei=BYTVS6_NE4yWrAeB3LjrDQ&amp;amp;ct=res&amp;amp;ved=0CAUQFjAA&amp;amp;cd=1&amp;amp;usg=AFQjCNG4nyBoKjwZyNbBHfyXV4r_WwYqxQ&quot;&gt;Windsor&lt;/a&gt; to resolve your VMs, you&amp;#39;ll feel right at home.&lt;/p&gt;
&lt;p&gt;
	So, what&amp;#39;s the catch? There&amp;#39;s always a catch, you might ask? There&amp;#39;s no catch seriously. Well, now that you insist, there is just one point. To be able to do so, you need to make your properties &amp;quot;virtual&amp;quot; as the sample above. I don&amp;#39;t consider this a &amp;quot;catch&amp;quot; since making your public API virtual is considered a good thing for many reasons and you probably do that anyway.&lt;/p&gt;</description>
            <link>http://www.hightech.ir/SeeSharp/Best-Implementation-Of-INotifyPropertyChange-Ever</link>
            <guid isPermaLink="true">http://www.hightech.ir/SeeSharp/Best-Implementation-Of-INotifyPropertyChange-Ever</guid>
            <pubDate>Mon, 26 Apr 2010 00:00:00 GMT</pubDate>
            <category>DynamicProxy</category>
            <category>MVVM</category>
            <category>INotifyPropertyChange</category>
        </item>
        <item>
            <dc:creator>HEskandari</dc:creator>
            <title>WPF Application with Caliburn - Part Two</title>
            <description>&lt;p&gt;
	In this part of the tutorial, we&amp;#39;ll enhance our shell view to display other presenters and add Save and Print support for presenters supporting it. You can use generalize this example and learn how to implement generic features in your shell.&lt;/p&gt;
&lt;p&gt;
	Caliburn has several existing classes that can be used as a base class for our presenters. Let&amp;#39;s explain some of them and see where do they fit:&lt;/p&gt;
&lt;p&gt;
	&lt;span style=&quot;color: rgb(255, 140, 0);&quot;&gt;&lt;em&gt;&lt;strong&gt;Presenter&lt;/strong&gt;&lt;/em&gt;&lt;/span&gt;&lt;br /&gt;
	This class implements IPresenter interface and provides life time methods such as Initialize, Shutdown, Active and Deactive. You can use this class for other views that are going to be displayed in the Shell View.&lt;/p&gt;
&lt;p&gt;
	&lt;span style=&quot;color: rgb(255, 140, 0);&quot;&gt;&lt;em&gt;&lt;strong&gt;Presenter Manager&lt;/strong&gt;&lt;/em&gt;&lt;/span&gt;&lt;br /&gt;
	Using a presenter manager, as the name implies, you can host and display a single instance of a Presenter. It only allows displaying of one Presenter only so you have only one view displayed to the user when using it.&lt;/p&gt;
&lt;p&gt;
	&lt;span style=&quot;color: rgb(255, 140, 0);&quot;&gt;&lt;em&gt;&lt;strong&gt;MultiPresenterManager&lt;/strong&gt;&lt;/em&gt;&lt;/span&gt;&lt;br /&gt;
	Same as PresenterManager but can host multiple Presenters at the same time, but only one of them is Active at a time.&lt;/p&gt;
&lt;p&gt;
	When we display a Presenter, the PresenterManager will call the lifetime methods on the Presenter instance. The following diagram shows this flow:&lt;/p&gt;
&lt;p style=&quot;text-align: center;&quot;&gt;
	&lt;img alt=&quot;&quot; src=&quot;/Images/BlogPics/Caliburn_PartTwo_Presenter.png&quot; /&gt;&lt;/p&gt;
&lt;p&gt;
	For now, it is obvious that we need to change the base class of our &lt;em&gt;ShellViewModel&lt;/em&gt; to &lt;em&gt;PresenterManager&lt;/em&gt; (too keep it simple for the time being), but how should we change the xaml code to host the views (other Presenters)? Your first guess would be to bind &lt;em&gt;CurrentPresenter&lt;/em&gt; property of the &lt;em&gt;PresenterManager&lt;/em&gt; to a &lt;em&gt;ContentControl&lt;/em&gt; in the Shell.xaml, but you don&amp;#39;t need to do that as Caliburn will do the plumbing for us, just add a &lt;em&gt;ContentControl&lt;/em&gt; to the Shell view where you want the views to be displayed and name it as &amp;quot;CurrentPresenter&amp;quot;.&lt;/p&gt;
&lt;p&gt;
	To make Caliburn bind Views to the content control, you need to enable additional &lt;em&gt;Conventions&lt;/em&gt; that are not enabled by default. Placing the following snippet in Caliburn configuration will do the trick:&lt;/p&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
var binder = (DefaultBinder)Container.GetInstance&amp;lt;IBinder&amp;gt;();
binder.EnableBindingConventions();
&lt;/pre&gt;
&lt;p&gt;
	The bare bone of the shell view that displays a single presenter is this:&lt;/p&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
&amp;lt;Window x:Class=&amp;quot;PayRoll.Views.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; Width=&amp;quot;640&amp;quot; Height=&amp;quot;400&amp;quot;&amp;gt;
    &amp;lt;DockPanel LastChildFill=&amp;quot;True&amp;quot;&amp;gt;

        &amp;lt;ScrollViewer&amp;gt;
            &amp;lt;ContentControl x:Name=&amp;quot;CurrentPresenter&amp;quot; /&amp;gt;
        &amp;lt;/ScrollViewer&amp;gt;

    &amp;lt;/DockPanel&amp;gt;
&amp;lt;/Window&amp;gt;
&lt;/pre&gt;
&lt;p&gt;
	&lt;span class=&quot;subtitle&quot;&gt;&lt;br /&gt;
	Adding Custom Controls&lt;/span&gt;&lt;br /&gt;
	Now to handle user interaction with the shell and the open presenter, we need some kind of a Toolbar / Menu control. WPF comes with a very basic menu and toolbar control, but to show how to use custom controls and see how Caliburn facilitates this, let&amp;#39;s use DevExpress BarManager control in this example.&lt;/p&gt;
&lt;p&gt;
	DevExpress, among other nice things, provides presentation layer controls for WPF such as Editors, Bars (MenuBar, ToolBar and soon Ribbon), Grid and Printing. One other thing they&amp;#39;ve also done is that they also have skinned native WPF controls so if used together with DevExpress controls, you&amp;#39;ll have a seemless look and feel.&lt;/p&gt;
&lt;p&gt;
	To add the BarManager control to our ShellView, you need to download DevExpress WPF controls (trial version here) and install it. The add the necessary reference to devexpress WPF assemblies and import the xml namespaces. Here&amp;#39;s the snippet that creates the BarButtonItems which is equivalent of a ToolbarItem. (Get the accompanied zip for complete source code):&lt;/p&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
&amp;lt;dxb:BarManager.Items&amp;gt;
	&amp;lt;!--General Actions--&amp;gt;
	&amp;lt;dxb:BarButtonItem Name=&amp;quot;bSave&amp;quot;  CategoryName=&amp;quot;File&amp;quot; Content=&amp;quot;Save&amp;quot; Glyph=&amp;quot;/Images/Save.png&amp;quot;  KeyGesture=&amp;quot;Ctrl+S&amp;quot; /&amp;gt;
	&amp;lt;dxb:BarButtonItem Name=&amp;quot;bPrint&amp;quot; CategoryName=&amp;quot;File&amp;quot; Content=&amp;quot;Print&amp;quot; Glyph=&amp;quot;/Images/Print.png&amp;quot; KeyGesture=&amp;quot;Ctrl+P&amp;quot; /&amp;gt;
	&amp;lt;dxb:BarButtonItem Name=&amp;quot;bExit&amp;quot;  CategoryName=&amp;quot;File&amp;quot; Content=&amp;quot;Exit&amp;quot; Glyph=&amp;quot;/Images/Exit.png&amp;quot; KeyGesture=&amp;quot;Ctrl+X&amp;quot; /&amp;gt;
	
	&amp;lt;!--Status Bar--&amp;gt;
	&amp;lt;dxb:BarStaticItem Name=&amp;quot;bStatus&amp;quot; CategoryName=&amp;quot;Status&amp;quot; MinWidth=&amp;quot;300&amp;quot; Content=&amp;quot;Read&amp;quot; AutoSizeMode=&amp;quot;Fill&amp;quot;/&amp;gt;
&amp;lt;/dxb:BarManager.Items&amp;gt;
&lt;/pre&gt;
&lt;p&gt;
	Same as Button object, BarButtonItems provide a Command property which you can bind to an ICommand instance on your ViewModel, but this is rather limited, don&amp;#39;t you think? What if you want to bind another event (other then Click) to your ViewModel?&lt;/p&gt;
&lt;p&gt;
	Caliburn provides Actions and Messages with which you can bind a regular Event on your View and Controls to a method on your ViewModel, without using ICommand. You can even run the event handler (on your VM) asynchronously! There are a few ways to do this but the best way, in my opinion, is to this format:&lt;/p&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
cal:Message.Attach=&amp;quot;[Event EventNameOnControl] = [Action ActionNameOnViewModel()]&amp;quot;
&lt;/pre&gt;
&lt;p&gt;
	Note that you can actually bind two actions to one event, just like you can have two methods listening to a regular event. Let&amp;#39;s change the snippet above and add the messaging support:&lt;/p&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
&amp;lt;dxb:BarButtonItem Name=&amp;quot;bSave&amp;quot; cal:Message.Attach=&amp;quot;[Event ItemClick] = [Action SavePresenter()]&amp;quot;/&amp;gt;
	&amp;lt;dxb:BarButtonItem Name=&amp;quot;bPrint&amp;quot; cal:Message.Attach=&amp;quot;[Event ItemClick] = [Action PrintPresenter()]&amp;quot;/&amp;gt;
	&amp;lt;dxb:BarButtonItem Name=&amp;quot;bExit&amp;quot; cal:Message.Attach=&amp;quot;[Event ItemClick] = [Action Exit()]&amp;quot; /&amp;gt;
&lt;/pre&gt;
&lt;p&gt;
	Note: Unlike a regular Button, BarButtonItem has no &amp;quot;Click&amp;quot; event and provides an &amp;quot;ItemClick&amp;quot; event instead. Clearly, we need the specified methods on our ViewModel, so let&amp;#39;s add them too:&lt;/p&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public class ShellViewModel : PresenterManager, IShellViewModel
{
    public virtual void SavePresenter()
    {
    }

    public virtual void PrintPresenter()
    {
    }

    public virtual void Exit()
    {
    }
}
&lt;/pre&gt;
&lt;p&gt;
	At this point, you can run the shell and click the tool bar items, which will call the specified method on the view model. Now the question is, what if a presenter is not in a suitable state to be saved (dirty checking, already saved, etc.). What if a presenter does not even support printing? How can we disable the BarButtonItem responsible for an action, if the presenter does not support it?&lt;/p&gt;
&lt;p&gt;
	With Conventions already enabled, you can have additional &amp;quot;Can*&amp;quot; methods acting as a Filter for your actions. These filters will be checked on runtime for returning false value indicating the action can not be performed, or true value for allowed actions. Caliburn will try to disable the piece of UI through an &amp;quot;IAvailabilityEffect&amp;quot; interface. Let&amp;#39;s see this in more dept.&lt;br /&gt;
	&amp;nbsp;&lt;/p&gt;
&lt;p&gt;
	&lt;span class=&quot;subtitle&quot;&gt;Working with Actions&lt;/span&gt;&lt;br /&gt;
	As mentioned, Caliburn checks for availability of an action automagically if it finds a pairing &amp;quot;Can*&amp;quot; filter method on the presenter. So let&amp;#39;s add those and see how it works:&lt;/p&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public virtual bool CanExit()
{
    return base.CanShutdown();
}

public virtual bool CanPrintPresenter()
{
    var presenter = CurrentPresenter as IPrintablePresenter;
    return presenter != null &amp;amp;&amp;amp;
           presenter.CanPrint;
}

public virtual bool CanSavePresenter()
{
    var presenter = CurrentPresenter as ISaveablePresenter;
    return presenter != null &amp;amp;&amp;amp;
           presenter.CanSave;
}
&lt;/pre&gt;
&lt;p&gt;
	When you run the application and set a break point on CanSave and Save methods, you&amp;#39;ll notice two things:&lt;/p&gt;
&lt;p&gt;
	&lt;em&gt;A. While CanPrint method returns False value, UI element (BarButtonItem) is not disabled!&lt;br /&gt;
	&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;
	&lt;em&gt;B. By clicking the BarButtonItem, the Save method will not be called.&lt;br /&gt;
	&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;
	So there seems to be a problem...Why isn&amp;#39;t BarButtonItem disabled? Wasn&amp;#39;t Caliburn supposed to do that for us? Well...The default &lt;em&gt;&lt;strong&gt;&amp;quot;Disable&amp;quot;&lt;/strong&gt;&lt;/em&gt; effect, only works for &lt;em&gt;UIElements&lt;/em&gt;, but &lt;em&gt;BarButtonItem&lt;/em&gt; is actually a &lt;em&gt;FrameworkContentElement&lt;/em&gt;. Those are two different beasts and Caliburn can not handle our UI control. The solution is easy though. You can create your own &lt;strong&gt;&lt;em&gt;IAvailabilityEffect&lt;/em&gt;&lt;/strong&gt; that works with &lt;em&gt;FrameworkContentElements&lt;/em&gt;.&lt;/p&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public class DisableMenuEffect : IAvailabilityEffect
{
    public void ApplyTo(DependencyObject target, bool isAvailable)
    {
        var element = target as FrameworkContentElement;
        if(element == null)
            return;

        element.IsEnabled = isAvailable;
    }
}
&lt;/pre&gt;
&lt;p&gt;
	...and set it along with the action on the View:&lt;/p&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
&amp;lt;dxb:BarButtonItem cal:Message.Attach=&amp;quot;[Event ItemClick] = [Action SavePresenter()]&amp;quot; cal:Message.AvailabilityEffect=&amp;quot;DisableMenuEffect&amp;quot; /&amp;gt;
    &amp;lt;dxb:BarButtonItem cal:Message.Attach=&amp;quot;[Event ItemClick] = [Action PrintPresenter()]&amp;quot; cal:Message.AvailabilityEffect=&amp;quot;DisableMenuEffect&amp;quot; /&amp;gt;
    &amp;lt;dxb:BarButtonItem cal:Message.Attach=&amp;quot;[Event ItemClick] = [Action Exit()]&amp;quot; cal:Message.AvailabilityEffect=&amp;quot;DisableMenuEffect&amp;quot; /&amp;gt;
&lt;/pre&gt;
&lt;p&gt;
	There&amp;#39;s one last trick to make this work. Caliburn has no way to convert the specified string to an IAvailabilityEffect instance! The existing ValueCovertor, asks our Container for any object named &amp;quot;DisableMenuEffect&amp;quot;. The final piece of code would be to register all instances of IAvailabilityEffects you might want to use on the container:&lt;/p&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
_container.Register(Component.For&amp;lt;DisableMenuEffect&amp;gt;()
                             .Named(&amp;quot;DisableMenuEffect&amp;quot;)
                             .LifeStyle.Singleton);
&lt;/pre&gt;
&lt;p&gt;
	When running the application, and there&amp;#39;s no open view, the toolbar items are disabled.&lt;/p&gt;
&lt;p style=&quot;text-align: center;&quot;&gt;
	&lt;img alt=&quot;&quot; src=&quot;/Images/BlogPics/Caliburn_PartTwo_DisabledToolbar.png&quot; style=&quot;width: 400px; height: 280px;&quot; /&gt;&lt;/p&gt;
&lt;p&gt;
	To show how it works, let&amp;#39;s add a new View and ViewModel to our application, and also add a button to the shell that allows us to open this view. As mentioned before, to do this, you need to create a UserControl for you View and a class deriving from Presenter base class for your ViewModel.&lt;/p&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public class PersonViewModel : Presenter
{
    private Person _person;
    private ObservableCollection&amp;lt;Person&amp;gt; _personnelList;
    private ObservableCollection&amp;lt;Job&amp;gt; _jobs;
    private readonly IPersonDataService _service;

    public PersonViewModel(IPersonDataService service)
    {
        _service = service;
    }

    public override void Initialize()
    {
        _jobs = new ObservableCollection&amp;lt;Job&amp;gt;(_service.GetJobs());
        _personnelList = new ObservableCollection&amp;lt;Person&amp;gt;(_service.GetPersonnel());
    }

    public Person CurrentPerson
    {
        get { return _person; }
        set
        {
            _person = value;
            base.NotifyOfPropertyChange(&amp;quot;CurrentPerson&amp;quot;);
        }
    }

    public ObservableCollection&amp;lt;Person&amp;gt; Personnel
    {
        get { return _personnelList; }
    }

    public ObservableCollection&amp;lt;Job&amp;gt; Jobs
    {
        get { return _jobs; }
    }
}
&lt;/pre&gt;
&lt;p&gt;
	Now create a UserControl for PersonView using DevExpress editors looking like this:&lt;/p&gt;
&lt;p style=&quot;text-align: center;&quot;&gt;
	&lt;img alt=&quot;&quot; src=&quot;/Images/BlogPics/Caliburn_PartTwo_PersonView.png&quot; style=&quot;width: 533px; height: 272px;&quot; /&gt;&lt;/p&gt;
&lt;p&gt;
	To support saving, let&amp;#39;s add ISaveablePresenter interface to our ViewModel and check if DateOfBirth property of the current person is valid before saving:&lt;/p&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public bool CanSave
{
    get 
    {
        return CurrentPerson != null &amp;amp;&amp;amp;
               CurrentPerson.DateOfBirth.Year &amp;gt; 1900;
    }
}

public void Save()
{
    MessageBox.Show(&amp;quot;Saved&amp;quot;);
}
&lt;/pre&gt;
&lt;p&gt;
	You can observe that CanSave property will never get executed! The reason is that when application starts, Caliburn checks if any of the Action methods are available by checking their respective Filters (here CanSavePresenter and CanPrintPresenter), but it never checks them again. In other words, by default action filters (Can* methods) are only called once. How can we change this behavior?&lt;/p&gt;
&lt;p&gt;
	There&amp;#39;s an attribute called &lt;em&gt;&lt;strong&gt;&amp;quot;AutoCheckAvailability&amp;quot;&lt;/strong&gt;&lt;/em&gt; that you can place on your action methods. This will tell WPF Command Manager to look out for availability of the bound action. Doing this will call the action filters periodically, so make sure if you really need it before actually using it. So apply this to our ViewModel, let&amp;#39;s get back to our ShellViewModel class and place the attribute on our actions:&lt;/p&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
[AutoCheckAvailability]
public virtual void SavePresenter()
{
    var presenter = (ISaveablePresenter)CurrentPresenter;
    presenter.Save();
}

[AutoCheckAvailability]
public virtual void PrintPresenter()
{
    var presenter = (IPrintablePresenter)CurrentPresenter;
    presenter.Print();
}
&lt;/pre&gt;
&lt;p&gt;
	&lt;em&gt;&lt;strong&gt;Note: You need to place this on your actions, not on filters.&lt;br /&gt;
	&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;
	...et voila!&lt;/p&gt;
&lt;p style=&quot;text-align: center;&quot;&gt;
	&lt;img alt=&quot;&quot; src=&quot;/Images/BlogPics/Caliburn_PartTwo_Application_View.png&quot; /&gt;&lt;/p&gt;
&lt;p&gt;
	Our shell now can host other views and has generic actions that is automagically enabled / disabled for views supporting it.&lt;/p&gt;
&lt;p&gt;
	In the next post, I&amp;#39;ll show you how to change our existing shell to display a Tabbed interface and display multiple views at the same time. The &lt;a href=&quot;http://cid-4962b6ceabc2cbd7.skydrive.live.com/self.aspx/BlogFiles/PayRoll%20-%20Caliburn%20Part%20Two.zip&quot;&gt;attached zip file&lt;/a&gt; contains the complete source code.&lt;/p&gt;</description>
            <link>http://www.hightech.ir/SeeSharp/WPF-Application-With-Caliburn-Part-Two</link>
            <guid isPermaLink="true">http://www.hightech.ir/SeeSharp/WPF-Application-With-Caliburn-Part-Two</guid>
            <pubDate>Fri, 15 Jan 2010 00:00:00 GMT</pubDate>
            <category>MVVM</category>
            <category>WPF</category>
            <category>Caliburn</category>
        </item>
        <item>
            <dc:creator>HEskandari</dc:creator>
            <title>WPF Application with Caliburn - Part One</title>
            <description>&lt;p&gt;Back in May 2008, I did &lt;a href=&quot;http://www.hightech.ir/SeeSharp/wpf-composite-application-with-caliburn-part-one&quot;&gt;two posts&lt;/a&gt; on how to implement a composite application using &lt;a href=&quot;http://caliburn.codeplex.com/&quot;&gt;Caliburn&lt;/a&gt; framework. By that time, Caliburn was still in pre-alpha stage. With lots of the changes along the way to reach &lt;a href=&quot;http://caliburn.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=32809&quot;&gt;Release Candidate&lt;/a&gt;, those content are not valid anymore, so I thought a new post to show how you can use Caliburn to build a WPF application is in order.&lt;br/&gt;&lt;br/&gt;

In fact, a while ago I started porting my old .NET 1.1 pay roll application to WPF and .NET 3.5 so I naturally chose to use Caliburn and it did facilitate things a lot, but to keep things simple, I'm not going to discuss my own application here. I'll show how you how can create your own application using Caliburn framework and how it will help you out.&lt;/p&gt;

&lt;span class=&quot;subtitle&quot;&gt;Framework Setup&lt;/span&gt;
&lt;p&gt;
First thing you need to do, is to setup a new WPF application. Let's call it PayRoll application. After doing so, add reference to &lt;a href=&quot;http://caliburn.codeplex.com&quot;&gt;Caliburn&lt;/a&gt; and &lt;a href=&quot;http://www.castleproject.org/container/index.html&quot;&gt;Castle&lt;/a&gt; assemblies. Caliburn honors the &lt;a href=&quot;http://en.wikipedia.org/wiki/Dependency_inversion_principle&quot;&gt;Dependency-Injection principle&lt;/a&gt; by depending only on abstractions. The idea is to allow you to easily plug in your own implementation of that abstraction and customize how Caliburn components work. To do so, Caliburn uses an &lt;a href=&quot;http://en.wikipedia.org/wiki/Inversion_of_control&quot;&gt;IoC Container&lt;/a&gt; to lookup the services it requires.&lt;br/&gt;&lt;br/&gt;

If you're new to &lt;a href=&quot;http://martinfowler.com/articles/injection.html&quot;&gt;Dependency Injection&lt;/a&gt; stuff, don't worry, there is a built-in &lt;em&gt;SimpleContainer&lt;/em&gt; which will do the job for you but I'll be using Castle container (Windsor) here. If you're using other IoC containers such as &lt;a href=&quot;http://code.google.com/p/autofac/&quot;&gt;AutoFac&lt;/a&gt;, &lt;a href=&quot;http://ninject.org/&quot;&gt;Ninject&lt;/a&gt;, &lt;a href=&quot;http://structuremap.sourceforge.net/&quot;&gt;StructureMap&lt;/a&gt;, &lt;a href=&quot;http://www.springframework.net/&quot;&gt;Spring&lt;/a&gt; or even &lt;a href=&quot;http://www.codeplex.com/MEF&quot;&gt;MEF&lt;/a&gt; (&lt;a href=&quot;http://devlicio.us/blogs/casey/archive/2009/12/18/what-is-the-difference-between-an-ioc-container-and-mef.aspx&quot;&gt;not technically an IoC container&lt;/a&gt;), Caliburn comes with existing adapters for those too, so no worries. To lookup instances of the services it needs, Caliburn uses the &lt;a href=&quot;http://www.codeplex.com/CommonServiceLocator&quot;&gt;Common ServiceLocator&lt;/a&gt; and &lt;a href=&quot;http://en.wikipedia.org/wiki/Service_locator_pattern&quot;&gt;Service Locator&lt;/a&gt; design pattern. This allows looking up for services from various IoC containers, without actually depending on those containers.&lt;br/&gt;&lt;br/&gt;

Now to initialize Caliburn framework at startup there are various ways, but the easiest would be to create a CaliburnApplication. We already have an application object (App.xaml and App.xaml.cs) so we only need to change them to derive from CaliburnApplication class. To do so, open the App.xaml file first, and include the Caliburn namespace and change the type to Caliburn application. Also, we don't want to specify any StartupUri, so get rid of that too. The result would be this:&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
&amp;lt;cal:CaliburnApplication x:Class=&quot;PayRoll.App&quot;
    xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
    xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
    xmlns:cal=&quot;http://www.caliburnproject.org&quot;&amp;gt;
    &amp;lt;Application.Resources&amp;gt;
         
    &amp;lt;/Application.Resources&amp;gt;
&amp;lt;/cal:CaliburnApplication&amp;gt;
&lt;/pre&gt;

&lt;p&gt;With this, the project won't compile! Because we've specified different base classes in our Xaml and Code Behind. Since the base class in code behind is inferred, open the code behind and remove the base class. The code would look like this:&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
namespace PayRoll
{
    /// &amp;lt;summary&gt;
    /// Interaction logic for App.xaml
    /// &amp;lt;/summary&gt;
    public partial class App
    {
    }
}
&lt;/pre&gt;

&lt;p&gt;So far so good. Now, If you look at the Caliburn Application class, there are interesting things that we can do. The obvious one is a method called CreateContainer. The default implementation, as said before, will create a &lt;em&gt;SimpleContainer&lt;/em&gt; but we're going to use our own container, so let's do so:&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
    protected override IServiceLocator CreateContainer()
    {
        _container = new WindsorContainer();
        return new WindsorAdapter(_container);
    }
&lt;/pre&gt;

&lt;p&gt;Next step would be specifying a RootViewModel (also called ShellViewModel) that will act as ViewModel for our MainWindow. Notice that we have nothing to do with the actual View (UI) that will be displayed, we just specify the ViewModel for it:&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
    protected override object CreateRootModel()
    {
        return _container.Resolve&amp;lt;IShellViewModel&amp;gt;();
    }
&lt;/pre&gt;

&lt;p&gt;At this point, we need to create a ViewModel and a View for our Shell and register the VM in the container. Create two folders in your solution one named &lt;em&gt;Views&lt;/em&gt; and the other &lt;em&gt;ViewModels&lt;/em&gt;. Create an interface in ViewModels folder named IShellViewModel and create a class implementing this yet empty interface, named ShellViewModel. So now we need to register these (along with other services, view models, etc.) in the container:&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
    public App()
    {
        RegisterComponents();
    }

    private void RegisterComponents()
    {
        _container.Register(Component.For&amp;lt;IShellViewModel&amp;gt;()
                                     .ImplementedBy&amp;lt;ShellViewModel&amp;gt;()
                                     .LifeStyle.Singleton);
    }
&lt;/pre&gt;
	
&lt;p&gt;Notice that lifestyle of ShellViewModel is set to singleton. This is logical because there's always one instance of the ShellView running. We'll see how this allow us interact from other ViewModels with Shell VM.&lt;/p&gt;

&lt;span class=&quot;subtitle&quot;&gt;Marrying the View and ViewModel&lt;/span&gt;
&lt;p&gt;Now, let's run the application and see what happens. When we run the application, Caliburn throws an exception complaining that a View can not be created for the ShellViewModel. Since we didn't specify any information about our Views, you might say: How is Caliburn supposed to create a View for my ViewModel anyway? Well, Caliburn tries many things before giving up and throwing an exception:&lt;/p&gt;

&lt;ul&gt;
   &lt;li&gt;First, if your ViewModel implements the IMetadataContainer interface, the GetMetadata&lt;T&gt; method is called on your VM, asking for a view. Since this not a good option for us, let's skip it.&lt;/li&gt;
   &lt;li&gt;Second, if the ViewModel is decorated with a ViewAttribute, the specified view will be created. This is relatively easy, but it clutters your ViewModel with an attribute and I don't like it.&lt;/li&gt;
   &lt;li&gt;Third, specified assemblies will be searched to find the matching view according to a specified naming convention. This sound interesting, let's use this method.&lt;/li&gt;
   &lt;li&gt;Fourth, if you don't like any of these behaviors, you can plug in your own IViewStrategy implementation.&lt;/li&gt;
&lt;/ul&gt;
   
&lt;p&gt;If you remember, we've created an empty &lt;em&gt;Views&lt;/em&gt; folder. If you create a UserControl named &lt;em&gt;ShellView&lt;/em&gt; (mind the naming), Caliburn will automagically pick it up as the View for our &lt;em&gt;ShellViewModel&lt;/em&gt;. How is this done, you may ask? According to &lt;a href=&quot;http://en.wikipedia.org/wiki/Convention_over_configuration&quot;&gt;pre-defined naming rules&lt;/a&gt;, Caliburn will look in folders named &lt;em&gt;Presenter&lt;/em&gt;, &lt;em&gt;Model&lt;/em&gt;, &lt;em&gt;ViewModel&lt;/em&gt; and &lt;em&gt;PresentationModel&lt;/em&gt; to create a ViewModel instance, and to create a View instance, it will look for it in the &lt;em&gt;Views&lt;/em&gt; folder. An example might clear it up a little bit. Supposing you have an &lt;em&gt;IShellPresenter&lt;/em&gt;, the implementation would be named &lt;em&gt;ShellPresenter&lt;/em&gt; in the folder named &lt;em&gt;Presenters&lt;/em&gt;. You should name the view for this presenter &lt;em&gt;ShellView&lt;/em&gt; and place it in &lt;em&gt;Views&lt;/em&gt; folder. The ViewModel names refers to different implementation of &lt;a href=&quot;http://martinfowler.com/eaaDev/PresentationModel.html&quot;&gt;Presentation Model&lt;/a&gt; design pattern, but those terms are used interchangeably in Caliburn.&lt;br/&gt;&lt;br/&gt;

So, we're going to use the naming convention (fourth method). Let's create an empty UserControl named &lt;em&gt;ShellView&lt;/em&gt; and put it in &lt;em&gt;Views&lt;/em&gt; folder:&lt;/p&gt;

&lt;pre class=&quot;brush:xml&quot;&gt;
&amp;lt;UserControl x:Class=&quot;PayRoll.Views.ShellView&quot;
    xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
    xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;&amp;gt;
    
&amp;lt;/UserControl&amp;gt;
&lt;/pre&gt;

&lt;p&gt;You can run the application now and it works. Caliburn has created a View (UI) and a POCO class as ViewModel and set the DataContext property of the View to the instance of the ViewModel. If you've noticed, we've set a UserControl as our root View. While you can create a Window object as your root View, if you create a UserControl (or anything other than a Window), Caliburn will create a MainWindow for you and place the View object as its content. This behavior is for Caliburn v1.1 so if you're using older version 1.0 you can either upgrade or use a Window as your root view.&lt;/p&gt;

&lt;span class=&quot;subtitle&quot;&gt;Binding&lt;/span&gt;
&lt;p&gt;To check if View and ViewModel are really bound together, let's create a commmand on the ViewModel and invoke it from the View. When invoked, it will change a Message property on the ViewModel. So first, open the IShellViewModel interface and add the ICommand and Message properties to the interface definition:&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
    public interface IShellViewModel
    {
        /// &amp;lt;summary&gt;
        /// A command that says hello when invoked.
        /// &amp;lt;/summary&gt;
        ICommand SayHelloCommand { get; }

        /// &amp;lt;summary&gt;
        /// Message
        /// &amp;lt;/summary&gt;
        string Message { get; set; }
    }
&lt;/pre&gt;
	
&lt;p&gt;...and implement the command property on your ShellViewModel class. To facilitate command handling, we'll use a DelegateCommand class (originally &lt;a href=&quot;http://msdn.microsoft.com/en-us/magazine/dd419663.aspx&quot;&gt;RelayCommand&lt;/a&gt;) introduced by &lt;a href=&quot;http://joshsmithonwpf.wordpress.com/&quot;&gt;Josh Smith&lt;/a&gt;. Then instead of just displaying a MessageBox, let's Create a TextBlock and bind it to the Message property on our ViewModel. When binding some element to a property on the ViewModel, we need to implement INotifyPropertyChanged interface on the ViewModel. Fortunately, there's a base class in Caliburn which does exactly that:&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
    public class ShellViewModel : PropertyChangedBase, IShellViewModel
    {
        private ICommand _sayHelloCommand;
        private string _message;

        public virtual ICommand SayHelloCommand
        {
            get
            {
                if (_sayHelloCommand == null)
                    _sayHelloCommand = new DelegateCommand(SayHello);

                return _sayHelloCommand;
            }
        }

        public virtual string Message
        {
            get { return _message; }
            set
            {
                _message = value;
                NotifyOfPropertyChange(&quot;Message&quot;);
            }
        }

        private void SayHello()
        {
            Message = &quot;Greetings from Caliburn!&quot;;
        }
    }
&lt;/pre&gt;

&lt;p&gt;...Finally, let's place a Button and a TextBlock on the View and bind those to our ViewModel:&lt;/p&gt;

&lt;pre class=&quot;brush:xml&quot;&gt;
&amp;lt;Window x:Class=&quot;PayRoll.Views.ShellView&quot;
    xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
    xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot; Width=&quot;320&quot; Height=&quot;200&quot; &amp;gt;
    &amp;lt;StackPanel&amp;gt;
        
        &amp;lt;Button Command=&quot;{Binding Path=SayHelloCommand}&quot; Content=&quot;Say Hello&quot;  /&amp;gt;
        
        &amp;lt;TextBlock Text=&quot;{Binding Path=Message}&quot; FontSize=&quot;16&quot; FontWeight=&quot;Bold&quot; /&amp;gt;
        
    &amp;lt;/StackPanel&amp;gt;
&amp;lt;/Window&amp;gt;
&lt;/pre&gt;

&lt;p&gt;In next post, I'll show you how to add &lt;a href=&quot;http://www.devexpress.com/Products/NET/Controls/WPF/&quot;&gt;DevExpress components&lt;/a&gt; to the pot and how to create a re-usable shell and along the way. We'll see how to host other ViewModels in our ShellView and how to manage them. You can get the source code of this part from &lt;a href=&quot;http://cid-4962b6ceabc2cbd7.skydrive.live.com/self.aspx/BlogFiles/PayRoll%20-%20Caliburn%20Part%20One.zip&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;</description>
            <link>http://www.hightech.ir/SeeSharp/WPF-Application-With-Caliburn-Part-One</link>
            <guid isPermaLink="true">http://www.hightech.ir/SeeSharp/WPF-Application-With-Caliburn-Part-One</guid>
            <pubDate>Wed, 30 Dec 2009 00:00:00 GMT</pubDate>
            <category>MVVM</category>
            <category>WPF</category>
            <category>Caliburn</category>
        </item>
        <item>
            <dc:creator>HEskandari</dc:creator>
            <title>Caliburn = Less Code?</title>
            <description>&lt;a href=&quot;http://www.codeplex.com/caliburn&quot;&gt;Caliburn&lt;/a&gt; is an application framework for WPF / Silverlight. If you're developing applications for these platforms, there are many reasons why you definitely need to be using this framework, but today, I noticed how using this framework resulted writing less code while doing more. Let's see how writing a small WPF application using &lt;a href=&quot;http://en.wikipedia.org/wiki/Model_View_ViewModel&quot;&gt;MVVM&lt;/a&gt; pattern is different when using &lt;a href=&quot;http://www.codeplex.com/caliburn&quot;&gt;Caliburn&lt;/a&gt;.
&lt;i&gt;&lt;b&gt;Note: There are many other ways to skin a cat. This is how I do things, there may be other, better ways to do the same thing.&lt;/b&gt;&lt;/i&gt;&lt;br /&gt;&lt;br /&gt;&lt;span class=&quot;subtitle&quot;&gt;Application Startup&lt;/span&gt;&lt;br /&gt;When creating an application using MVVM and &lt;em&gt;&lt;a href=&quot;http://wildermuth.com/2009/05/22/Which_came_first_the_View_or_the_Model&quot;&gt;ViewModel First&lt;/a&gt;&lt;/em&gt; development, you'd create the root View and VM, bind them through DataContext and show the main window of the application.  &lt;br /&gt;&lt;br /&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
///
/// Interaction logic for App.xaml
///
public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        
        var container = new WindsorContainer();
        var rootView = new RootView();
        var rootModel = new RootViewModel();
        
        rootView.DataContext = rootModel;
        this.MainWindow = rootView;
        this.MainWindow.Show();
    }
}
&lt;/pre&gt;
With caliburn, all you need to do is to create the root VM. There's no trace of any View creation and binding the DataContext to VM. All this is done automatically by Caliburn. To do this, use &lt;em&gt;&lt;a href=&quot;http://caliburn.codeplex.com/Wiki/View.aspx?title=Application&quot;&gt;CaliburnApplication&lt;/a&gt;&lt;/em&gt; as your base application class which will configure Caliburn framework upon startup. There are &lt;a href=&quot;http://caliburn.codeplex.com/Wiki/View.aspx?title=Project%20Setup&amp;amp;referringTitle=Home&quot;&gt;other ways&lt;/a&gt; to do the configuration but let's stick to this simple configuration scenario that installs default implementations of Calburn &lt;em&gt;Components&lt;/em&gt;.&lt;br /&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
///
/// Interaction logic for App.xaml
///
public partial class App : CaliburnApplication
{
    protected override IServiceLocator CreateContainer()
    {
        var container = new WindsorContainer();
        var adapter = new WindsorAdapter(container);
        
        return adapter;
    }
    
    protected override object CreateRootModel()
    {
        return new RootViewModel();
    }
}
&lt;/pre&gt;
One thing a little different is that Caliburn uses &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/dd458913.aspx&quot;&gt;IServiceLocator&lt;/a&gt; insterface (from &lt;a href=&quot;http://www.codeplex.com/CommonServiceLocator/&quot;&gt;Common Service Locator&lt;/a&gt;) and has no direct dependency on a vendor specific &lt;a href=&quot;http://martinfowler.com/articles/injection.html&quot;&gt;IoC Container&lt;/a&gt;, which is a good thing. This means, you can choose various IoC containers and adapters for major IoC containers like &lt;a href=&quot;http://www.castleproject.org/container/index.html&quot;&gt;Windsor&lt;/a&gt;, &lt;a href=&quot;http://ninject.org/&quot;&gt;Ninject&lt;/a&gt;, &lt;a href=&quot;http://code.google.com/p/autofac/&quot;&gt;Autofac&lt;/a&gt;, etc. are already included in Caliburn bits. If you're not a fan of IoC containers and won't be using one in your application (now, come on!), Caliburn uses a lightweight built-in container, in case you don't specify any other.&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;color: #0080c0; font-size: 100%;&quot;&gt;&lt;b&gt;Actions and Commands&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;Should you bind an action to a ICommand instance on the VM, in pure MVVM application you would bind the &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/ms752308.aspx&quot;&gt;Command&lt;/a&gt; property to an &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.windows.input.icommand.aspx&quot;&gt;ICommand&lt;/a&gt; instance on the VM. You can specify the condition on which the command will be executable and you'll also implement the action execute by the command.&lt;br /&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
&amp;lt;Button Command=&quot;{Binding ExitCommand}&quot; Content=&quot;Exit Application&quot;&amp;gt;

public class RootViewModel : BaseViewModel
{
    private ICommand _exitCommand;
    public ICommand ExitCommand
    {
        get
        {
            if (_exitCommand == null)
                _exitCommand = new RelayCommand(this.Exit, this.CanExit);
            
            return _exitCommand;
        }
    }
    
    public bool CanExit()
    {
        return true;
    }
    
    public void Exit()
    {
        Application.Current.Shutdown();
    }
}
&lt;/pre&gt;
Notice there are other &lt;em&gt;hidden&lt;/em&gt; code here too. You'll need to create a new Command, or use &lt;a href=&quot;http://www.codeproject.com/KB/WPF/VMCommanding.aspx&quot;&gt;RelayCommand&lt;/a&gt; (kudos to &lt;a href=&quot;http://joshsmithonwpf.wordpress.com/&quot;&gt;Josh&lt;/a&gt;) and you probably need a common &lt;a href=&quot;http://martinfowler.com/eaaCatalog/layerSupertype.html&quot;&gt;layer supertype&lt;/a&gt; that implements &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx&quot;&gt;INotifyPropertyChanged&lt;/a&gt;&lt;i&gt;&lt;/i&gt; interface. Using Caliburn you'd bind the &lt;a href=&quot;http://caliburn.codeplex.com/Wiki/View.aspx?title=Action%20Basics&amp;amp;referringTitle=Home&quot;&gt;action&lt;/a&gt; directly to the VM and there's no dependency to ICommand instances. The good thing is, you're not limited to Command property anymore and you can bind various other events such as Click, MouseOver, etc. to actions on your VM.&lt;br /&gt;
&lt;pre name=&quot;code&quot; class=&quot;brush:c-sharp&quot;&gt;
&amp;lt;Button cal:Message.Attach=&quot;[Event Click] = [Action Exit]&quot; Content=&quot;Exit Application&quot;&amp;gt;

public class RootViewModel : Presenter
{
    public bool CanExit()
    {
        return true;
    }
    
    public void Exit()
    {
        Application.Current.Shutdown();
    }
}
&lt;/pre&gt;
There are lots of existing boilerplate functionalities already available in Caliburn, so you can drop BaseViewModel and use &lt;a href=&quot;http://caliburn.codeplex.com/Wiki/View.aspx?title=IPresenter%20Component%20Model&quot;&gt;Presenter&lt;/a&gt; class (IPresenter implementation).&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;color: #0080c0; font-size: 100%;&quot;&gt;&lt;b&gt;Displaying Views&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;To display other views in the RootView (e.g. Shell), we'd constructed a new VM and set it to a Content property of a ContentControl. This will actually pick up the view specified in the DataTemplate from Application Resources, and display it on the UI. You have to maintain a mapping between your Views and your VMs in a resource dictionary and as your application grows this gets harder to maintain.&lt;br /&gt;
&lt;pre name=&quot;code&quot; class=&quot;brush:c-sharp&quot;&gt;
&amp;lt;Application.Resources&amp;gt;
    &amp;lt;DataTemplate DataType=&quot;{x:Type vm:CustomerViewModel}&quot;&amp;gt;
        &amp;lt;view:CustomerView /&amp;gt;
    &amp;lt;/DataTemplate&amp;gt;
&amp;lt;/Application.Resources&amp;gt;

&amp;lt;ContentControl Content=&quot;{Binding Path=CurrentView}&quot;/&amp;gt;

public class RootViewModel : BaseViewModel
{
    public void ShowCustomer()
    {
        CurrentView = IoC.Resolve&amp;lt;Customerviewmodel&amp;gt;();
    }
    
    private BaseViewModel _currentView;
    public BaseViewModel CurrentView
    {
        get { return _currentView; }
        set
        {
            _currentView = value;
            RaisePropertyChanged(&quot;CurrentView&quot;);
        }
    }
}
&lt;/pre&gt;
Let's see how we can do this using Caliburn. First off, we do not need to maintain any ViewModel mapping if we name our Views and ViewModels according to the Caliburn &lt;a href=&quot;http://caliburn.codeplex.com/Wiki/View.aspx?title=IBinder%20and%20Convention%20over%20Configuration&quot;&gt;Conventions&lt;/a&gt; that is, your view names should ending in View, presenters / VMs ending in &lt;em&gt;ViewModel&lt;/em&gt;or &lt;em&gt;Presenter&lt;/em&gt; and each should be in a separate namespace, namingly &lt;em&gt;Views&lt;/em&gt; and &lt;em&gt;ViewModels&lt;/em&gt; or &lt;em&gt;Presenters&lt;/em&gt;. This is just by convention and you can always override if you need to. Caliburn will automatically create the view for you, set the &lt;em&gt;CurrentPresenter&lt;/em&gt; property on the main window (i.e. &lt;a href=&quot;http://caliburn.codeplex.com/Wiki/View.aspx?title=IPresenter%20Component%20Model&quot;&gt;IPresenterHost&lt;/a&gt;) and do any required bindings. Did I mention you don't need the whole mapping of View &amp;lt;-&amp;gt; &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.windows.datatemplate.aspx&quot;&gt;DataTemplate&lt;/a&gt; in your Application / Form resource?&lt;br /&gt;
&lt;pre name=&quot;code&quot; class=&quot;brush:c-sharp&quot;&gt;
&amp;lt;ContentControl x:Name=&quot;CurrentPresenter&quot; &amp;gt;

[Singleton(&quot;RootViewModel&quot;)]
public class RootViewModel : PresenterManager
{
    public void ShowCustomer()
    {
        var presenter = ServiceLocator.Current.GetInstance&amp;lt;Customerviewmodel&amp;gt;();
        this.Open(presenter);
    }
}
&lt;/pre&gt;

&lt;span style=&quot;color: #0080c0; font-size: 100%;&quot;&gt;&lt;b&gt;Conclusion&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;What's the catch? How does Caliburn do this? Caliburn uses &lt;em&gt;&lt;a href=&quot;http://caliburn.codeplex.com/Wiki/View.aspx?title=IBinder%20and%20Convention%20over%20Configuration&quot;&gt;Convention over Configuration&lt;/a&gt;&lt;/em&gt; pattern, so if you do things according to the convention you'll end up saving a lot of code. There's always the possibility to change the default behavior too. By complying to these conventions, clearly you'll end up writing less code, but more importantly the code you do write is cleaner, more robust and probably with better testabilty. With the help of &lt;em&gt;Binding Tests&lt;/em&gt; utilities existing in Caliburn, you can test your bindings the easy way, which is some thought for later posts.</description>
            <link>http://www.hightech.ir/SeeSharp/caliburn-less-code</link>
            <guid isPermaLink="true">http://www.hightech.ir/SeeSharp/caliburn-less-code</guid>
            <pubDate>Wed, 02 Sep 2009 11:59:00 GMT</pubDate>
            <category>MVVM</category>
            <category>WPF</category>
            <category>Caliburn</category>
        </item>
        <item>
            <dc:creator>HEskandari</dc:creator>
            <title>MVVM Validation With NHibernate Validator</title>
            <description>&lt;p&gt;&lt;a href=&quot;http://lh6.ggpht.com/_Z5KTIfnfuNs/Sg5-Fzj07XI/AAAAAAAAAOk/0ca2oK3AUjs/s1600-h/MVVM-Validation%5B7%5D.png&quot;&gt;&lt;img style=&quot;border: 0px none ; margin: 5px 20px 0px 10px; display: inline;&quot; title=&quot;MVVM-Validation&quot; alt=&quot;MVVM-Validation&quot; src=&quot;http://lh4.ggpht.com/_Z5KTIfnfuNs/Sg5-LYic86I/AAAAAAAAAOo/YhoCqfl99Bk/MVVM-Validation_thumb%5B5%5D.png?imgmax=800&quot; border=&quot;0&quot; height=&quot;150&quot; width=&quot;294&quot; /&gt;&lt;/a&gt;&lt;/p&gt;  
&lt;p&gt;Simplest way to do Validation in WPF is usually implementing IDataErrorInfo interface, and do the validation in the indexer's getter. It turns out to be ugly and gets out of hand when your model / viewmodel gets a little larger. Implementing the IDataErrorInfo is as simple as this:&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public string this[string propertyName]
{
  get
  {
      //Validate property that is being set,
      //and return an error message if there's
      //any error.

      return null;
  }
}

public string Error
{
  get { return string.Empty; }
}
&lt;/pre&gt;

&lt;p&gt;I intend to use NHibernate Validator attributes to add non-intrusive validation to my ViewModel classes. So you'd just decorate properties of your ViewModel and let WPF and NHibernate Validator do the rest for you. Before we do that, let's create a more elegant way to show the errors by restyling the TextBox control and add an Error Icon and tooltip to it in case of an error existing:&lt;/p&gt;

&lt;pre class=&quot;brush:xml&quot;&gt;
&amp;lt;Style TargetType=&quot;{x:Type TextBox}&quot;&amp;gt;
   &amp;lt;Setter Property=&quot;Validation.ErrorTemplate&quot;&amp;gt;
       &amp;lt;Setter.Value&amp;gt;
           &amp;lt;ControlTemplate&amp;gt;
               &amp;lt;DockPanel LastChildFill=&quot;True&quot;&amp;gt;
                   &amp;lt;Image x:Name=&quot;ErrorIcon&quot; Source=&quot;Images/FieldError.png&quot; DockPanel.Dock=&quot;Right&quot; Width=&quot;16&quot; Height=&quot;16&quot; Margin=&quot;4,0,0,0&quot; /&amp;gt;
                   &amp;lt;Border BorderBrush=&quot;Red&quot; BorderThickness=&quot;1&quot;&amp;gt;
                       &amp;lt;AdornedElementPlaceholder /&amp;gt;
                   &amp;lt;/Border&amp;gt;
               &amp;lt;/DockPanel&amp;gt;
           &amp;lt;/ControlTemplate&amp;gt;
       &amp;lt;/Setter.Value&amp;gt;
   &amp;lt;/Setter&amp;gt;
   &amp;lt;Style.Triggers&amp;gt;
       &amp;lt;Trigger Property=&quot;Validation.HasError&quot; Value=&quot;true&quot;&amp;gt;
           &amp;lt;Setter Property=&quot;ToolTip&quot; Value=&quot;{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}&quot;/&amp;gt;
       &amp;lt;/Trigger&amp;gt;
   &amp;lt;/Style.Triggers&amp;gt;
&amp;lt;/Style&amp;gt;
&lt;/pre&gt;

Now that styles are all set, let's configure NHibenrate Validator's engine on application startup. Nothing fancy, just a straightforeward configuration. We'll use a shared validation engine:&lt;br /&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public void RegisterValidatorEngine()
{
  var config = new NHVConfigurationBase();

  config.Properties[Environment.ApplyToDDL] = &quot;false&quot;;
  config.Properties[Environment.AutoregisterListeners] = &quot;true&quot;;
  config.Properties[Environment.ValidatorMode] = &quot;UseAttribute&quot;;
  config.Properties[Environment.SharedEngineClass] = typeof(ValidatorEngine).FullName;
  config.Mappings.Add(new MappingConfiguration(DomainAssemblyName, null));

  Environment.SharedEngineProvider = new NHibernateSharedEngineProvider();
  Environment.SharedEngineProvider.GetEngine().Configure(config);

  ValidatorInitializer.Initialize(NHibernateConfig);
}
&lt;/pre&gt;

And to make things reusable, why not create a base ViewModel:&lt;br /&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public abstract class ValidatableViewModel : IDataErrorInfo
{
  private readonly ValidatorEngine validation;

  protected ValidatableViewModel()
  {
      validation = Environment.SharedEngineProvider.GetEngine();
  }

  public string this[string propertyName]
  {
      get
      {
          var rules = GetInvalidRules(propertyName);
          if (rules != null &amp;&amp; rules.Count &amp;gt; 0)
          {
              return rules[0].Message;
          }

          return null;
      }
  }

  public string Error
  {
      get { return string.Empty; }
  }

  public IList&lt;InvalidValue&gt; GetInvalidRules(string propertyName)
  {
      var type = this.GetType();

      return validation.ValidatePropertyValue(type, propertyName, GetPropertyValue(type, propertyName));
  }

  public IList&lt;InvalidValue&gt; GetAllInvalidRules()
  {
      return validation.Validate(this);
  }

  private object GetPropertyValue(Type objectType, string properyName)
  {
      return objectType.GetProperty(properyName).GetValue(this, null);
  }
}
&lt;/pre&gt;

&lt;p&gt;The rest is just to inherit the ValidatableViewModel and add necessary attributes to our binded properties. A sample ViewModel containing a Save command, which is invocable only when there's no error on the model and a couple of other business properties would look like this:&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public class NewAccountViewModel : ValidatableViewModel, INotifyPropertyChanged
{
  private string _firstName;
  private string _lastName;
  private string _currentBalance;

  [NotNullNotEmpty]
  public string Firstname
  {
      get { return _firstName; }
      set
      {
          _firstName = value;
          this.Notify(this.PropertyChanged, o =&amp;gt; o.Firstname);
      }
  }

  [NotNullNotEmpty]
  public string Lastname
  {
      get { return _lastName; }
      set
      {
          _lastName = value;
          this.Notify(this.PropertyChanged, o =&amp;gt; o.Lastname);
      }
  }

  [IsNumeric]
  [NotNullNotEmpty]
  public string CurrentBalance
  {
      get { return _currentBalance; }
      set
      {
          _currentBalance = value;
          this.Notify(this.PropertyChanged, o =&amp;gt; o.CurrentBalance);
      }
  }

  public event PropertyChangedEventHandler PropertyChanged = delegate { };

  private ICommand _cmdSave;
  public ICommand SaveCommand
  {
      get
      {
          if (_cmdSave == null)
              _cmdSave = new RelayCommand(Save, CanSave);

          return _cmdSave;
      }
  }

  public void Save()
  {
      MessageBox.Show(&quot;Save&quot;);
  }

  public bool CanSave()
  {
      return GetAllInvalidRules().Count == 0;
  }
}
&lt;/pre&gt;

&lt;pre class=&quot;brush:xml&quot;&gt;
&amp;lt;UserControl x:Class=&quot;Jimba.UI.View.NewAccountView&quot;
  xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
  xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;&amp;gt;
  &amp;lt;StackPanel&amp;gt;
      &amp;lt;StackPanel Orientation=&quot;Horizontal&quot;&amp;gt;
          &amp;lt;Label Width=&quot;100&quot;&amp;gt;Firstname:&amp;lt;/Label&amp;gt;
          &amp;lt;TextBox Text=&quot;{Binding Path=Firstname, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}&quot; /&amp;gt;
      &amp;lt;/StackPanel&amp;gt;

      &amp;lt;StackPanel Orientation=&quot;Horizontal&quot;&amp;gt;
          &amp;lt;Label Width=&quot;100&quot;&amp;gt;Lastname:&amp;lt;/Label&amp;gt;
          &amp;lt;TextBox Text=&quot;{Binding Path=Lastname, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}&quot; /&amp;gt;
      &amp;lt;/StackPanel&amp;gt;

      &amp;lt;StackPanel Orientation=&quot;Horizontal&quot;&amp;gt;
          &amp;lt;Label Width=&quot;100&quot;&amp;gt;Current Balance:&amp;lt;/Label&amp;gt;
          &amp;lt;TextBox Text=&quot;{Binding Path=CurrentBalance, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}&quot; /&amp;gt;
      &amp;lt;/StackPanel&amp;gt;
  &amp;lt;/StackPanel&amp;gt;
&amp;lt;/UserControl&amp;gt;
&lt;/pre&gt;</description>
            <link>http://www.hightech.ir/SeeSharp/mvvm-validation-with-nhibernate</link>
            <guid isPermaLink="true">http://www.hightech.ir/SeeSharp/mvvm-validation-with-nhibernate</guid>
            <pubDate>Sat, 16 May 2009 13:19:00 GMT</pubDate>
            <category>NHibernateValidator</category>
            <category>MVVM</category>
            <category>WPF</category>
        </item>
    </channel>
</rss>
