Create F# ViewModel for WinRT app

Last night I gave a talk about WinRT and Caliburn.Micro at the Nashville .NET User group meeting. Caliburn.Micro is a popular MVVM framework for XAML-based application like WPF, Silverlight, and Windows Phone.

In the talk, I mentioned about using F# in the model part of the sample WinRT app. And that got attention from couple of members from NashFP who also use F#. The discussion lead me to consider using F# for the ViewModel part, so I did some research and found that F# developers have written articles and samples about using F# in ViewModel for other XAML-based application like WPF and Silverlight already.

So I try building a sample WinRT app and use ViewModelBase and RelayCommand implementation from “F# Windows App (WPF, MVVM)” template created by a fellow Nashvillian, Daniel Mohl.

Here is some code for View (XAML), ViewModel, RelayCommand, ViewModelBase:

And here is a screenshot from the app:



As F# is one of CLI languages and works fine in any CLR, everything works perfectly on WinRT as well.

You can found a full solution here.

Happy coding!



Revisit WinRT

Windows Runtime or WinRT was officially introduced to the world together with Windows 8 in BUILD 2011.  At that time, there were a lot of questions surrounding it such as, would it replace Win32, .NET, Silverlight, and so on? It’s almost two years, and I assume everyone has their own answers to those questions.

What is WinRT exactly? It is a new set of COM-based (i.e., every WinRT object implements IUnknown and does refcounting) native APIs on Windows 8. Every WinRT objects implements IInspectable which inherits from IUnknown. The API is defined in WinMD metadata format similar to .NET.


Besides creating modern APIs that is cloud-ready, sandboxed, etc., the design objective of WinRT is to create APIs that is accessible to .NET and JavaScript developers as well. WinRT exposed their APIs to C++, JavaScript, and .NET stacks through projections mechanism.


Windows Store App (formerly known as Metro-Style App)

The only type of applications that can be developed by WinRT are Windows Store apps. That’s why many people including me also use term WinRT app to refer to Windows Store app. However, there is no reason to think that, in the future, Microsoft won’t let developer to use WinRT to develop other kinds of app (e.g., desktop app). WinRT app can be run on both x86 (Windows 8) and ARM (Windows RT).

What does WinRT have to do with .NET?

WinRT app developed using .NET (XAML/C#/VB/F#) is still running on CLR which is the same CLR.dll that runs .NET 4.5 app. However, WinRT app is using a subset of APIs and is using different profiles (similar to .NET or console profile).


Silverlight/WPF/Windows Phone developers will feel at home when they are creating WinRT app although some APIs is missing (e.g., unrelated APIs like ASP.NET, COM wrappers) or moved to new classes (i.e., Reflection) or new namespaces. Like Silverlight, WinRT API is also asynchronous heavy (i.e., if an API can take longer than 50 ms to run, the API is asynchronous).


In summary, WinRT provides single APIs for all language stacks. If you want to squeeze out every bit of performance or don’t want GC to get in the way, C++ (C++/CX or C++ and COM) is closest to the metal and is the obvious choice. If you come from .NET background, C#/VB stacks will get you start quickly. If you come from web development side and prefer JavaScript/HTML, WinRT got you covered too (although you still have to learn WinJS). Finally, interoperability among language stacks are seamless as all stacks can consume WinRT components which can be created by C++ and .NET (Not JavaScript).

Here are some references if you want to learn more about WinRT:

WinRT demystified by Miguel de Icaza (Xamarin)

Underneath the Hood with .NET and the Windows Runtime by Shawn Farkas (MSDN Magazine)

Lap around the Windows Runtime by Martyn Lovell (BUILD 2011)

The Windows Runtime Q&A (BUILD 2012)

Rocky and Billy Introduce WinRT! by Rocky Lhotka and Billy Hollis (.NET Rocks)

Understanding WinRT and Windows 8 for .NET Programmers  by Immo Landwerth (The Hanselminutes Podcast)

How does the new Windows 8 Runtime (WinRT) compare to Silverlight and WPF? (Stackoverflow answer by Pavel Minaev)

A bad picture is worth a thousand long discussions by Doug Seven

.NET and Metro: The Windows Runtime and the CLR on Windows 8 by Jeremy Likness

Introduction to Telerik RadControls for Metro (Pie Chart)

Following the previous Telerik RadControls Bar Chart post, in this post, I will reuse the StateData and Person data model to create a Pie Chart.

Pie Chart needs pie series with the ValueBinding (similart to Bar Chart). However, PieSeries does not have CategoryBinding which creates labels in Bar Chart. For the PieSeries we will need PieLabelStategy instead.

The code below shows how we put PieChart control in xaml page. Don’t forget to specify telerik namespace like we did in the Bar Chart post.

        <telerik:RadPieChart Grid.Row="1" PaletteName="DefaultDark"

In the code behind, I create PieSeries and binding. Like the Bar Chart sample, the ValueBinding is binded to StateData.Count (i.e., how many customers in the state). RadiusFactor property controls how big is our pie chart.

        protected override void OnNavigatedTo(NavigationEventArgs e)
            var peopleByStates = from p in SamplePeople.People
                                 group p by p.ResidenceState into g
                                 orderby g.Key
                                 select new { State = g.Key, People = g };

            var series = new PieSeries();
            series.RadiusFactor = 0.7;

            series.ValueBinding = new PropertyNameDataPointBinding("Count");
            // Set up label strategy
            var pieLabelStrategy = new PieLabelStrategy();
            pieLabelStrategy.Binding = new PropertyNameDataPointBinding("Name");
            var chartSeriesLabelDefinition = new ChartSeriesLabelDefinition();
            chartSeriesLabelDefinition.Strategy = pieLabelStrategy;


            var itemSources = new List<object>();
            foreach (var state in peopleByStates)
                var item = new StateData { Name = state.State, Count = state.People.Count() };
            series.ItemsSource = itemSources;

To create a label strategy, we extend an abstact class Telerik.UI.Xaml.Controls.ChartSeriesLabelStrategy and override Options property, CreateDefaultVisual method, and GetLabelContent method. The CreateDefaultVisual method returns FrameworkElement instance that will represent the label while the GetLableContent method returns the label at the specified index.

public class PieLabelStrategy : ChartSeriesLabelStrategy
        private string format = "{0}\n{1} ({2:P2})";

        public PropertyNameDataPointBinding Binding { get; set; }

        public override LabelStrategyOptions Options
            get { return LabelStrategyOptions.Content | LabelStrategyOptions.DefaultVisual; }

        public PieLabelStrategy()

        public override FrameworkElement CreateDefaultVisual(DataPoint point, int labelIndex)
            var textBlock = new TextBlock()
                Foreground = new SolidColorBrush(Colors.White),
                FontSize = 14.667 };
            return textBlock;

        public override object GetLabelContent(DataPoint point, int labelIndex)
            if (point == null || labelIndex < 0)
                return base.GetLabelContent(point, labelIndex);

            return string.Format(this.format, Binding.GetValue(point.DataItem), ((PieDataPoint)point).Value, ((PieDataPoint)point).Percent / 100);

Telerik does provide PieLabelStrategy sample, and I just modified it a little bit to provide my own label and FrameworkElement.

                /// <summary>
		/// Creates a <see cref="T:Windows.UI.Xaml.FrameworkElement"/> instance that will
		/// represent the label for the provided data point.
		/// </summary>
		/// <param name="point">The data point a label is needed for.</param>
		/// <param name="labelIndex">The index of the label. More than one label is supported
		/// per data point.</param>
		public virtual Windows.UI.Xaml.FrameworkElement CreateDefaultVisual(Telerik.Charting.DataPoint point, int labelIndex) {
return null;

		/// <summary>
		/// Gets the content for the label at the specified index, associated with the provided
		/// data point.
		/// </summary>
		/// <param name="point">The data point the label is associated with.</param>
		/// <param name="labelIndex"></param>
		public virtual object GetLabelContent(Telerik.Charting.DataPoint point, int labelIndex) {
if (point != null)
return point.Label;
return null;

You can download the full source code here. I include both Pie Chart and Bar Chart samples into one project with the top app bar buttons (which I used Syncfusion Metro Studio to create buttons) to navigate between two sample. Enjoy coding!




Introduction to Telerik RadControls for Metro (Bar Chart)

Telerik is one of the lead providers of .NET components and development tools. At work, my group utilizes a lot of Telerik products, so when I learned that Telerik is jumping into metro style application bandwagon, I would like to try it.

The first component that I look at today is a chart component. When we talk about Line-Of-Business (LOB) application, besides grids and forms, charts are other type of controls that are used often. WinRT (either XAML or HTML) provides vector-based drawing API that we can used to draw a chart, but it is better to be able to utilize reusable components for common charts like bar, pie, or line charts.

In this post, I will create a simple bar chart using Telerik chart control for metro in XAML. As always, I will reuse my Person and SamplePeople classes that I used in other posts about Windows 8. In this example, I will plot number of my customers by gender in each state using bar chart.

First, let’s download Telerik RadControls for Metro beta here.


After I create a C#/XAML blank app and add references to Telerik libraries as shown in the above screenshot, I start by adding telerik namespace and a RadCartesianChart control which I can use to create several type of charts including bar chart. RadCartesianChart control uses the Cartesian coordinate system to plot series of data within X and Y axes.


Here is the code in Main.xaml

        <telerik:RadCartesianChart x:Name="radChart" Grid.Row="1" Margin="120 0 0 0" PaletteName="DefaultDark">

Inside the RadCartesianControl, I define two axes, a horizontal categorical axis which will arrange the plotted data points in defined categories (e.g., name of state) and linear vertical axis which uses the numeric value (e.g., number of customers in each state).

In the code-behind, I get the sample people and group them by state, so I can count them. Then I create two bar series, one for male and another for female, and bind category to Name (StateData.Name) and value to Count (StateData.Count). I also need to specify the series combined mode. There are four modes, None, Cluster, Stack, and Stack100. Cluster makes the series combined next to each other while stack forms stacks and so on.

Here is the code-behind in Main.xaml.cs

    public sealed partial class MainPage : Page
        public MainPage()

        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)


        private void AddSeries(string gender)
            var peopleByStates = from p in SamplePeople.People
                                 where p.Gender == gender
                               group p by p.ResidenceState into g
                               orderby g.Key
                               select new { State = g.Key, People = g };
            var series = new BarSeries();
            series.CombineMode = Telerik.Charting.ChartSeriesCombineMode.Stack;
            series.CategoryBinding = new PropertyNameDataPointBinding("Name");
            series.ValueBinding = new PropertyNameDataPointBinding("Count");

            var itemSources = new List<object>();
            foreach (var state in peopleByStates)
                var item = new StateData { Name = state.State, Count = state.People.Count() };

            series.ItemsSource = itemSources;

    public class StateData
        public double Count { get; set; }
        public string Name { get; set; }

Let’s run the app and see how it looks. The first screenshot is the bar chart in Cluster mode and the second one is the bar chart in stack mode.



As you see, just couple lines of code, I now have nice looking bar chart in my app. There are a lot more components in the beta download including, DatePicker, Slider, DropDownList, and other chart types like pie chart and so on. I am going to post about them in the future. As of now, enjoy coding!

Adding Auto-suggestion to Metro Style App Search Contract

As promised on my post about adding search to C# metro style app, I will enhance the sample project from the first post by adding auto-suggestion (auto-complete) capability.

If you have already implemented search contract on your metro style app project, adding auto-suggestion is just a matter of registering an additional event handler (yes, WinRT API is really that easy).

Anyway, let’s get started.

First, I register a SuggestionRequested event handler in the OnLaunced method.

        protected override void OnLaunched(LaunchActivatedEventArgs args)

            SearchPane.GetForCurrentView().SuggestionsRequested += OnSuggestionsRequested;

            // Do not repeat app initialization when already running, just ensure that
            // the window is active
            if (args.PreviousExecutionState == ApplicationExecutionState.Running)

            if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
                //TODO: Load state from previously suspended application

            // Create a Frame to act navigation context and navigate to the first page
            var rootFrame = new Frame();
            if (!rootFrame.Navigate(typeof(MainPage)))
                throw new Exception("Failed to create initial page");

            // Place the frame in the current Window and ensure that it is active
            Window.Current.Content = rootFrame;

Second, I reuse the code in SearchResult page in the first post and put it in OnSuggestionRequested method.

        private void OnSuggestionsRequested(SearchPane sender, SearchPaneSuggestionsRequestedEventArgs args)
            string queryText = args.QueryText.ToLower();

            var suggestions = SamplePeople.People
                .Where(p => p.LastName.ToLower().Contains(queryText.ToLower())
                        || p.FirstName.ToLower().Contains(queryText.ToLower())
                        || p.ResidenceState.ToLower().Contains(queryText.ToLower()));

            foreach (var suggestion in suggestions.Select(p => string.Format("{0}, {1} ({2})", p.LastName, p.FirstName, p.ResidenceState)))

The important part is how I add the suggestion to the SearchSuggestionCollection. The collection requires string, but it depends on the app to put the meaningful strings as suggestions. As my query is filtering either last name, first name, or state, I combined them together as a suggestion.




As you can see, Windows 8 also helps by highlighting the search term in those suggestions, so what you choose as suggestion strings will determine how easy to search on your application.

Hope you enjoy this short post. At the time of this writing, we already know that Windows 8 will be available (GA) on October 26th. Let’s get ready soon.  Enjoy coding!

Interesting Links, June 25, 2012

I have been directed to two posts below from my twitter feed.

The first post is by Infragistics. It should answers the common questions about Windows 8, Surface, Windows RT, and Windows Phone 8 include:

  • Can Windows 8 run my current Windows app?
  • Can I build Windows 8 Metro apps in .NET?
  • Are Windows 8 games built in C++ or XNA?
  • Can I build apps for both Windows 8 and Windows Phone?
  • What are all developer platforms for each devices?

Infragistics is one of the leaders in providing UI tools and .NET components . They also provide developer support, training, and consulting services. For anyone who is interested in UX and UI patterns, you should also visit Quince. There are many UI/UX patterns that you can search and learn.

The second post is about Infographics which is another topic that I try to learn as much as possible. I believe good understanding in how to design infographic can help you design the software dealing with complex and large amount of data. The post by Hyperkat’s Josh Smith is talking about how to design an infographic in 10 steps.

“Information can be useful–and even beautiful–but only when it’s presented well.”

The quote above said it all. With the advance of information technology, we can store almost any information that we have gathered. However, without the way to present them comprehensively, the information is useless. The writing is talking about the ten steps process of transforming data into a visually compelling graphic (aka Infographic).
I like this step as data/information can be boring. Attaching some story with them helps clarifying a complex set of data and highlighting a trend.

Enjoy coding!

Adding Search to your C# Metro Style App

Windows 8 introduces Charms and Contracts, which are elegant ways to formalize several trivia tasks in most apps such as search, print, setting, etc. through system-level contracts. For mouse/keyboard user, the search charms can be accessed directly using WinKey + Q.

I do like the standardize idea although this might confuse a new Windows 8 user including me who used to perform those tasks via application UI or menu items.  For example, the app does not provide obvious action or UI to search for a word. To do that, you would need to use “Search” Charms instead.


However, this should not prevent you to add this useful capability in your metro style app. The app is one of the example.

Note: I use the Windows 8 Release Preview and Visual Studio 2012 RC to create this example.

In this blog post, I create a simple metro style app which list customers in a GridView.  As you can see the list can be big, and it would be painful for our user that would need to scan the list to look for a specific record.


Here is the XAML code (MainPage.xaml and MainPage.xaml.cs) that includes DataTemplate and Binding for the GridView. I also hard-coded the ItemsSource assignment in the code behind 🙂 .Nothing is fancy here for anyone who has been working with XAML (e.g., Silverlight, WPF, Windows Phone).

                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="*"/>
            <Rectangle Width="120" Height="140" HorizontalAlignment="Left" x:Name="cornerRectangle"/>
            <StackPanel Grid.Column="1" Orientation="Horizontal" VerticalAlignment="Center">
                <Image Source="Assets/CM-logo.png" Height="50" Margin="0 0 20 0"/>
                <TextBlock Style="{StaticResource HeaderTextStyle}" VerticalAlignment="Center">Customers</TextBlock>
        <GridView x:Name="gridView" Grid.Row="1" Margin="120 0 0 0" >
                        <Border Background="Blue" Opacity="0.2"/>
                        <StackPanel Margin="20" Width="200">
                            <StackPanel Orientation="Horizontal">
                                <TextBlock Text="{Binding LastName}" Style="{StaticResource TitleTextStyle}"/>
                                <TextBlock xml:space="preserve" Style="{StaticResource TitleTextStyle}">, </TextBlock>                                
                                <TextBlock Text="{Binding FirstName}" Style="{StaticResource TitleTextStyle}" Margin="10 0"/>
                            <TextBlock Text="{Binding ResidenceState}" Margin="10 0" Style="{StaticResource BodyTextStyle}"/>                        


protected override void OnNavigatedTo(NavigationEventArgs e)
     gridView.ItemsSource = SamplePeople.People.OrderBy(p => p.LastName).ThenBy(p => p.FirstName).ThenBy(p => p.ResidenceState);

Now is the fun part. To enable search capability on my app, I will have to do the followings:

1. Declare the Search Contract in the app manifest. This is pretty straightforward as I just open manifest file and add “search” declaration.  In this blog, I won’t register the app as a search provider because I plan to have user search for customers after they are in my app already.



2. Add a Search Contract by adding a New Item. It might say that your project misses some dependencies if you start from a blank page project template (the search page requires additional Common files such as LayoutAwarePage and BindableBase). I just click ‘Yes’, and those files will be added automatically.


3. Besides the new SearchResult page (SearchResultsPage.xaml), Visual Studio addes OnSearchActivated() handle into the App.xaml.cs automatically. It just makes sure that it will activate the SearchResultPage when the user activates the search charm. In the new SearchResult code-behind page, I implement custom LINQ to get people which contain provided keyword and assign to the Results DefaultViewModel (This seems to be a normal MVVM implementation for most metro style app templates). This example, I allow a user to search by customer’s last or first name and residence state.

protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
     var queryText = navigationParameter as String;

     var filteredPeople = SamplePeople.People
         .Where(p => p.LastName.ToLower().Contains(queryText.ToLower())
                 || p.FirstName.ToLower().Contains(queryText.ToLower())
                 || p.ResidenceState.ToLower().Contains(queryText.ToLower()));

     this.DefaultViewModel["Results"] = filteredPeople.ToList();

     var filterList = new List();
     filterList.Add(new Filter("All", 0, true));

     // Communicate results through the view model
     this.DefaultViewModel["QueryText"] = '\u201c' + queryText + '\u201d';
     this.DefaultViewModel["CanGoBack"] = this._previousContent != null;
     this.DefaultViewModel["Filters"] = filterList;
     this.DefaultViewModel["ShowFilters"] = filterList.Count > 1;


    public class Person
        public string LastName { get; set; }
        public string FirstName { get; set; }

        public string ResidenceState { get; set; }

    public static class SamplePeople
        #region Last Names
        public static string[] _lastNames = new[]

        #region First Names
        public static string[] _firstNames = new[]

        #region States
        public static string[] _states = new[]
            "New Hampshire",
            "New Jersey",
            "New Mexico",
            "New York",
            "North Carolina",
            "North Dakota",
            "Rhode Island",
            "South Carolina",
            "South Dakota",
            "West Virginia",

        public static IEnumerable People { get; set; }

        public static void BuildSamplePeople()
            var people = new List<Person>();

            var length = 50;
            Random r = new Random();
            for (int i = 0; i < length; i++)
                var person = new Person();

                person.LastName = _lastNames[r.Next(0, _lastNames.Count())];
                person.FirstName = _firstNames[r.Next(0, _firstNames.Count())];
                person.ResidenceState = _states[r.Next(0, _states.Count())];

            People = people;

This should be all for simple search contract implementation.


Here is the XAML code in the searchresult page. I use normal GridView with a template binding properties of each returned person instance.

        <!--             The body of the page in most view states uses an items controls to create multiple radio buttons             for filtering above a horizontal scrolling grid of search results         -->






I could also implement auto-complete, provide more information about filtered list like screenshot below but I will hopefully post those examples later. Enjoy working on your metro style app!