Databinding to the VariableSizedWrapGrid in Windows 8 Metro

This article describes how to implement data binding and using variable sized cells in a VariableSizedWrapGrid control in a Windows 8 Metro application, Customer Preview release. The VariableSizedWrapGrid control exposes the ColumnSpan and RowSpan attached properties. These allow to specify the number of columns and rows an element should span. He're how the sample project looks like: According to the official documentation the ColumnSpan and RowSpan values are interpreted by the most immediate parent VariableSizedWrapGrid element from where the value is set. So let's say we have a Thing class (I couldn't find a better name) with a Width property that contains the relative width (i.e. the number of columns to span). Our viewmodel exposes a list of Things that we want to show, and allows binding to the selected Thing: public class MainPageViewModel : BindableBase { public List<Thing> Things { get { List<Thing> results = new List<Thing>(); results.Add(new Thing() { Name = "Beer", Height = 1, Width = 1, ImagePath = @"/Assets/Images/beer.jpg" }); results.Add(new Thing() { Name = "Hops", Height = 2, Width = 2, ImagePath = @"/Assets/Images/hops.jpg" }); results.Add(new Thing() { Name = "Malt", Height = 1, Width = 2, ImagePath = @"/Assets/Images/malt.jpg" }); results.Add(new Thing() { Name = "Water", Height = 1, Width = 2, ImagePath = @"/Assets/Images/water.jpg" }); results.Add(new Thing() { Name = "Yeast", Height = 1, Width = 1, ImagePath = @"/Assets/Images/yeast.jpg" }); results.Add(new Thing() { Name = "Sugar", Height = 2, Width = 2, ImagePath = @"/Assets/Images/sugars.jpg" }); results.Add(new Thing() { Name = "Herbs", Height = 2, Width = 1, ImagePath = @"/Assets/Images/herbs.jpg" }); // And so on, and so forth ... return results; } } private Thing selectedThing; public Thing SelectedThing { get { return selectedThing; } set { this.SetProperty(ref selectedThing, value); } } } The viewmodel derives from BindableBase, a helper class provided by the new Visual Studio templates that implements property changed notification using the new C# 5 CallerMemberName attribute. The viewmodel is attached to the view in XAML. I'm glad that this finally works! In the Developer Preview we needed to do this in the code behind: <Page.DataContext> <local:MainPageViewModel /> </Page.DataContext> Now the VariableSizedWrapGrid control is just a Panel, not an ItemsControl, so in a databound scenario we also need a GridView. In theory the next configuration would work. We simply attach the properties to the item data template of the GridView: <GridView ItemsSource="{Binding Things}"> <GridView.ItemTemplate> <DataTemplate> <Grid VariableSizedWrapGrid.ColumnSpan="{Binding Width}" > <!-- Insert Item Data Template Details Here --> <!-- ... --> </Grid> </DataTemplate> </GridView.ItemTemplate> <GridView.ItemsPanel> <ItemsPanelTemplate> <VariableSizedWrapGrid /> </ItemsPanelTemplate> <GridView.ItemsPanel> </GridView> This does not work. When data binding, each item is wrapped in a GridViewItem control, which apparently swallows the attached properties. So far for the theory. In practice, the only way to make the scenario work is to create a GridView child class and override the PrepareContainerForItemOverride method. The control class would look like this: public class VariableGridView : GridView { protected override void PrepareContainerForItemOverride(DependencyObject element, object item) { var viewModel = item as Thing element.SetValue(VariableSizedWrapGrid.ColumnSpanProperty, viewModel.Width); element.SetValue(VariableSizedWrapGrid.RowSpanProperty, viewModel.Height); base.PrepareContainerForItemOverride(element, item); } } Of course we're not going to build a specialized GridView class for each model in our application, so it makes sense to define an interface: public interface IResizable { int Width { get; set; } int Height { get; set; } } Here's a reusable version of the GridView child. It only depends on the interface: public class VariableGridView : GridView { protected override void PrepareContainerForItemOverride(DependencyObject element, object item) { var viewModel = item as IResizable; element.SetValue(VariableSizedWrapGrid.ColumnSpanProperty, viewModel.Width); element.SetValue(VariableSizedWrapGrid.RowSpanProperty, viewModel.Height); base.PrepareContainerForItemOverride(element, item); } } And here's the Thing, the whole Thing, and nothing but the Thing: public class Thing : IResizable { public string Name { get; set; } public string ImagePath { get; set; } public int Width { get; set; } public int Height { get; set; } public ImageSource Image { get { return new BitmapImage(new Uri("ms-appx://" + this.ImagePath)); } } } In the main page, we just replace GridView by the custom class: <local:VariableGridView ItemsSource="{Binding Things}"> <local:VariableGridView.ItemTemplate> <DataTemplate> <Grid> <!-- Insert Item Data Template Details Here --> <!-- ... --> </Grid> </DataTemplate> </local:VariableGridView.ItemTemplate> <local:VariableGridView.ItemsPanel> <ItemsPanelTemplate> <VariableSizedWrapGrid /> </ItemsPanelTemplate> <local:VariableGridView.ItemsPanel> </local:VariableGridView> Tadaa ! Here's the source code. It was written with Visual Studio Express 11 Beta, for the Windows 8 Consumer Preview: U2UConsult.Metro.VariableSizedWrapGridSample.zip (951,87 kb) Enjoy !  

Using Grouped GridView Navigation in Windows 8 Metro

This article describes how you can navigate through large amounts of data in a Metro application, on the Windows 8 Consumer Preview. We'll use a grouped and a non-grouped GridViews, a SemanticZoom, a WrapGrid, and a VariableSizedWrapGrid control. The app was built with the brand new Visual Studio 11 Beta. By the way, here's how that beta looks like: Cool, isn't it ? The Data The app will display a small collection of Belgian beers. In real life Belgian beer has a wonderful aroma, an excellent flavor and ditto mouthfeel. In the demo app Belgian beer just has a name, a category, and an image. Here's how the base list is created: /// <summary> /// Returns a list of some Belgian beers. /// </summary> public static IEnumerable<BelgianBeer> BelgianBeers { get { List<BelgianBeer> result = new List<BelgianBeer>(); result.Add(new BelgianBeer() { Name = "Saison 1900", Category = "Belgian Saison", ImagePath = "Assets/Images/1900.jpg" }); // And we have plenty more of these ... result.Add(new BelgianBeer() { Name = "Slaapmutske Tripel", Category = "Belgian Strong Ale", ImagePath = "Assets/Images/Slaapmutske.jpg" }); result.Add(new BelgianBeer() { Name = "Westmalle Tripel", Category = "Belgian Strong Ale", ImagePath = "Assets/Images/Westmalle.jpg" }); return result; } } Here's how this beer collection will be displayed by the app. It will nicely group the individual beers by their category: The data will be pulled from a CollectionViewSource that we define in XAML: <UserControl.Resources> <CollectionViewSource x:Name="cvs1" IsSourceGrouped="True" /> </UserControl.Resources> We're working in grouped mode here, so don't forget to set the IsSourceGrouped property. Since yesterday (the day the Consumer Preview was launched) the collection view source is happy with the result of a grouped LINQ query: /// <summary> /// Returns the same list of beers, grouped by category. /// </summary> public static IEnumerable<object> BelgianBeersByCategory { get { var query = from item in BelgianBeers orderby item.Category group item by item.Category into g select g; return query; } } When the main view is created, we populate the collection view source with the result of that LINQ query: this.cvs1.Source = MainViewModel.BelgianBeersByCategory; Displaying grouped data in a GridView The collection view source will be used as items source for a GridView. That GridView will do all the formatting through its many templates: <GridView ItemsSource="{Binding Source={StaticResource cvs1}}" IsSwipeEnabled="True"> <GridView.ItemTemplate> <DataTemplate> <!-- Insert Item Data Template Here --> <!-- ... --> </DataTemplate> </GridView.ItemTemplate> <GridView.ItemsPanel> <ItemsPanelTemplate> <!-- Insert Panel Template Here --> <!-- ... --> </ItemsPanelTemplate> </GridView.ItemsPanel> <GridView.GroupStyle> <GroupStyle> <GroupStyle.HeaderTemplate> <DataTemplate> <!-- Insert Group Header Template Here --> <!-- ... --> </DataTemplate> </GroupStyle.HeaderTemplate> <GroupStyle.Panel> <ItemsPanelTemplate> <!-- Insert Group Panel Template Here --> <!-- ... --> </ItemsPanelTemplate> </GroupStyle.Panel> </GroupStyle> </GridView.GroupStyle> </GridView> Here's a graphical overview of the templates in a grouped GridView: The Item Data Template (blue rectangle) describes how each item (beer) will be represented: <StackPanel Margin="8"> <TextBlock Text="{Binding Name}" Foreground="White" /> <Image Source="{Binding Image}" Height="145" Width="190" Stretch="UniformToFill" /> </StackPanel> The Item Panel Template (purple rectangle) describes how the groups (beer categories) will be arranged. I went for a horizontal stackpanel, so scrolling or swiping sideways will move you through the categories. Read on to discover why this was a bad idea: <StackPanel Orientation="Horizontal" /> In grouped mode you have to fill the GroupStyle property. The Group Header Template (red rectangle) describes how the group header (beer category header) looks like: <TextBlock Text="{Binding Key}" Foreground="Gold" /> The Group Panel Template (yellow rectangle) describes the arrangement of items (beers) in each group (beer category). In our app, the items are displayed in a VariableSizedWrapGrid. That's an advanced version of the old WrapPanel: elements are positioned in sequential order and go to the next row or column if there isn’t enough room. This control allows me to display some of the beers in a different size, by binding to the RowSpan and ColumnSpan properties. I'm not going to use these, so the panel will behave like just an ordinary WrapPanel: <VariableSizedWrapGrid Orientation="Vertical" /> Semantic Zoom We're merely displaying 21 beers here. What happens if you have a very large dataset ? Some of the local shops here have 300,  500 or even over 800 Belgian beers  ! You will get very thirsty when scrolling to the last category... Well, I have good news for you: there's a new control that allows you to jump easily into a specific group (beer category) in the data. It's called the SemanticZoom, the control that was formerly known as JumpViewer. This control allows you configure and combine two GridViews or anything else that implements the ISemanticZoomInformation interface: a details view -ZoomedInView- and a summary view -ZoomedOutView-. You can easily navigate between these two. The SemanticZoom is highly customizable, as you can see in the Guidelines for Semantic Zoom. In our app, we're using the beer label GridView as details view. The summary view looks like this:   The summary view is also a GridView, but it's populated directly with the list of beer categories. Its item template is just a TextBlock: <TextBlock Text="{Binding Group.Key}" Foreground="Gold" /> The items are arranged in a regular WrapGrid: <WrapGrid MaximumRowsOrColumns="4" HorizontalAlignment="Center" VerticalAlignment="Center" /> You call the summary view via a pinch gesture in the details view. In the summary view, tapping on a category brings you directly to the corresponding group in the detailed view. At least, that's were you should return to. In the Developer Preview this code worked fine, but the Consumer Preview seems to always navigate to the first group. Anyway, the issue was reported... ... and solved. Apparently the item panel template (purple rectangle) has to be a WrapGrid: <WrapGrid Orientation="Vertical" MaximumRowsOrColumns="1" /> Here's an overview of the semantic zoom structure: <SemanticZoom x:Name="semanticZoom"> <!-- Details View --> <SemanticZoom.ZoomedInView> <GridView ItemsSource="{Binding Source={StaticResource cvs1}}" IsSwipeEnabled="True"> <!-- Configure Details View Here --> <!-- ... --> </GridView> </SemanticZoom.ZoomedInView> <!-- Summary View --> <SemanticZoom.ZoomedOutView> <GridView> <!-- Configure Summary View Here --> <!-- ... --> </GridView> </SemanticZoom.ZoomedOutView> </SemanticZoom> Both GridViews use the same data, but you have to glue them together programmatically: (this.semanticZoom.ZoomedOutView as ListViewBase).ItemsSource = cvs1.View.CollectionGroups; Here's the app's tile after deployment, next to the highly addictive Metro version of Cut the Rope (that's an old screenshot by the way: I cut many more ropes since then). It's another VariableSizedWrapGrid in action: Source Code Here's the source code, it was written with VS11 beta for the Windows 8 Consumer Preview: U2UConsult.WinRT.GridViewSample.zip (2,72 mb) Enjoy ... and Cheers !  

Hello ObservableVector, goodbye ObservableCollection

WARNING: Article content applies to Windows 8 Developer Preview only. ObservableCollection<T> is alive and kicking in the current release. WinRT, the new Windows 8 runtime for Metro applications, introduces a new interface for collection change notification. IObservableVector<T> replaces ye olde INotifyCollectionChanged. The ObservableCollection class still exists, you can continue to use it. Unfortunately its collection change events are ignored by the WinRT framework. I can assure you that this will give cross-platform developers a serious headache - or worse. Don't say I didn't warn you: The IObservableVector<T> interface is defined, but the framework does not contain an implementation yet. There's no built-in collection that raises the new VectorChanged events. The fresh cocoon framework on CodePlex contains an implementation of ObservableVector<T>. Unsurprisingly it's a light-weight wrapper around an IList<T>. The class is described here. Here's my own version of the class - I just adapted it to my property change notification mechanism: namespace Mvvm { using System.Collections.Generic; using System.Collections.ObjectModel; using Windows.Foundation.Collections; using Windows.UI.Xaml.Data; /// <summary> /// IObservableVector<T> implementation. /// </summary> public class ObservableVector<T> : Collection<T>, INotifyPropertyChanged, IObservableVector<T> { // *** Events *** public event PropertyChangedEventHandler PropertyChanged; public event VectorChangedEventHandler<T> VectorChanged; // *** Constructors *** public ObservableVector() : base() {} public ObservableVector(IList<T> list) : base(list) {} // *** Protected Methods *** protected override void ClearItems() { base.ClearItems(); this.PropertyChanged.Raise(this, o => o.Count); this.PropertyChanged.Raise(this, o => o.Items); this.OnVectorChanged(CollectionChange.Reset, 0); } protected override void InsertItem(int index, T item) { base.InsertItem(index, item); this.PropertyChanged.Raise(this, o => o.Count); this.PropertyChanged.Raise(this, o => o.Items); this.OnVectorChanged(CollectionChange.ItemInserted, (uint)index); } protected override void RemoveItem(int index) { base.RemoveItem(index); this.PropertyChanged.Raise(this, o => o.Count); this.PropertyChanged.Raise(this, o => o.Items); this.OnVectorChanged(CollectionChange.ItemRemoved, (uint)index); } protected override void SetItem(int index, T item) { base.SetItem(index, item); this.PropertyChanged.Raise(this, o => o.Items); this.OnVectorChanged(CollectionChange.ItemChanged, (uint)index); } // *** Event Handlers *** protected void OnVectorChanged(CollectionChange collectionChange, uint index) { this.OnVectorChanged(new VectorChangedEventArgs(collectionChange, index)); } protected virtual void OnVectorChanged(IVectorChangedEventArgs e) { if (this.VectorChanged != null) this.VectorChanged(this, e); } // *** Private Sub-classes *** private class VectorChangedEventArgs : IVectorChangedEventArgs { // *** Fields *** private readonly CollectionChange collectionChange; private readonly uint index; // *** Constructors *** public VectorChangedEventArgs(CollectionChange collectionChange, uint index) { this.collectionChange = collectionChange; this.index = index; } // *** Properties *** public CollectionChange CollectionChange { get { return this.collectionChange; } } public uint Index { get { return this.index; } } } } } I consider this temporary code - I assume that next versions of WinRT will have a native version of ObservableVector<T>. I built a small sample application around to demonstrate the usage of the class in a MVVM application: all the work is done through data and command bindings. The app just manages two collections of Dragons: 'All Dragons' and 'Favorites'. The selected Dragon in each ListBox can be moved to the other collection by clicking the buttons in the middle. Here's how the app looks like: By the way, in the current version of WinRT -Developer Preview- the collection changed events are only handled if T is object, so you have to define the collection as follows: public ObservableVector<object> Dragons { get; set; } For any other type -like ObservableVector<string> or ObservableVector<Dragon>- the change events will be simply ignored by the binding mechanism. That's another headache. You use the class exactly the same way as good old ObservableCollection, e.g. as ItemsSource to a an ItemControl: <ListBox DataContext="{Binding}" ItemsSource="{Binding Dragons}" SelectedItem="{Binding SelectedDragon, Mode=TwoWay}" /> Here's the full source code, it's built with Visual Studio 11 Developer Preview: U2UConsult.WinRT.ObservableVector.Sample.zip (47,83 kb) Enjoy!

Databinding to an enumeration in WinRT

This article demonstrates how to databind a radiobutton to an enumeration element, in a WinRT Metro application. The MVVM viewmodel has a property of an enumeration type, which is bound to the IsChecked property of some radiobuttons. A value converter compares the value from the viewmodel with an enumeration element that is provided as parameter to the converter. The Convert method returns true if both match, the ConvertBack method updates the bound value when the radiobutton is clicked or tapped. Here's a screenshot of the attached sample application. The radiobuttons are bound to the CarColor property -an enumeration- of the viewmodel. The Vote-button updates that same property through a command: The converter is much more complex than the WPF version from my previous article, it's even more complex than its corresponding Silverlight version that you can find here. Here's a list of reasons why the implementation was not so straightforward: The x:Static markup extension is not allowed in a Metro application, Binding.DoNothing does not exist in WinRT, and unlike in WPF or Silverlight, the converter receives the enumeration value as an integer instead of a string. When I observed all of this, my first reaction was AARGH!!! Don't worry: it was not a call of anger and frustration. In the noble Antwerp language aerg just means 'this is bad'. Non-believers: just follow this link. As a result, the converter is much more complex than expected. It reconstructs the enumeration parameter from the binding expression by string parsing and reflection. Here's how it looks like: namespace U2UConsult.WinRT.Converters { using System; using System.Globalization; using Windows.UI.Xaml; using Windows.UI.Xaml.Data; /// <summary> /// Converts an enum to a boolean. /// </summary> public class EnumToBooleanConverter : IValueConverter { /// <summary> /// Compares the bound value with an enum param. Returns true when they match. /// </summary> public object Convert(object value, string typeName, object parameter, string language) { try { string parm = parameter.ToString(); int lastDot = parm.LastIndexOf("."); string enumName = parm.Substring(0, lastDot); string enumValue = parm.Substring(lastDot + 1); Type t = Type.GetType(enumName); string s = Enum.GetName(t, value); object b = Enum.Parse(t, enumValue); return b.ToString() == s; } catch (Exception) { return false; } } /// <summary> /// Converts the boolean back into an enum. /// </summary> public object ConvertBack(object value, string typeName, object parameter, string language) { try { string parm = parameter.ToString(); int lastDot = parm.LastIndexOf("."); string enumName = parm.Substring(0, lastDot); string enumValue = parm.Substring(lastDot + 1); Type t = Type.GetType(enumName); object b = Enum.Parse(t, enumValue); return b; } catch (Exception) { return DependencyProperty.UnsetValue; } } } } In your application, all you need to do is create an enumeration: public enum CarColor { Yellow, Red, Pink, Black } In the viewmodel, create a property of the enumeration type: private CarColor carColor = CarColor.Black; public event PropertyChangedEventHandler PropertyChanged; public CarColor CarColor { get { return carColor; } set { this.carColor = value; this.PropertyChanged.Raise(this, (o) => o.CarColor); } } The propertychanged notification makes sure that the radiobutton follows all modifications of the property. In the view, define the converter instance as a resource in XAML: <UserControl.Resources> <cv:EnumToBooleanConverter x:Key="EnumToBooleanConverter" /> </UserControl.Resources> Bind the viewmodel's CarColor property to the Ischecked property of each radioButton. The enumeration value is provided as parameter to the converter with its fully qualified name. Also, you have to set the binding mode to TwoWay, and make sure that every radiobutton has its own GroupName. This is because we can't use Binding.DoNothing in the IValueConverter.ConvertBack Method. We always have to return the parameter, or DependencyProperty.UnsetValue. Both (re-)trigger all radiobuttons in the same group and that's not what we want; more info here. Here's the full binding syntax in XAML: <RadioButton Content="Giallo Modena" GroupName="Yellow" IsChecked="{Binding CarColor, Mode=TwoWay, Converter={StaticResource EnumToBooleanConverter}, ConverterParameter=U2UConsult.WinRT.DataBindingToEnum.ViewModels.CarColor.Yellow}" /> <RadioButton Content="Rosso Corsa" GroupName="Red" IsChecked="{Binding CarColor, Mode=TwoWay, Converter={StaticResource EnumToBooleanConverter}, ConverterParameter=U2UConsult.WinRT.DataBindingToEnum.ViewModels.CarColor.Red}" /> <RadioButton Content="Rosa Insapora" GroupName="Pink" IsChecked="{Binding CarColor, Mode=TwoWay, Converter={StaticResource EnumToBooleanConverter}, ConverterParameter=U2UConsult.WinRT.DataBindingToEnum.ViewModels.CarColor.Pink}" /> <RadioButton Content="Matte Nero" GroupName="Black" IsChecked="{Binding CarColor, Mode=TwoWay, Converter={StaticResource EnumToBooleanConverter}, ConverterParameter=U2UConsult.WinRT.DataBindingToEnum.ViewModels.CarColor.Black}" /> This solution is more error-prone and definitely slower than the WPF version, but it does the job. That's the good news. I also have bad news: the pink Ferrari photo is NOT photoshopped, aerg. Anyway, here's the full source code. It was developed with Visual Studio 11 Developer Preview: U2UConsult.WinRT.DataBindingToEnum.zip (364,11 kb) Enjoy!

A core MVVM framework for WinRT

This article presents a core MVVM framework for building Metro applications on the WinRT runtime. With the WinRT runtime, Microsoft launched its fourth XAML-based platform - after WPf, Silverlight, and the Windows Phone. It's the fourth time they strongly advice development teams all over the world to get the maximum out of the power of XAML bindings, hence use the MVVM pattern in their applications. Strangely enough it's also the fourth time that they ship a runtime without the basic support for that same pattern. So it's up to the developers community to fill the gap. The gap will be filled rapidly. While Microsoft Patterns & Practice's Prism team is still hesitating, Laurent Bugnion with his MVVM Light Toolkit  and Rob Eisenberg with Caliburn Micro are definitely going for a WinRT version of their popular frameworks. But we're not going to sit and wait for these frameworks, are we? We want to start developing MVVM applications (in Metro-speak they're called 'apps') here and now. In my ever humble opinion, the following three are the core requirements for using MVVM in an application : Raising the PropertyChanged event should be easy and typesafe. Defining a bindable command in a ViewModel should be easy and typesafe. Messaging between components should be easy and typesafe, and not create memory leaks.   I gleaned a core MVVM-framework with just three files - one for each requirement: The namespace is Mvvm, so you can start each source code file with 'using Mvvm;'. Your manager will be impressed. Change Notification Most frameworks provide a base class that implements INotifyPropertyChanged. I'm a bit reluctant to use a scarse resource like inheritance- for such a triviality like just raising a standard event. Extension methods are much more flexible: namespace Mvvm { using System; using System.Collections.Generic; using System.Linq.Expressions; using Windows.UI.Xaml.Data; /// <summary> /// Generic extension methods used by the framework. /// </summary> public static class ExtensionMethods { /// <summary> /// Raises the PropertyChanged event. /// </summary> public static void Raise<T, P>(this PropertyChangedEventHandler pc, T source, Expression<Func<T, P>> pe) { if (pc != null) { pc.Invoke(source, new PropertyChangedEventArgs(((MemberExpression)pe.Body).Member.Name)); } } /// <summary> /// Raises the PropertyChanged event for all properties. /// </summary> public static void RaiseAll<T>(this PropertyChangedEventHandler pc, T source) { if (pc != null) { pc.Invoke(source, new PropertyChangedEventArgs(string.Empty)); } } } } Here's how a typical property looks like in a viewmodel or a model that implements INotifyPropertyChanged. Broadcasting a property value change is easy, ànd you get Intellisense support: private string message public string Message { get { return this.message; } set { this.message = value; this.PropertyChanged.Raise(this, o => o.Message); } } It also definitely makes a good candidate for a code snippet... Command binding Most frameworks have an implementation of ICommand to be used specifically in viewmodels. Microsoft's RoutedCommand makes no sense there. Caliburn uses a radically different paradigm based on triggers and actions - the result is the same but it's further away from MVVM. The ICommand implementations in Prism and MVVM Light Toolkit have a constructor with just delegates for the Executed and CanExecute members. I prefer the RelayCommand implementation of the MVVM Light Toolkit, but I also prefer to call it DelegateCommand (sorry, Laurent) - the Prism terminology. It's easy to use and it comes with a generic version: namespace Mvvm { using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Windows.UI.Xaml.Input; using EventHandler = Windows.UI.Xaml.EventHandler; public class DelegateCommand : ICommand { private readonly Action _execute; private readonly Func<bool> _canExecute; /// <summary> /// Initializes a new instance of the DelegateCommand class that /// can always execute. /// </summary> /// <param name="execute">The execution logic.</param> /// <exception cref="ArgumentNullException">If the execute argument is null.</exception> public DelegateCommand(Action execute) : this(execute, null) { } /// <summary> /// Initializes a new instance of the DelegateCommand class. /// </summary> /// <param name="execute">The execution logic.</param> /// <param name="canExecute">The execution status logic.</param> /// <exception cref="ArgumentNullException">If the execute argument is null.</exception> public DelegateCommand(Action execute, Func<bool> canExecute) { if (execute == null) { throw new ArgumentNullException("execute"); } _execute = execute; _canExecute = canExecute; } /// <summary> /// Occurs when changes occur that affect whether the command should execute. /// </summary> public event EventHandler CanExecuteChanged; /// <summary> /// Raises the <see cref="CanExecuteChanged" /> event. /// </summary> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate", Justification = "This cannot be an event")] public void RaiseCanExecuteChanged() { var handler = CanExecuteChanged; if (handler != null) { handler(this, EventArgs.Empty); } } /// <summary> /// Defines the method that determines whether the command can execute in its current state. /// </summary> /// <param name="parameter">This parameter will always be ignored.</param> /// <returns>true if this command can be executed; otherwise, false.</returns> [DebuggerStepThrough] public bool CanExecute(object parameter) { return _canExecute == null ? true : _canExecute(); } /// <summary> /// Defines the method to be called when the command is invoked. /// </summary> /// <param name="parameter">This parameter will always be ignored.</param> public void Execute(object parameter) { if (CanExecute(parameter)) { _execute(); } } } } Here's how to use the DelegateCommand. The ViewModel defines a command by providing just delegates, and provides implementations: public ICommand UpdateTextCommand { get { return new DelegateCommand(this.UpdateTextCommand_Executed); } } private void UpdateTextCommand_Executed() { // Command Logic }   The View can bind to that command in XAML, no code-behind is needed: <Button Content="Update Text" Command="{Binding UpdateTextCommand}" /> Event Aggregation In an application that consists of different loosely-coupled components that need to publish and subscribe to events, it's not a good idea to rely on regular .NET events. More info can be found here. A so-called event aggregator is a much better solution. Prism's event aggregator may be the most powerful on the market, but the one from Caliburn Micro is easier to extract out of its framework. I just added the singleton pattern because I don't want to introduce an Inversion-of-Control container and bootstrappers in my three-file-framework. Here's the full code of the Event Aggregator: namespace Mvvm { using System; using System.Collections.Generic; using System.Linq; using System.Reflection; /// <summary> /// A marker interface for classes that subscribe to messages. /// </summary> public interface IHandle { } /// <summary> /// Denotes a class which can handle a particular type of message. /// </summary> /// <typeparam name = "TMessage">The type of message to handle.</typeparam> public interface IHandle<TMessage> : IHandle { /// <summary> /// Handles the message. /// </summary> /// <param name = "message">The message.</param> void Handle(TMessage message); } /// <summary> /// Enables loosely-coupled publication of and subscription to events. /// </summary> public interface IEventAggregator { /// <summary> /// Gets or sets the default publication thread marshaller. /// </summary> /// <value> /// The default publication thread marshaller. /// </value> Action<System.Action> PublicationThreadMarshaller { get; set; } /// <summary> /// Subscribes an instance to all events declared through implementations of <see cref = "IHandle{T}" /> /// </summary> /// <param name = "instance">The instance to subscribe for event publication.</param> void Subscribe(object instance); /// <summary> /// Unsubscribes the instance from all events. /// </summary> /// <param name = "instance">The instance to unsubscribe.</param> void Unsubscribe(object instance); /// <summary> /// Publishes a message. /// </summary> /// <param name = "message">The message instance.</param> /// <remarks> /// Uses the default thread marshaller during publication. /// </remarks> void Publish(object message); /// <summary> /// Publishes a message. /// </summary> /// <param name = "message">The message instance.</param> /// <param name = "marshal">Allows the publisher to provide a custom thread marshaller for the message publication.</param> void Publish(object message, Action<System.Action> marshal); } /// <summary> /// Enables loosely-coupled publication of and subscription to events. /// </summary> public class EventAggregator : IEventAggregator { /// <summary> /// The default thread marshaller used for publication; /// </summary> public static Action<System.Action> DefaultPublicationThreadMarshaller = action => action(); private static IEventAggregator instance; readonly List<Handler> handlers = new List<Handler>(); /// <summary> /// Initializes a new instance of the <see cref = "EventAggregator" /> class. /// </summary> public EventAggregator() { PublicationThreadMarshaller = DefaultPublicationThreadMarshaller; } /// <summary> /// Gets the singleton instance. /// </summary> public static IEventAggregator Instance { get { if (instance == null) { instance = new EventAggregator(); } return instance; } } /// <summary> /// Gets or sets the default publication thread marshaller. /// </summary> /// <value> /// The default publication thread marshaller. /// </value> public Action<System.Action> PublicationThreadMarshaller { get; set; } /// <summary> /// Subscribes an instance to all events declared through implementations of <see cref = "IHandle{T}" /> /// </summary> /// <param name = "instance">The instance to subscribe for event publication.</param> public virtual void Subscribe(object instance) { lock (handlers) { if (handlers.Any(x => x.Matches(instance))) return; handlers.Add(new Handler(instance)); } } /// <summary> /// Unsubscribes the instance from all events. /// </summary> /// <param name = "instance">The instance to unsubscribe.</param> public virtual void Unsubscribe(object instance) { lock (handlers) { var found = handlers.FirstOrDefault(x => x.Matches(instance)); if (found != null) handlers.Remove(found); } } /// <summary> /// Publishes a message. /// </summary> /// <param name = "message">The message instance.</param> /// <remarks> /// Does not marshall the the publication to any special thread by default. /// </remarks> public virtual void Publish(object message) { Publish(message, PublicationThreadMarshaller); } /// <summary> /// Publishes a message. /// </summary> /// <param name = "message">The message instance.</param> /// <param name = "marshal">Allows the publisher to provide a custom thread marshaller for the message publication.</param> public virtual void Publish(object message, Action<System.Action> marshal) { Handler[] toNotify; lock (handlers) toNotify = handlers.ToArray(); marshal(() => { var messageType = message.GetType(); var dead = toNotify .Where(handler => !handler.Handle(messageType, message)) .ToList(); if (dead.Any()) { lock (handlers) { dead.Apply(x => handlers.Remove(x)); } } }); } protected class Handler { readonly WeakReference reference; readonly Dictionary<TypeInfo, MethodInfo> supportedHandlers = new Dictionary<TypeInfo, MethodInfo>(); public Handler(object handler) { reference = new WeakReference(handler); var handlerInfo = typeof(IHandle).GetTypeInfo(); var interfaces = handler.GetType().GetTypeInfo().ImplementedInterfaces .Where(x => handlerInfo.IsAssignableFrom(x.GetTypeInfo()) && x.IsGenericType); foreach (var @interface in interfaces) { var type = @interface.GenericTypeArguments[0]; var method = @interface.GetTypeInfo().DeclaredMethods.First(x => x.Name == "Handle"); supportedHandlers[type.GetTypeInfo()] = method; } } public bool Matches(object instance) { return reference.Target == instance; } public bool Handle(Type messageType, object message) { var target = reference.Target; if (target == null) return false; var typeInfo = messageType.GetTypeInfo(); foreach (var pair in supportedHandlers) { if (pair.Key.IsAssignableFrom(typeInfo)) { pair.Value.Invoke(target, new[] { message }); return true; } } return true; } } } /// <summary> /// Generic extension methods used by the framework. /// </summary> public static class EventAggregatorExtensionMethods { /// <summary> /// Applies the action to each element in the list. /// </summary> /// <typeparam name="T">The enumerable item's type.</typeparam> /// <param name="enumerable">The elements to enumerate.</param> /// <param name="action">The action to apply to each item in the list.</param> public static void Apply<T>(this IEnumerable<T> enumerable, Action<T> action) { foreach (var item in enumerable) action(item); } } } Here's how to use it. Please note that I'm just passing messages of type String, you might want to define your own event payload classes. A publisher just needs to get a reference to the central even handler, and publish its message: EventAggregator.Instance.Publish(this.Message); The subscriber registers himself to the same event aggregator. He specifies the type of message he's interested in by implementing the IHandle<T> interface: class SubscriberViewModel : INotifyPropertyChanged, IHandle<string> { public SubscriberViewModel() { // Subscribe EventAggregator.Instance.Subscribe(this); } public void Handle(string message) { // Event handling comes here } }  Publisher and subscriber never have a reference to each other, while the event aggregator uses weak references. This results in a memory-leak free pattern. Sample I built a small and simple application (oops, I did it again: app) to test drive the framework. Here's how it looks like: On the left side of the screen, there's a text balloon and a button. These belong to the publisher. Clicking the button updates the Message property and via the change notification extension methods also the GUI. It sends the new value as message through the event aggregator.  The text balloon in the middle belongs to a subscriber that is instantiated using a view-first approach: the view instantiates its viewmodel. Typically this is done by defining its data context in XAML - but that does not seem to work yet, so I needed some code behind. The text balloon on the right belongs to another subscriber. This one is instantiated using the viewmodel-first approach. When the datacontext of a control is set to a viewmodel, the control decides what template to load. This is typically done with typed data templates in WPF, or with a value converter in Silverlight. Since typed data templates are not available in Metro, I used the Silverlight approach. [Note: The IValueConverter interface in Metro is different from its predecessors.] Both subscribers receive the message through the event aggregator subscription, and use the change notification extensions methods it to update their own Message property, populating the text balloon. Source Code Here's the full source code. It requires VS 2011 Developer Preview: U2UConsult.WinRT.MVVM.zip (205,86 kb) Enjoy!