This article presents a FlipView context indicator control for Windows 8 UI Style apps. FlipView is a Windows 8 items control that displays one item at a time. It allows traversing its collection of items through a horizontal flick gesture. There are some limitations in its usage. In an app, the maximum size of a flipview is the size of the page. If you make the FlipView wider than its container, you're just going to confuse your user (and probably also the runtime): does a horizontal flick triggers scrolling, or are we moving to the next (or previous) page ? This is one of the reasons why I personally prefer the single page GridView style over a FlipView. If you decide to stick to the FlipView, you're not only limited in the size of the data template. You'll also bump into another problem: how are you going to make it clear to your user that he can navigate to other items ? Well, the Guidelines for FlipView Controls prescribe the usage of a context indicator, but they don't specify how it should look like.
The official FlipView Control Sample only has a HTML/JS version. There used to be XAML/C# sample for the Release Preview -my control templates are based on it. But that sample app seems to have been lost in RTM translation. So the best functional example of a FlipView Context Indicator can be found in the store:
Here's how I built my control. Its design is very simple and so is the implementation. [Warning:spoiler in next statement] It is just a templated ListBox that is bound to the ItemsSource and SelectedItem of its associated FlipView.
In Visual Studio, I created a new project of the type 'Windows Store Apps Class Library' and added a new 'Templated Control'. I made that control inherit from ListBox. In the Generic.xaml resource dictionary, I added the two styles from the (now disappeared) FlipView Control Sample: a style for the ListBox itself (just a rectangle), and a style for the ListBoxItem (another rectangle). That's a lot of XAML to just define two rectangles.
I gave the control a dependency property -called FlipView- of the type ... FlipView:
public static readonly DependencyProperty FlipviewProperty =
DependencyProperty.Register("Flipview", typeof(FlipView), typeof(FlipViewIndicator), new PropertyMetadata(null, FlipView_Changed));
public FlipView Flipview
{
get { return (FlipView)GetValue(FlipviewProperty); }
set { SetValue(FlipviewProperty, value); }
}
When the property is assigned or changed -e.g. through XAML- I set the ItemsSource of the context indicator to the ItemsSource of the FlipView. I also create a two-way binding to the SelectedItem.
private static void FlipView_Changed(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
FlipViewIndicator that = d as FlipViewIndicator;
FlipView flip = (e.NewValue as FlipView);
that.ItemsSource = flip.ItemsSource;
Binding binding = new Binding();
binding.Mode = BindingMode.TwoWay;
binding.Source = flip;
binding.Path = new PropertyPath("SelectedItem");
that.SetBinding(FlipViewIndicator.SelectedItemProperty, binding);
}
This way, the context indicator can be used to navigate through the items collection - just by tapping one of the small rectangles. That's why I made these rectangles wider than the ones in the Store. Here's how it looks like in the attached sample app. For the record: the flipview context indicator is the small bar in the lower left corner:
This app is just a FlipView and Context Indicator on a list of Belgian Super Heroes. The description is in Dutch, which may look weird if you don't know the language. But I assure you: if you translate them in English, they will still look weird. The bottom line is that Belgian Super Heroes evolved from men in mini skirts in the 1970s, to men in fluorescent leather catsuits in the 2010s:
O, I almost forgot: here's how to add the control on a page, and link it to a FlipView:
<FlipView x:Name="heroFlipView"
ItemsSource="{Binding Heroes}">
...
</FlipView>
<controls:FlipViewIndicator Flipview="{Binding ElementName=heroFlipView}"
VerticalAlignment="Bottom"
HorizontalAlignment="Left"
Margin="8" />
That's all there is.
Here's the code of the control and sample app. It was written in Visual Studio 2012 Ultimate, for the Windows 8 RTM: U2UConsult.Win8.FlipViewIndicatorSample.zip (587.48 kb)
Update: This is the very first version of the FlipViewIndicator. A newer version of this control is embedded in Tim Heuer's Callisto framework, were it will continue its life cycle.
Enjoy!

This article describes how to restyle the Metro GridView to host a single page app like the sample Weather and Finance apps. I'll show you how to get rid of the default disco effects of this control - like the swiping behavior and the pressed animation. For this article, I started with my own lightweight version of the weather app, but I got bored very soon. So I upgraded the app to a tribute to the iconic rock band CPeX, with some pictures, some overflowing RichTextBox controls with lyrics, and WebView controls revealing the band's web site and wikipedia page; there's even a YouTube video in it:
The GridView is a good candidate to host a single page Metro app: out-of-the-box it's layed out horizontally, and it supports panning through differently sized content pages. It was designed for selecting and moving items, so its default look-and-feel is way too busy. But Visual Studio 11 Release Candidate is the ideal environment to tame it. Visual Studio is now sharing some of its designers with Expression Blend. If you want to restyle a control on a page, all you have to do is right click in the XAML designer, and select "edit template" and "edit a copy". The control template will be pulled out of generic.xaml and applied to the control, after you decided where to save the style:
That's exactly what I did to create new copies of the templates for the GridView and GridViewItem control.
Here's the list of modifications to the default GridView style:
I changed the IsSwipeEnabled property to false:
<Setter Property="IsSwipeEnabled" Value="False" />
I added a default value for the SelectionMode property:
<Setter Property="SelectionMode" Value="None" />
I changed the ItemsPanelTemplate to a horizontal StackPanel:
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" VerticalAlignment="Stretch" />
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
Finally, I made the outer ScrollViewer snap to the GridViewItems:
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="GridView">
<Border ... >
<ScrollViewer
x:Name="ScrollViewer"
...
HorizontalSnapPointsType="Optional">
<ItemsPresenter .../>
</ScrollViewer>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
After a swipe, the GridView pans smoothly to the beginning of the next (or previous) page. Heck, even the Weather and Finance apps don't do this:
Here's the list of modifications to the default GridViewItem style:
I changed the margin, so that all pages touch the borders and each other:
<Setter Property="Margin" Value="-4 -4 -4 0" />
I cleared the animations for the following visual states: PointerOver, Pressed, PointerOverPressed, and Focused:
<VisualState x:Name="PointerOver">
<Storyboard />
</VisualState>
When I was happy with the result, I moved the two styles to a separate resource dictionary:
I added a reference to it in the app.xaml:
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Common/StandardStyles.xaml" />
<ResourceDictionary Source="Common/ZenStyles.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
Here's how the main GridView uses the styles:
<GridView
Style="{StaticResource ZenGridViewStyle}"
ItemContainerStyle="{StaticResource ZenGridViewItemStyle}">
...
</GridView>
Here's the sample project. It was developed with Visual Studio 11 Ultimate RC for the Windows 8 Release Preview: U2UConsult.Metro.GridViewZen.zip (1.26 mb)
Enjoy!

This article describes how to create modal dialogs in a Windows 8 MVVM Metro-style app. Here's the use case: a main page opens a dialog and provides it with some information. The dialog is displayed in the center of the screen, and collects some information. As long as the dialog is open, the main page is inaccessible by the user interface. When the dialog is closed, the main page reads the result from the dialog, and continues processing.
The Sample
Here are some screenshots of the attached solution. You see the main page with a shop button to open the dialog, the dialog that allows you to select multiple items from a catalog and then checkout, and finally the main page displaying the purchased items after the dialog was closed:
The Dialog
The dialog is implemented as a regular Page. When it's displayed, it will occupy the whole screen to prevent access to the underlying main page:
public CatalogDialog()
{
this.InitializeComponent();
var bounds = Window.Current.Bounds;
this.RootPanel.Width = bounds.Width;
this.RootPanel.Height = bounds.Height;
}
The dialog look-and-feel is created by using a semi-transparent background under a white border with a wide margin around the core content:
<Page>
<Grid
x:Name="RootPanel"
Opacity=".75"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch">
<Border
Background="White"
Margin="120">
<Grid Background="Blue" Margin="8">
<GridView
x:Name="CatalogGridView"
ItemsSource="{Binding Cars}"
SelectionMode="Multiple"
SelectionChanged="CatalogGridView_SelectionChanged">
</GridView>
<Button
Content="Checkout"
Click="CloseButton_Click">
</Button>
</Grid>
</Border>
</Grid>
</Page>
The dialog notifies its end-of-life by raising a CloseRequested event, in the click event handler of the checkout-button. This is the kind of code that you would factor out into a Dialog base class:
public event EventHandler CloseRequested;
private void CloseButton_Click(object sender, RoutedEventArgs e)
{
if (this.CloseRequested != null)
{
this.CloseRequested(this, EventArgs.Empty);
}
}
The viewmodel always reflects the dialog's state. Binding to the SelectedItems property is not possible, so we have to refrain from hard-core MVVM. We update the viewmodel each time the selection in the catalog gridview is changed:
private void CatalogGridView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
foreach (var item in e.AddedItems)
{
PinkFerrari pf = item as PinkFerrari;
pf.IsSelected = true;
}
foreach (var item in e.RemovedItems)
{
PinkFerrari pf = item as PinkFerrari;
pf.IsSelected = false;
}
}
The Main Page
The main page has a button that opens the dialog, and a listview to display the result:
<Page>
<Page.DataContext>
<local:MainPageViewModel />
</Page.DataContext>
<Grid>
<Button
Content="Shop"
Command="{Binding OpenDialogCommand}">
</Button>
<ListView
ItemsSource="{Binding ShoppingList}">
</ListView>
</Grid>
</Page>
When the shop-button is clicked, a command is fired in the main page's viewmodel. That viewmodel creates a new instance of the dialog view. MVVM tifosi would prefer to use some kind of ViewLocator here, instead of a hard reference to the view's class. The dialog view is associated with a viewmodel - that's how the two viewmodels can exchange information. An event handler is hooked onto the CloseRequested event. Then the dialog view is wrapped in a Popup element, which is then opened:
private void OpenDialog_Executed()
{
this.catalog = new CatalogViewModel();
CatalogDialog dialog = new CatalogDialog();
dialog.DataContext = this.catalog;
dialog.CloseRequested += Dialog_CloseRequested;
this.catalogPopup = new Popup();
this.catalogPopup.Child = dialog;
this.catalogPopup.IsOpen = true;
}
When the dialog closes, the main page's viewmodel is updated:
private void Dialog_CloseRequested(object sender, EventArgs e)
{
this.catalogPopup.IsOpen = false;
this.shoppingList.Clear();
var query = from f in this.catalog.Cars
where f.IsSelected
select f;
foreach (var item in query)
{
this.shoppingList.Add(item);
}
}
That's all there is...
The Result
Last week our CEO used this app to order the new company cars. Here's a picture of our parking area this morning:
The Code
Here's the full source code of the sample solution. Is was build with Visual Studio 2012 Ultimate RC for the Windows 8 Release Preview: U2UConsult.Metro.DialogSample.zip (409,68 kb)
Enjoy !

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!

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

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!

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 !

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 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 !