Category: Tutorial

Mar 31 2011

Thoughts on WPF / MVVM Tutorial

Yesterday I spent a couple of hours going through Karl Shifflet’s In the Box Training for WPF / MVVM.  There is a lot of great things I could say about In the Box format for developer training but for today it will have to suffice to say that it is awesome—mostly because it directly integrates with Visual Studio.  

And Karl REALLY knocked himself out with the content.  Except for a few reasonable WPF pre-reqs, this is “ground-zero” training that does not presume on anything.  

I just wanted to documents some takeaways and thoughts on what I learned so that next time I do  the content (I will very likely go through this training multiple times) I won’t be starting over each time.

I thought I would present this in the form of a brass tacks bulleted/ordered list of the steps I would take to complete an MVVM application.

WARNING – these instruction are ultimately WAY to simplistic and does not represent a REAL way to architect and design an application but should work for me based on what I know.

  • First wireframe your UI / Screens and Interactions using Balsamiq Mockups.
  • Create a WPF project and then create a MainPage view in XAML for each major screen and separate xaml views for each logical component of your UI. 
    • The Views and main form will have “empty” code-behind files except for the boilerplate InitializeComponent().  This is how you know you are doing MVVM instead of a traditional windows app.
    • The bootstrapping of the App will be done later, using an IOC container, in the app startup event after all of the ViewModels are completed .
    • For more on this see the UI Design and Bootstrapping sections of the tutorial.
  • Create your Domain objects.  The classes here are just very simple POCOs (plain old clr objects) with no methods.  I think this is because all of the business logic is in the ViewModel itself.  
    • The POCOs had no methods, only property setters and getters.
    • With the exception of light-weight items used to fill lists, all of the objects inherit from ObservableObject.  ObservableObject is a utility class provided in the tutorial that implements INotifyPropertyChanged which is a core WPF interface for using the WPF property system.
    • For light-weight “listable” items that map to real objects but only have the properties needed to fill the list, you do not need to inherit from Observsable object.
    • If any property members are collections make the collection a generic type of ObservableCollection (i.e. ObservableCollection<Expense> _expenses 😉
    • All of the property setters should call the RaisePropertyChanged method passign the property name as a string argument (i.e. RaisePropertyChanged("Notes") 😉
    • All of the Observable POCO clasess are marked as Serializable.  
    • All of the Observable POCOs had a default constructor with no overloaded cosntructor.
    • The light-weight POCO did have a overloaded constructor that hydrates the object.
  • For data access, create a I<OBECT>Repository interface and a matching class for implementing the interface for each domain object.
    • The interface will have all of your basic DAL stuff.  For example…
    • Event GetById(Guid id);
      Int32 Remove(Event @event);
      Int32 Save(Event @event);
      Int32 GetCount();
      Event Create();

    • The example interface also had a method for getting a collection of light-weight IEnumberable (i.e.  IEnumerable<EventSearchResult> GetSearchResults();)
    • The repository implementation will have a private field that keeps a list of objects of the type (i.e. readonly List<Event> _events;)
    • The constructor of the implementation hydrates the POCOs and adds them to the list.  This is great for swapping out DALs at any time and unit testing.
    • Of course, you add implementation for all of the interface defs.  (I wonder what an implementation that actually hits the database would look like?)
  • Create a ViewModel for each major Screen. 
    • A ViewModel is the DataTemplate for the screen and all of the child views/components of that screen. 
    • The startup event of the application wires the main screens (views) to the ViewModel as the DataTemplate.
    • The ViewModels also inherit from ObservableObject.
    • As needed, the ViewModel contains instances of all relevant Domain POCOs and light-weight POCOs and collectionSleeping half-moon of POCOs as needed..  
    • It may implement properties that track the current or active or selected POCO instance.
    • The ViewModel will also have private, read-only fields that hold references to the repository objects that it needs (readonly IEventRepository _repository;)
    • As with the Domain POCOs, the property setters call the RaisePropertyChanged methods. 
    • Some of the property setters can set the Acive / Selected object (i.e. RecordSelected(value);)
    • View and view model interactions are handled through the create of ICommand objects.  The tutorial provides and implementation of this in the RelayCommand class which is what the ICommand method construct and return.   He goes into some length to explain why he implemented this ICommand instead of using the built-in DelegateCommand.
    • View / ViewModel interactions can also be done by defining “behaviours” in the view but this is not explained or demonstrated in the turtorial.
    • Different strategies for implementing and using ICommands are demonstrated.
    • The tutorial also gives helpful information on how to invoke dialog boxes from the ViewModels. 
    • The ViewModel also implements Can<COMMAND>Execute methods that have to be very fast along with void <COMMAND>Execute methods that interact with the collections and repositories to do CRUD operations on the data.
    • A single ViewModel can serve as the DataTemplate for all of the view and child views/components. 

IMPORTANT – PROBABLY THE MOST important thing to understand and master in the tutorial is the page call View-View Model Interactions.  Maybe a future post will explore that in greater details.  But below are the relevant topics.

EventEditView Bindings

The below XAML snippet from EventEditView.xaml illustrates one technique for binding UI controls to model objects exposed from a view model.

The DataContext for this view is the view model. ActiveEvent is a property on the view model. Each of the controls “dot in” to the property on the model object they want to bind to.

<TextBox Text="{Binding Path=ActiveEvent.Title, Mode=TwoWay}" />

<TextBox Text="{Binding Path=ActiveEvent.Location, Mode=TwoWay}"/>

<DatePicker Text="{Binding Path=ActiveEvent.EventDate, Mode=TwoWay}"/>

<TextBox Text="{Binding Path=ActiveEvent.Notes, Mode=TwoWay}"/>

<DataGrid ItemsSource="{Binding Path=ActiveEvent.Expenses}" .../>

It is also possible to assign the ActiveEvent instance to a parent container’s DataContext like a Grid control and then the child controls would not have to “dot in” since their DataContext root would be the ActiveEvent instance instead of the view model instance.


The MainWindowViewModel exposes the following five ICommand properties; the EventEditView data binds to those properties.

public ICommand DeleteCommand {

get { return new RelayCommand(DeleteExecute, CanDeleteExecute); }


public ICommand SaveCommand {

get { return new RelayCommand(SaveExecute, CanSaveExecute); }


public ICommand CancelCommand {

get { return new RelayCommand(CancelExecute, CanCancelExecute); }


public ICommand ThrowCommand {

get { return new RelayCommand(ThrowExecute, CanThrowExecute); }


public ICommand NewCommand {

get { return new RelayCommand(NewExecute); }


<StackPanel Orientation="Horizontal" Grid.Row="5" Grid.ColumnSpan="2">

<Button Content="New" Command="{Binding Path=NewCommand}" />

<Button Content="Save" Command="{Binding Path=SaveCommand}" />

<Button Content="Cancel" Command="{Binding Path=CancelCommand}" />

<Button Content="Delete" Command="{Binding Path=DeleteCommand}" />

<Button Content="Throw" Command="{Binding Path=ThrowCommand}" />


Jul 16 2010

Mercurial Workflow and Tutorial

I just read Joel Spolsky's outstanding introductory tutorial to Mercurial. Mercurial is a distributed Version Control System.  You can read it at Here is my glossary and workflow description from the tutorial for mercurial.


  1. If you haven’t done so in a while, get the latest version that everyone else is working off of:
    • hg pull
    • hg up
  2. Make some changes
  3. Commit them (locally)
  4. Repeat steps 2-3 until you’ve got some nice code that you’re willing to inflict on everyone else
  5. When you’re ready to share:
    • hg pull to get everyone else’s changes (if there are any)
    • hg merge to merge them into yours
    • test! to make sure the merge didn’t screw anything up
    • hg commit (the merge)
    • hg push


hg help hg init                                    Create a repo.  Be in the directory you want to source. hg add                                  adds files in directory to repo hg commit (com)              Commit changes to local repo   -m include a message in quotes hg log                                    see changes since last commit.  –P shows changes that just arrived. hg revert                             revert changes to last changeset   --all (revert all files) hg status                              list files that have change hg diff   <file>                    show changes in a file hg cat                                    print file to screen           -r N <file> (where N  is a changeset #) print that version. hg update (up)  -r N          N is changeset #.  Changes your working set to that revision.  With no number goes to latest. hg serve                                 Share the repository in the built in web server (port 8000 default) hg clone                                 clone the repository    hg clone <url/path-to-repo> <new folder name> hg push                                  Pushes changes from local repo to central repo hg outgoing (out)               Lists changes that are waiting to be sent to central repo hg incoming (in)                  Lists changes that are waiting to be sent from central repo to local repo hg merge                               combines changeset into new tip.  Then use commit to commit merge to repo.  If merge fails you can revert it.  On success you can commit it. hg parent                              tells you what changeset your are working in.   Pull does not change your changeset so a pull is always safe. hg rollback                            Undoes one commit but only if it hasn’t been pushed. (Revert changes to the last commit whereas rollback reverts the last commit.) hg paths                                 default = shows the path to the default repository that a push will use. Hg backout –r N --merge              undoes a particular  changeset from the working directory hg tag <name>                    Give current changeset a name.  Then you can use it for N.


If you see when doing a push…
abort: push creates new remote heads!
(did you forget to merge? use push -f to force) …then you need to do a Pull then do a Push