Binding to a ConverterParameter in Windows 8 Metro

This article describes how to simulate databinding to a ConverterParameter in a Windows 8 Metro XAML app. Let's say we have a TextBlock that displays a value from the ViewModel, and a Converter that takes this value together with some Range object as parameter. The converter should return a Brush -green or red- that indicates wether or not the value is within the range. The converter is used for providing the foreground color of the textblock. The following intuitive code would represent this behavior: <TextBlock Text="{Binding SomeValue}" Foreground="{Binding SomeValue, Converter={StaticResource RangeValidationConverter}, ConverterParameter={Binding SomeRange}}" /> Unfortunately, databinding to a ConverterParameter is not supported by any of Microsoft's XAML platforms. But let me share with you a little secret: that binding is actually easy to simulate. The following screenshots from the attached sample application show the bitterness of a beer (a value from the ViewModel) in green if it's within the expected range (the alleged Range parameter for the Converter), and red if it's out of range. With the slider you can throw more hops into the recipe to add bitternes, or remove hops to decrease bitterness. The value in the textblock, the needle in the gauge, but also the color of the textblock will synchonize with the bitterness value: Here's how it works. Instead of using the converter parameter, I decorated the converter with a dependency property to hold the range: public Range<int> Range { get { return (Range<int>)GetValue(RangeProperty); } set { SetValue(RangeProperty, value); } } public static readonly DependencyProperty RangeProperty = DependencyProperty.Register("Range", typeof(Range<int>), typeof(RangeValidationConverter), new PropertyMetadata(new Range<int>(0,100))); The converter can use the Range in its Convert method: public object Convert(object value, Type targetType, object parameter, string language) { int measurement = System.Convert.ToInt32(value); Range<int> range = this.GetValue(RangeProperty) as Range<int>; if (range == null) { return new SolidColorBrush(Colors.Gray); } if (measurement >= range.Min && measurement <= range.Max) { return new SolidColorBrush(Colors.LawnGreen); } return new SolidColorBrush(Colors.Red); } The converter is registered in the traditional way: as a resource. But the Range property can now be assigned through data binding: <Page.Resources> <local:RangeValidationConverter x:Key="RangeValidationConverter" Range="{Binding BitternessRange}" /> </Page.Resources>  The textblock just uses the converter without providing a parameter: <TextBlock Text="{Binding CurrentBitterness}" Foreground="{Binding CurrentBitterness, Converter={StaticResource RangeValidationConverter}}" /> There you go ! Here's the source code. It was written in Visual Studio 11 Express Beta for the Windows 8 Consumer Preview: U2UC.Metro.ConverterParameterBinding.zip (115,27 kb) Enjoy!

Look Mom, I’m on the Tablet Show

People that know me will definitely confirm that I’m a silent, modest person, always trying to keep a low profile . Last week, however, Carl Franklin and Richard Campbell from the Tablet show pulled me way out of my comfort zone to produce a podcast on the development of enterprise applications for Metro. The talk started from the trenches of development in preview-labelled environments; and evolved into a visionary discussion on Star Trek desk setups and using the Kinect in the enterprise. I definitely sound as if I was sitting in an empty beer kettle [note to myself: buy a microphone], but I'm still proud of the result: Diederik Krols Builds Metro UIs in Windows 8

Using Dynamic XAML in Windows 8 Metro

This article describes how the Windows 8 Metro Consumer Preview deals with three standard ways of dynamically applying a look-and-feel to XAML controls. When working in Metro with XAML and data, you will want to maximally leverage the data binding capabilities of the platform from day one. You can do this at multiple levels. In this article, I will discuss the following techniques: value converters, style selectors, and data template selectors.  Here's a screenshot of the attached sample project: Using a Value Converter Dependency properties of a XAML control can be directly bound to properties of the viewModel. Sometimes a conversion of value and/or data type needs to take place; that can be done through a ValueConverter. A value converter is a class that implements the IValueConverter interface, with just Convert and ConvertBack functions. Here's an example of a string-to-string converter that translates official beer colors into HTML named colors: using System; using Windows.UI.Xaml.Data; public class BeerColorConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, string language) { switch (value.ToString()) { case "Yellow": return "LemonChiffon"; case "Straw": return "Wheat"; case "Gold": return "GoldenRod"; case "Amber": case "LightCopper": case "Copper": return "Peru"; case "LightBrown": return "Chocolate"; case "Brown": return "Brown"; case "DarkBrown": return "darkRed"; case "VeryDarkBrown": return "SaddleBrown"; case "Black": return "Black"; default: return "Lime"; } } public object ConvertBack(object value, Type targetType, object parameter, string language) { return value; } } Just define an instance of the converter as a resource: <Page.Resources> <local:BeerColorConverter x:Key="BeerColorConverter" /> </Page.Resources> And use it in the binding: <TextBlock Text="{Binding Name}" Foreground="{Binding Color, Converter={StaticResource BeerColorConverter}}" /> Unfortunately Metro doesn't ship with MultiBinding, and bindings don't come with a StringFormat option. That definitely restricts the usage of a value converter, compared to WPF and Silverlight. Using a Style Selector Another way of dynamically styling items in a XAML list control, is with a StyleSelector. This provides a way to apply styles based on custom logic. This seems to be the only way to create a dynamic style in Metro, due to the absence of DataTriggers. Just create a subclass of the StyleSelector class and implement the SelectStyle method. The bound item is the first parameter, the item's style is the return value. Here's a small example on how to modify the style for a list view item: public class BeerStyleSelector: StyleSelector { protected override Style SelectStyleCore(object item, DependencyObject container) { Style style = new Style(typeof(ListViewItem)); style.Setters.Add(new Setter(ListViewItem.ForegroundProperty, new SolidColorBrush(Colors.Red))); return style; } } Again, the class containing the logic should be defined as a resource: <Page.Resources> <local:BeerStyleSelector x:Key="BeerStyleSelector" /> </Page.Resources>  You can then assign the ItemContainerStyleSelector to an instance of it: <ListView ItemsSource="{Binding BelgianBeers}" ItemContainerStyleSelector="{StaticResource BeerStyleSelector}" /> I did not elaborate this example to much, since unfortunately style selectors don't work in the Consumer Preview. Hopefully the problem will be solved next week, with the Release Preview. Using a Data Template Selector The most powerful way of dynamically changing XAML, is using a DataTemplateSelector, which allows you to choose or generate a DataTemplate based on the data object and the data-bound element. To create a template selector, create a class that inherits from DataTemplateSelector and override the SelectTemplate method. Once your class is defined you can assign an instance of the class to the template selector property of your element. The business logic could be as simple a selecting an existing template from a resource, like this.DefaultTemplate in the following code snippet. But the entire template could also be generated on the spot through a XamlReader. The following chauvinist logic creates a colored stackpanel including a Belgian flag for superior beers, and applies the default template to the rest: using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Markup; public class BeerTemplateSelector : DataTemplateSelector { public DataTemplate DefaultTemplate { get; set; } protected override DataTemplate SelectTemplateCore(object item, DependencyObject container) { Beer beer = item as Beer; if (!(beer.Category.Contains("Belgian") || beer.Category.Contains("Flemish"))) { return this.DefaultTemplate; } BeerColorConverter converter = new BeerColorConverter(); string backGroundColor = converter.Convert((item as Beer).Color, null, null, null).ToString(); string template = @" <DataTemplate xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'> <StackPanel Background='" + backGroundColor + @"' Width='360'> <TextBlock Text='{Binding Name}' FontWeight='Bold' Margin='2' Foreground='Black' HorizontalAlignment='center' /> <Grid> <TextBlock Text='{Binding Category}' Margin='2' Foreground='Black' /> <Image Source='../Assets/belgianFlag.png' Margin='2' HorizontalAlignment='Right' Stretch='None' /> </Grid> </StackPanel> </DataTemplate>"; return XamlReader.Load(template) as DataTemplate; } } Again, register the class contining the logic as a resource: <Page.Resources> <DataTemplate x:Key="DefaultDataTemplate"> <StackPanel> <TextBlock Text="{Binding Name}" Foreground="{Binding Color, Converter={StaticResource BeerColorConverter}}" FontWeight="Bold" /> <TextBlock Text="{Binding Category}" Foreground="{Binding Color, Converter={StaticResource BeerColorConverter}}" /> </StackPanel> </DataTemplate> <local:BeerTemplateSelector x:Key="BeerTemplateSelector" DefaultTemplate="{StaticResource DefaultDataTemplate}" /> </Page.Resources> Then use an instance as ItemTemplateSelector: <ListView ItemsSource="{Binding BelgianBeers}" ItemTemplateSelector="{StaticResource BeerTemplateSelector}" /> With a DataTemplateSelector you're not restricted to dependency properties. Source Code Here's the source code of the sample project. It was written with Visual Studio 11 Express Beta, for the Windows 8 Consumer Preview: U2UConsult.Metro.DynamicTemplating.zip (70,30 kb) Enjoy!

Using the CarouselPanel in Windows 8 Metro

Warning: content applies to Windows 8 Consumer Preview only. In the current release, the CarouselPanel can not be used in stand alone mode anymore. This short article describes how to use the CarouselPanel in a Windows 8 Consumer Preview Metro style app. Don't expect the spectacular rotating 3D effects from the Infragistics WPF control with the same name. In the current release, a Metro CarouselPanel is nothing more than a vertically revolving conveyer belt. That's good enough: the CarouselPanel is one of those controls that keeps your design away from the traditional dull grid-and-combobox layout that we know from excel or standard winforms databinding. Here's a WPF example; it's a prototype of an application that allows you to mix your own cocktails by selecting the products and entering the corresponding quantity: If you would sell this app through the store, you probably won't get rich. Grid-and-combobox design is so passé. On the other hand: if you would generate views on the same data model using the default ASP.NET MVC templates, you'll get exactly the same lame design...  Anyway, here's how this application may look like in Metro style. It's operated by swiping and tapping on the products carousel on the left, instead of fighting with comboboxes and empty grid rows: The vertical strip on the left is an instance of a CarouselPanel. The CarouselPanel was already available in the Developer Preview of Windows 8, but only as a part of the ComboBox control template. In the Consumer Preview you can use it as ItemsPanelTemplate of any ItemsControl. <ListView ItemsSource="{Binding YourCollectionHere}"> <ListView.ItemTemplate> <DataTemplate> <!-- Your Data Template Here --> </DataTemplate> </ListView.ItemTemplate> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <CarouselPanel /> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> </ListView> That's all there is! You can scroll via touch or via the mouse wheel. When you reach the end of the list, you can continue scrolling in the same direction. After the end of the list an empty placeholder is inserted, and then everything starts all over again. The following screenshot shows the placeholder - between the end of the list (pineapple juice) and the new beginning (white rum): For those who want to use the control in a horizontal orientation (e.g. as a filmstrip), here's the good news: there is a CanHorizontallyScroll property in the documentation and in Visual Studio's Designer: Here's the bad news: setting the property gives a compile time error. The horizontal strip in the demo app is just a GridView; you have to move back and forth to have an overview of all ingredients. Anyway, the existence of the CanHorizontallyScroll property (and some of the other non-functioning class members) indicates that Microsoft has plans to do more with this control in the future. Here's the code of the demo app. It was written in Visual Studio 11 Express Beta for Windows 8 Consumer Preview: U2UConsult.WinRT.CarouselSample.zip (770,55 kb) Enjoy !

A StringFormat converter for Windows 8 Metro

Some people seem to think that the world has only one language, one currency, and one way to represent a date, a time, or a number. So WinRT comes without a StringFormat option in data binding. I know for sure that I never built a WPF or Silverlight application without extensively using that StringFormat option. Just think about how your calendar or online banking application would look like without the proper content formatting: "Dear customer, at 3/20/2012 6:23:30 PM the balance of your bank account BE43068999999501 was at -850325, so we will withdraw that amount from your credit card 4417123456789113. Please call +442071311117 for further assistance." You simply can't get away with that, so I believe that one of the next Metro versions *will* come with string formatting in bindings. In the mean time, we will have to implement formatting in the viewmodel, or help ourselves using a value converter. Here's an example of the latter. It supports two-way bindings, and it doesn't crash when you forget to specify the format: public class StringFormatConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, string language) { // No format provided. if (parameter == null) { return value; } return String.Format((String)parameter, value); } public object ConvertBack(object value, Type targetType, object parameter, string language) { return value; } } Just define it as a resource in XAML: <Page.Resources> <local:StringFormatConverter x:Key="StringFormatConverter" /> </Page.Resources> And use it: <TextBlock Text="{Binding SomeDateTime, Converter={StaticResource StringFormatConverter}, ConverterParameter='{}{0:dd MMM yyyy}'}" /> It works well against strings, dates, times, and numbers: Here's the full source. It was built with Visual Studio 11 Express Beta, for the Windows 8 Consumer Preview: U2UConsult.WinRT.StringFormatConverterSample.zip (170,03 kb) Enjoy!

A Radial Gauge custom control for Windows 8 Metro

A long time ago in a galaxy actually not so far away, Colin Eberhardt wrote a Radial Gauge custom control for Silverlight in less than six hours. It had everything a gauge should have: a needle, and a scale with tick markers and labels. Hell, it even had colored quality range indicators. A couple of months ago, I thought "Hey, I can do that too." So I started a new Metro project in my Developer Preview of Windows 8. I tried to create a Metro version of that same radial gauge in less than six hours. Six lonely nights later, I still had absolutely nothing, and I started to consider anger management training. I gave up and started from scratch, this time on a much simpler control: a minimalistic slider. That involved a lot of work with -let's be honest- a rather lame result. The Developer Preview was clearly not an ideal environment for building custom controls. But that was then and this is now. Yesterday, Tim Heuer revealed how to build a deployable custom control for XAML Metro style apps with the Consumer Preview of Windows 8. I discovered that the current beta of Visual Studio 11 comes with a template for a Templated Control. I happily noticed the return of the themes/generic.xaml file that we know from all the other XAML platforms. So I decided to have another go on the radial gauge custom control. Here's the result: Colin's Silverlight Gauge Diederik's Metro Gauge Here's how the gauge is defined in XAML: <local:RadialGaugeControl Maximum="100" Minimum="-100" Value="65" Unit="°C" Height="200"> <local:RadialGaugeControl.QualitativeRanges> <local:QualitativeRange Color="#FFFFFFFF" Maximum="0" /> <local:QualitativeRange Color="#FFFFFF00" Maximum="40" /> <local:QualitativeRange Color="#FFFFA500" Maximum="80" /> <local:QualitativeRange Color="#FFFF0000" Maximum="100" /> </local:RadialGaugeControl.QualitativeRanges> </local:RadialGaugeControl> The Metro version of the radial gauge is simplified in many ways:• It has the Metro look-and-feel: it's sharp, without gradients or shadows. No chrome, but content!• It does not delegate its look-and-feel to a separate viewmodel. All code is hosted by the control class itself.• I simplified most of the calculations by creating a fixed size control and wrapping it in a Viewbox. After all, the control only contains vector graphics: Ellipse, Path, and Text. There's probably more room for simplification and improvement, but this was a race against time, remember. At the end or the day, I'm happy with the result. Here's how the attached sample solution looks like. By the way, EBC -the unit of color- stands for European Brewing Convention (the European alternative for Lovibond) and EBU -the unit of bitterness- stands for European Bitterness Unit (the European version of IBU): The conversion from Silverlight to Metro went very fast. The Consumer Preview version of Metro uses the same paradigms (and name spaces!) as the existing XAML platforms, so I'm going to spare you the details. A custom control is defined by a control class with dependency properties, and a generic.xaml file with the default style definition: So if you can write a custom control in Silverlight, you can write a custom control in Metro! Sometimes you may have to work your way around some glitches. I noticed that the rotation transformation on the needle path isn't fired if it's defined in XAML. The values are correctly assigned by the TemplateBinding, but the transformation does not happen: <Path.RenderTransform> <RotateTransform Angle="{TemplateBinding ValueAngle}" /> </Path.RenderTransform> So I moved it to the code behind: Path needle = this.GetTemplateChild(NeedlePartName) as Path; needle.RenderTransform = new RotateTransform() { Angle = this.ValueAngle }; I still had a lot of time left in my six hour frame, when I started the implementation of the qualitative ranges - the nicely colored arc segments. I discovered rapidly that there are no TypeConverters for WinRT structs such as Color. There is also no support for custom TypeConverters. Bummer. I had no choice but to redefine the Color property as a String - instead of a 'real' Color type: public class QualitativeRange { public double Maximum { get; set; } public String Color { get; set; } } That type change comes with a huge price: say "bye-bye Visual Studio Designer support" when assigning a Color in XAML. I then had to figure out how to translate the color string into a Brush, because there is no ColorConverter.ConvertFromString in Metro. So back to anger management training... ... or not. I decided to drop support for named colors and restrict the color values to hexadecimal codes only. I then upgraded an old HexToColor converter that I found in one of my legacy Silverlight (2.0?) frameworks. That definitely does the trick - at least if the input falls in the expected range: namespace U2UConsult.Metro.RadialGauge { using System; using Windows.UI; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Media; public class HexToColorConverter : IValueConverter { /// <summary> /// Converts a hexadecimal string value into a Brush. /// </summary> public object Convert(object value, Type targetType, object parameter, string language) { byte alpha; byte pos = 0; string hex = value.ToString().Replace("#", ""); if (hex.Length == 8) { alpha = System.Convert.ToByte(hex.Substring(pos, 2), 16); pos = 2; } else { alpha = System.Convert.ToByte("ff", 16); } byte red = System.Convert.ToByte(hex.Substring(pos, 2), 16); pos += 2; byte green = System.Convert.ToByte(hex.Substring(pos, 2), 16); pos += 2; byte blue = System.Convert.ToByte(hex.Substring(pos, 2), 16); return new SolidColorBrush(Color.FromArgb(alpha, red, green, blue)); } /// <summary> /// And back again. /// </summary> public object ConvertBack(object value, Type targetType, object parameter, string language) { SolidColorBrush val = value as SolidColorBrush; return "#" + val.Color.A.ToString() + val.Color.R.ToString() + val.Color.G.ToString() + val.Color.B.ToString(); } } } To make the gauge interactive, I hooked a change event handler to the dependency property: public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(double), typeof(RadialGaugeControl), new PropertyMetadata(0.0, OnValueChanged)); private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { RadialGaugeControl c = (RadialGaugeControl)d; // ... } } Unfortunately neither a GetTemplateChild nor a FindName method call were able to find the Needle element: both retrieved a null value. So I created a private field for the Needle, populated the field in the OnApplyTemplate call: this.Needle = this.GetTemplateChild(NeedlePartName) as Path; Then it became accessible in the change event handler: if (c.Needle != null) { c.Needle.RenderTransform = new RotateTransform() { Angle = c.ValueAngle }; } And the radial gauge became truly bindable: Here's the code for the gauge control and the client app. It was written with Visual Studio 11 Express Beta for the Windows 8 Consumer Preview: U2UConsult.Metro.RadialGauge.zip (399,29 kb) Enjoy !

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!