Composition is an integral part of Windows 8 UI design from both aesthetic and logical perspectives. This post modified my previous post, Refactoring Windows 8 Code-Behind to MVVM. adding to the variety of compositional examples. I’ll start with an explanation of composition in Windows 8, modify the previous code to show the power of composition, and then highlight a few more existing examples of where composition naturally fits into the Windows 8 UI environment.
Understanding Windows 8 Composition
A Windows 8 UI is built like a tree. You have a single root element that surrounds all other elements, multiple branches containing more elements, and finally many leaves that don’t contain any elements. In shorthand, the structure looks something like this:
Root
Content
Branch
Branch
Leaf
Branch
Leaf
Leaf
Branch
Leaf
You might have noticed that I sneaked in an extra element, Content, in the figure above that I hadn’t talked about yet. Nevertheless, Content is necessary and important in Windows 8 development. The figure above is a generalization of the hierarchical relationship between elements. However, the XAML below, based on the previous post, is a concrete example:
<UserControl x:Class="TwitterClient.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="768" d:DesignWidth="1366">
<Grid x:Name="LayoutRoot" Background="#FF0C0C0C">
<Button Content="Refresh Public Tweets" Height="72" Width="365"
HorizontalAlignment="Left" Margin="500,66,0,0"
Name="RefreshButton" VerticalAlignment="Top"
Command="{Binding RefreshCommand}"/>
<ListBox Height="465" HorizontalAlignment="Left" Margin="5,144,0,0"
Name="PublicTweetListBox" VerticalAlignment="Top" Width="1355"
ItemsSource="{Binding Tweets}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Height="132">
<Image Source="{Binding ImageUrl}"
Height="73" Width="73"
VerticalAlignment="Top" Margin="0,10,8,0"/>
<StackPanel Width="370">
<TextBlock Text="{Binding Name}"
Foreground="#FFC8AB14" FontSize="28" />
<TextBlock Text="{Binding Text}"
TextWrapping="Wrap" FontSize="24" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</UserControl>
The example above gives a better idea of the compositional relationship between elements and how they form a tree that is visually identifiable through proper spacing of elements. UserControl is the Root element and Grid is the Content element for Root. Subsequent elements form a hierarchy, further displaying the compositional nature of Windows 8 UI development.
Since the examples in this post are based on the previous post, you might find it useful to have a few tips on getting from there to here, which is discussed next.
Reusing Previous Code
Over the past couple of posts, I’ve renamed the same project to something new. This is more tedious than necessary, so I’ll just rename the project one more time to something more generic, like TwitterClient. If you’re thinking, “Oh no, not another Twitter client!”, don’t worry. It’s just a sample program – and besides, no one will ever use it.
Here’s a quick walk-through of the file system part of the rename:
- Make a copy of RefactorToMVVM folder in Windows Explorer and rename it to TwitterClient.
- In the new TwitterClient folder, rename the solution file, RefactorToMVVM.sln, to TwitterClient.sln.
- Unhide files and rename RefactorToMVVM.v11.suo to TwitterClient.v11.suo (Alternatively delete because VS11 recreates it for you).
- Rename the project folder, RefactorToMVVM, to TwitterClient.
- In the new TwitterClient project folder, rename the project file, RefactorToMVVM.csproj, to TwitterClient.csproj.
Now your file names are up-to-date, you’ll need to change a couple more items in the solution. To get started on this part, go back to the TwitterClient solution folder and double-click on TwitterClient.sln to open the solution. You’ll see an error saying that VS can’t open the RefactorToMVVM project and that’s okay because you intentionally renamed it – meaning that the solution file won’t be able to find the project file under it’s new name. Click OK for the error message box that appears. The following steps fix the project load problem and take you through the rest of the renaming:
- After the solution loads, right-click on the grayed-out RefactorToMVVM project and select Remove.
- Right-click on the solution, select Add, Existing Project and an Add Existing Project window will appear.
- Navigate to the TwitterClient solution, down to the TwitterClient project, select TwitterClient.csproj and click OK. The new project will load.
- Under the TwitterClient project, double-click Properties to open the Properties configuration page.
- On the Properties Application tab, change both the Assembly name and Default namespaces to TwitterClient.
- Open Tweet.cs (or any code file), select RefactorToMVVM, type Ctrl+R+R, and rename to TwitterClient. Select preview, comments, and strings options and observe all the places in code where the change is made. Click Apply when you’re ready to make the changes.
- Double-click the Package.appxmanifest file, which opens the Package configuration window.
- On the Application UI tab, change Display Name to TwitterClient, Entry Point to TwitterClient.App, and Description to Client Application for Twitter.
- On the Packaging tab, change Package Display Name to TwitterClient.
- Save and close Package.appxmanifest.
- The visual designer for Package.appxmanifest doesn’t let you change everything and there’s one more item to remember. Right-click on Package.appxmanifest, select Open With, select XML Editor, and click OK.
- Under /Applications/Application, change the Executable attribute to TwitterClient.exe.
Before finishing, press F7 to build the solution. If you have errors, it’s most likely because of the naming changes done previously. So, it would be useful to retrace your steps if the error message doesn’t lead you to the answer right away. Now that we have a new renamed solution/project, we can proceed to an in-depth discussion of Composition and Content by adding a button the the tweet list.
Adding a Button
Here, we’re not going to just add a button, we’re going to examine how a button supports composition through its Content property. You’ll see attribute content, element content, and a cool trick that makes it easy to code compositional content in XAML.
If you want a simple button with text, you can use the Content attribute, like this:
<Button Content="{Binding Name}" />
The XAML Content attribute corresponds to a Content property of the Button class. Your first thought, upon seeing the Content property on a Button, might be to ask, “Why isn’t this property named Text?” That’s a logical question, especially if you’ve been using Windows Forms, ASP.NET, or one of many other UI frameworks. Actually, Windows 8 is closer to both Silverlight and WPF in their view of composition and content.
The primary rationale for content is because text isn’t the only object you can display on a button. You can add different types of UI elements to a button by assigning those items to the Content property. In previous frameworks, that don’t support content, you would have needed to slog through extra code to create a special button. With Windows 8, you only need to assign a value to the content property of a given control. Here’s an example for creating a button that contains an image:
<Button>
<Button.Content>
<Image Source="{Binding ImageUrl}"
Height="73" Width="73"
VerticalAlignment="Top" Margin="0,10,8,0"/>
</Button.Content>
</Button>
Above, Button contains an image, which can’t be represented in text, as previously shown via the Content attribute. This example uses Property Element syntax – which is the control type and property name, separated by a dot. The power of this approach to re-defining the appearance of a button can’t be understated – you can see how easy it is to do.
Note: The content property isn’t always named Content. i.e. Types derived from ItemsControl, such as ListBox designate the Items property as their content property.
A control can be decorated with Windows.UI.Xaml.Markup.ContentPropertyAttribute, specifying what the content property is for that control. In the case of Button, the content property is Content (same name):
[ContentProperty("Content")]
public class UserControl : Windows.UI.Xaml.Controls.Control
{
// ...
public UIElement Content { get; set; }
// ...
}
This is good information if you’re a control developer, but it’s also interesting because of a special feature of content properties that gives you simpler syntax. More specifically, you can remove the Property Element syntax, like this:
<Button>
<Image Source="{Binding ImageUrl}"
Height="73" Width="73"
VerticalAlignment="Top" Margin="0,10,8,0"/>
</Button>
The image below is a new snapshot of the updated screen, showing how the images look as buttons. As you can see, customizing buttons is very easy. More to the point, composing custom UI elements is easy via Windows 8 content support.

While this discussion focused on the Button, many other control types have content properties and support composition the same way. If you look back at the XAML in the previous section, “Understanding Windows 8 Composition”, you’ll see several more composition examples, including UserControl/Grid, Grid/Elements, ListBox/ListBox.ItemTemplate, and so on.
Summary
This post demonstrated the inherent support for composition in Windows 8 UI development. This capability is supported via content properties. You saw how Button demonstrates the power of composition and the role of the content property in facilitating composition. Remember that Button is only an example, and you should understand that other controls have content properties.
@JoeMayo
In my previous post, Using LINQ to Twitter in Windows 8 Metro Apps, I cheated a little (some might say a lot) on my UI architecture by using code-behind. In this post, I’ll make it all better by showing you how to separate the model and interaction logic from the UI design – proper separation of concerns.
I’ll accomplish this with a pattern, named Model-View-ViewModel (MVVM), which is widely used for WPF, Silverlight, and (soon) Windows 8 Metro Apps. I’ll start by discussing what MVVM is, move to how I’ll apply it to the previous Windows 8 Metro app, and finish with a step-by-step walkthrough to refactor from code-behind to MVVM.
Understanding MVVM
The subject of whether to use MVVM or not can be debated forever. However, it’s a useful way to achieve separation of concerns in your application and many people like and use it, including myself.
Jeremy Likeness has a nice site that specializes in the subject: MVVM Explained.
Designing Our Implementation
There are a handful of good frameworks for helping you write applications using MVVM. In this app, Since Windows 8 is so new, these frameworks aren’t generally available or ready. However, MVVM is a pattern, not a library, and you can always provide your own code to support the pattern, as you’ll see in this post.
This application will work exactly the same as the original, displaying public tweets when a button is clicked, but the internal implementation will be modified. In particular, the classes and relationship between classes are altered to match the MVVM pattern. The following illustration shows this relationship:

The three objects in the illustration above represent files for implementing a View, ViewModel, and Model. The view is MainPage.xaml, where you can see tweets and click the Refresh button. The model is an object that holds information for a single tweet. Actually, we’ll be working with a list of tweets, which will be held in the ViewModel and bound to the View.
In some diagrams, you’ll see a binding layer between the ViewModel and View, which is an important part of their relationship. In fact the binding relationship can be involved, but this application is so simple that I’ve also opted for a simpler diagram. Besides managing the model and supporting data binding, the ViewModel is instrumental in holding the current state of the view. i.e. if you select a ComboBox option, it’s the View that holds onto the value that is selected. Here’s a breakdown in responsibilities for this app:
- Model: Hold data for a single tweet. Technically, the list of tweets, held by the ViewModel is also a model component – instead of a single instance it’s a collection of instances.
- ViewModel: Hold a list of current tweets and provide a command handler that responds to Refresh button clicks and populates the list of tweets.
- View: Display tweets and let the user click a refresh button.
Refactoring the Model
In the previous post, I named the object bound to the View with a ViewModel suffix, TweetViewModel. To fix this, select the TweetViewModel.cs file, in the Solution Explorer Project, press F2 and change the name to Tweet.cs. You’ll see a message box asking if you want to do a rename and you should click the Yes button, which renames the class name in the file as well as any declarations of that class in the project.
Next, rename the Tweet property, of the Tweet class by selecting the property name, Tweet, press Ctrl+R+R, change Tweet to Text in the New name box of the Rename message box that appears, and click OK. Here’s the updated Tweet class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RefactorToMVVM
{
public class Tweet
{
public string Name { get; set; }
public string Text { get; set; }
public string ImageUrl { get; set; }
}
}
Note: I’ve also done a refactoring of the namespace, LinqToTwitterPublicQuery, to RefactorToMVVM.
Though this class was previously called a ViewModel, the name didn’t capture the essence of what a ViewModel is about: model access, binding, and state management. You’ll see some of this in the next section.
Creating the ViewModel
The ViewModel is often described as “A model of the View”, which is a non-visual abstraction of the view. The ViewModel supports separation of concerns where the concern of designing a UI occurs in the XAML, but the concern of state management and responding to events belongs to the ViewModel. In this simple ViewModel, we’ll add just enough functionality to be architecturally correct, but no more than is needed for this application. More specifically, we’ll create the PublicTweetsViewModel, shown below, that references a model and responds to refresh commands from the View (remember to add a project reference to LinqToTwitter.dll):
using System.Collections.Generic;
using System.Linq;
using LinqToTwitter;
using Windows.UI.Xaml.Data;
namespace RefactorToMVVM
{
public class PublicTweetViewModel : INotifyPropertyChanged
{
public List<Tweet> Tweets { get; set; }
public PublicTweetViewModel()
{
RefreshCommand = new TwitterCommand<object>(OnRefresh);
}
public TwitterCommand<object> RefreshCommand { get; set; }
void OnRefresh(object obj)
{
var twitterCtx = new TwitterContext();
Tweets =
(from tweet in twitterCtx.Status
where tweet.Type == StatusType.Public
select new Tweet
{
Name = tweet.User.Name,
Text = tweet.Text,
ImageUrl = tweet.User.ProfileImageUrl
})
.ToList();
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Tweets"));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
The code above has a constructor, Tweets collection property, RefreshCommand property, OnRefresh method, and PropertyChanged event. The Tweets collection will hold a list of public tweets and is populated by the OnRefresh method. Tracing back, the constructor adds the OnRefresh method as a handler for the RefreshCommand property, using the TwitterCommand, which is a special implementation of ICommand. Here’s the implementation of TwitterCommand, which you should add to another file, named TwitterCommand.cs:
using System;
using Windows.UI.Xaml.Input;
namespace RefactorToMVVM
{
public class TwitterCommand<T> : ICommand
{
readonly Action<T> callback;
public TwitterCommand(Action<T> handler)
{
callback = handler;
}
public bool CanExecute(object parameter)
{
return true;
}
public event Windows.UI.Xaml.EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
if (callback != null) callback((T)parameter);
}
}
}
The TwitterCommand constructor accepts an Action delegate, assigning handler to callback. When the View triggers the RefreshCommand in PublicTweetViewModel, Execute is invoked, which then invokes the callback delegate that the PublicTweetViewModel constructor assigned to the OnRefresh method.
When OnRefresh executes, it isn’t enough to just assign results to Tweets, you must also let the View know it should display the new data. This is where the INotifyPropertyChanged interface helps. The PropertyChanged event is a member of INotifyPropertyChanged and the View listens to this event. The following code is a snippet of PublicTweeViewModel, shown previously, with only the INotifyPropertyChanged related code:
...
public class PublicTweetViewModel : INotifyPropertyChanged
{
...
void OnRefresh(object obj)
{
...
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Tweets"));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
After LINQ to Twitter gets new tweets, OnRefresh fires the PropertyChanged event, passing the property name, Tweets, that changed. This tells the View to re-bind to Tweets.
With the ViewModel in place, all that’s left to do is hook up the ViewModel in the View and complete binding so the View doesn’t use code-behind anymore.
Binding the ViewModel to the View
The first View related task is to fix the code-behind problem. Essentially, remove all unnecessary code from MainPage.xaml.cs. So, you can delete the entire RefreshButton_Click method and set the DataContext for the View, like this:
namespace RefactorToMVVM
{
partial class MainPage
{
public MainPage()
{
InitializeComponent();
DataContext = new PublicTweetViewModel();
}
}
}
Notice how the MainPage constructor sets its DataContext property to an instance of PublicTweetViewModel. I won’t put any more code in the code-behind.
Note: I could have avoided putting any extra code in the code-behind by setting the DataContext in XAML. Unfortunately, the preview version of VS11 doesn’t support that yet. If you do, you’ll see a message like “Method 'add_PropertyChanged' in type 'RefactorToMVVM.PublicTweetViewModel' from assembly 'refactortomvvm.intermediate, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' does not have an implementation. C:\Users\jmayo\Documents\Visual Studio 11\Projects\RefactorToMVVM\RefactorToMVVM\MainPage.xaml RefactorToMVVM”.
Now, all the binding expressions in MainPage.xaml can reference properties of PublicTweetViewModel. This includes binding RefreshButton and PublicTweetListBox, like this:
<UserControl x:Class="RefactorToMVVM.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="768" d:DesignWidth="1366">
<Grid x:Name="LayoutRoot" Background="#FF0C0C0C">
<Button Content="Refresh Public Tweets" Height="72" Width="365"
HorizontalAlignment="Left" Margin="500,66,0,0"
Name="RefreshButton" VerticalAlignment="Top"
Command="{Binding RefreshCommand}"/>
<ListBox Height="465" HorizontalAlignment="Left" Margin="5,144,0,0"
Name="PublicTweetListBox" VerticalAlignment="Top" Width="1355"
ItemsSource="{Binding Tweets}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Height="132">
<Image Source="{Binding ImageUrl}"
Height="73" Width="73"
VerticalAlignment="Top" Margin="0,10,8,0"/>
<StackPanel Width="370">
<TextBlock Text="{Binding Name}"
Foreground="#FFC8AB14" FontSize="28" />
<TextBlock Text="{Binding Text}"
TextWrapping="Wrap" FontSize="24" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</UserControl>
For RefreshButton, remove the Click event handler and replace it with the command binding shown above. This is how the RefreshCommand property in the PublicTweetViewModel, which is an instance of TwitterCommand binds to the button.
Since we already deleted the RefreshButton_Click method from the code behind, we need to tell PublicTweetListBox to get it’s data by binding the Tweets collection, from PublicTweetViewModel, to the ItemsSource property.
Within the DataTemplate for PublicTweetsListBox, each individual tweet binds the same as the previous post. The exception is that you must change the TextBlock binding for the previously named property, Tweet, to Text. If you recall, we changed the Tweet property of the model (also named Tweet) to Text.
That’s it, press F5 to run the application. You’ll notice that it works exactly like the previous application where pressing the Refresh Public Tweets button will load public tweets to the screen.
Summary
In this post, I attempted to redeem myself from the supposed crimes of those who would be offended. Seriously, the MVVM pattern is pretty slick in how it relies primarily on binding and keeps the UI design separate from the implementation. You saw an image of how the previous code would be refactored to support MVVM. Then I took you through a series of steps that refactored the Model, created a new ViewModel and an ICommand implementation. Finally, you learned how to connect the ViewModel to the View and bind the ICommand to the Button and data to a ListBox. The result is an application that works the same as its code-behind predecessor, yet is more maintainable because of the clean separation of concerns that MVVM helps with.
@JoeMayo
While the title of this post suggests focus on LINQ to Twitter, it also indicates that I’ll be discussing how to build a Windows 8 Metro application. The application itself will display a list of tweets from Twitter’s public feed. In the sections that follow, you’ll read background information on pre-requisites to understanding the post, learn how to get LINQ to Twitter working with Visual Studio 11, and then see a step-by-step on how the application is built.
Getting Started
You can build Metro applications with various languages, including C#, C++, JavaScript, and VB. This example uses C#. This post doesn’t dive into the gory details of how this works, but stays at the application level to hit the singular goal of building a simple application. You can visit the MSDN Windows developer center for more details.
The development model for Metro is similar to WPF or Silverlight. The user interface (UI) is built with XAML with a startup App.xaml and MainPage.xaml and associated files. If you haven’t worked with WPF or Silverlight, it would be helpful for you to learn some basic XAML, which you can find with a quick Web (Bing, Google, etc.) search. I’ll be describing the application in terms of XAML, rather than visual designer interaction. If you need a quick intro to C#, check out C# Station.
You’ll also need to install Windows 8 and Visual Studio 11 (VS11), again visiting MSDN Windows developer center for more details for more information.
Note: The “11” in Visual Studio 11 isn’t the year. The version # for Visual Studio is #11 and the beta preview is named Visual Studio 11. This could be confusing because the previous version was #10 and named Visual Studio 2010.
Setting up LINQ to Twitter
LINQ to Twitter works seamlessly with Windows 8 Metro applications, without recompilation. This means that you can visit the LINQ to Twitter download page at CodePlex.com and get the latest version. Since Visual Studio 11 works with the .NET 4.0 (v4.0.30319 as of the preview), you should download the version labeled “LINQ to Twitter .NET 4.0 Binaries“.
Creating the Project
After you open VS11, press Ctrl+Shift+N and you’ll see the following New Project window:

From the New Project window, select Visual C# > Windows Metro Style from the tree view on the left. You have various application types to choose from and each is interesting for learning some basic layout techniques. This post doesn’t cover all those features because I want to show you something simpler. So, select Application from the list and name the file LinqToTwitterPublicQuery. VS creates a new project that looks like this:

After the VS creates the application, you’ll see a new file in the designer and new projects in Solution Explorer. The file, MainPage.xaml, is the default first page to show when your application starts. To keep things simple, we’ll work on MainPage.xaml to display public tweets.
In Solution Explorer, the LinqToTwitterPublicQuery project has various folders and files. The Properties, and References folders serve the same purpose as other .NET project types. The Images folder contains default images for logos and splash screen. You can replace these images with your own. The App.xaml file contains initialization logic/markup to start the application, but we won’t be looking at it in this post, accepting whatever it’s defaults are. The Package.appxmanifest file contains XML formatted configuration information for the application. Double-clicking Package.appxmanifest opens a visual designer that makes it easy to change these parameters, but again we’ll take the defaults. Our primary focus is MainPage.xaml, which I discuss next.
Examining MainPage.xaml
MainPage.xaml is the surface upon which our UI will be built. VS provides a visual designer, giving you drag and drop capabilities to quickly populate the screen with controls. There’s also a more sophisticated UI tool, Blend, that lets you build UI’s. These are nice tools, but the XAML for this application is simple and it’s very useful to be able to work with it, so that’s what I’ll use. Here’s the XAML for MainPage.xaml:
<UserControl x:Class="LinqToTwitterPublicQuery.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="768" d:DesignWidth="1366">
<Grid x:Name="LayoutRoot" Background="#FF0C0C0C">
</Grid>
</UserControl>
If you’re familiar with XML, you’ll notice that the XAML above is XML. Really, it’s a special type of XML used for building UI’s in WPF, Silverlight, and now Windows8. As described by the outer tag, MainPage.xaml is a UserControl. The namespaces are normal for supporting XAML UIs and integration with external tools, such as Blend. You can also see that the width and height are specified as attributes of the UserControl tag, after namespace declarations. The Grid is a layout control that works well for specifying rows and columns. You can change the Background attribute from nearly black, but the darker backgrounds save power, which might be appreciated even more on mobile devices, such as tablets.
Note: XAML is also used in non-UI applications, such as Windows Workflow, but for our purposes here, we’re primarily interested in using it to build UIs.
Peeking at the MainPage.xaml.cs Code-Behind
In addition to XAML, MainPage has a code-behind file, named MainPage.xaml.cs. You can open the code-behind by opening the tree branch by MainPage.xaml in the project. Here’s the code from the code-behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;
namespace LinqToTwitterPublicQuery
{
partial class MainPage
{
public MainPage()
{
InitializeComponent();
}
}
}
The relationship between the MainPage class above and the XAML is that they are partial types of the same class. The syntax in the XAML that indicates its matching partial is the x:Class attribute of the UserControl tag. When you build your project, the XAML transforms to C# code with a partial name of MainPage, as specified by the x:Class attribute and the resulting class has an InitializeComponent method, containing the C# code that creates all the controls specified in the XAML.
Note: I refer to code-behind because of my own familiarity with legacy .NET UI frameworks. Furthermore, the blasphemy continues by ignoring the popular UI architectural practices, such as MVVM. My goal is simplicity and raw functionality, rather than to impress with my pattern prowess (or lack thereof). For those who would be offended, I beg forgiveness in advance.
The code-behind above has a constructor that calls InitializeComponent. The crux of this factoid is that you now know that all controls on the page will be instantiated and initialized after the InitializeComponent method call, making them safe to call. In contrast, those controls don’t exist before the InitializeComponent call. Right-now the XAML and associated code-behind are nearly empty, except for a Grid, the next section discusses what type of data will be shown in the UI.
Tip: Drilling down on MainPage.xaml.cs in the project in Solution Explorer will allow you to see the generated code (build the project first) in a VS generated file named MainPage.g.i.cs.
Building the ViewModel
The ViewModel is a class I’m building to define what information will display in the XAML. The XAML is the View and the data bound to the View is a ViewModel. (Somewhere in this stream, the pattern-police are bound to bust me.) The TweetViewModel in this application is shown below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LinqToTwitterPublicQuery
{
public class TweetViewModel
{
public string Name { get; set; }
public string Tweet { get; set; }
public string ImageUrl { get; set; }
}
}
The properties in the code above will hold data for an individual user’s name, tweet text, and URL where their profile image is stored. Now, lets look at the XAML to see how this data is displayed.
Designing the UI
The look and feel of the UI is defined with XAML, which leads back to MainPage.xaml. We’ll enhance the existing Grid with a Button to load tweets and a ListBox to display the tweets. Here’s the updated MainPage.xaml:
<UserControl x:Class="LinqToTwitterPublicQuery.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="768" d:DesignWidth="1366">
<Grid x:Name="LayoutRoot" Background="#FF0C0C0C">
<Button Content="Refresh Public Tweets" Height="72" Width="365"
HorizontalAlignment="Left" Margin="500,66,0,0"
Name="RefreshButton" VerticalAlignment="Top" />
<ListBox Height="465" HorizontalAlignment="Left" Margin="5,144,0,0"
Name="PublicTweetListBox" VerticalAlignment="Top" Width="1355">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Height="132">
<Image Source="{Binding ImageUrl}"
Height="73" Width="73"
VerticalAlignment="Top" Margin="0,10,8,0"/>
<StackPanel Width="370">
<TextBlock Text="{Binding Name}"
Foreground="#FFC8AB14" FontSize="28" />
<TextBlock Text="{Binding Tweet}"
TextWrapping="Wrap" FontSize="24" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</UserControl>
Within the Grid in the XAML above, there’s a Button and a ListBox. As indicated by its name, Button is for refreshing the list of public tweets, which I’ll describe the inner workings for soon. ListBox normally displays a list of strings as it’s default behavior, but this application needs special formatting for the ImageUrl, Name, and Tweet properties of the bound TweetViewModel instances. This is where data templates come in.
As you can see above the DataTemplate element resides within the ListBox.ItemTemplate property element. The purpose of this DataTemplate is to define the shape of the data to display. The bindings of the data are specified between curly braces, with ImageUrl bound to the Source property of an Image control, Name bound to the Text property of the first TextBlock, and similarly Tweet is bound to the Text property of the second TextBlock.
Tip: When I show you the final image of the application running, you can refer back to this XAML so you can see how each control is positioned.
I’ve explained how the properties of each TweetViewModel instance is bound to the UI, but still need to show you how to bind the entire collection so the ListBox can find it’s data, which is next.
Binding a Collection of Tweets to the UI
To operate this application, the user will click on the RefreshButton, from the MainPage.xaml in the previous section. The Button Click event handler is where the magic happens, where the program uses LINQ to Twitter to get public tweets and binds those tweets to the ListBox. To get started on this part, double-click the Button in the UI (Yes, I know I said everything in the UI would be done by typing XAML, but this is so fun and easy). VS will add a handler to the code-behind and take you there. Here’s the code-behind, populated with code that does the binding:
Note: Be sure to add a project reference to the LinqToTwitter.dll assembly you downloaded earlier.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using LinqToTwitter;
using Windows.Foundation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;
namespace LinqToTwitterPublicQuery
{
partial class MainPage
{
public MainPage()
{
InitializeComponent();
}
private void RefreshButton_Click(object sender, RoutedEventArgs e)
{
var twitterCtx = new TwitterContext();
var tweetVM =
(from tweet in twitterCtx.Status
where tweet.Type == StatusType.Public
select new TweetViewModel
{
Name = tweet.User.Name,
Tweet = tweet.Text,
ImageUrl = tweet.User.ProfileImageUrl
})
.ToList();
PublicTweetListBox.ItemsSource = tweetVM;
}
}
}
The RefreshButton_Click method above is the handler for the Click event of the button, which you can now see if you look at the XAML in your IDE after double-clicking the button. The code above does a normal LINQ to Twitter query for tweets from the public timeline and projects into a List of TweetViewModel.
What’s important to the binding story is that the code assigns the resulting collection to the ItemsSource property of PublicTweetListbox. When the ListBox renders, it iterates through this list, binding each property of each TweetViewModel in the list according to the binding directives specified in the XAML earlier.
To run the application, press F5 and you’ll see a screen with a button but no tweets. Push the button and you’ll see tweets show up in a scrollable list, similar to the image below: 
Summary
You learned how to set up an application with VS11 and the different artifacts that are created for you. I showed you a few things about MainPage.xaml and it’s associated code-behind. Then you saw how to create a ViewModel, specify how to display data from the ViewModel, and how to bind Twitter data to the View. Now you have a working Windows 8 Metro application that displays tweets, via the LINQ to Twitter library.
@JoeMayo
Installing Windows 8 Developer Preview isn’t always simple. It was troublesome on a 32-bit machine, but much easier on x64.
Since Win8’s debut at Build last September, VirtualBox supports installing Win8 natively, so you’ll want to download the latest version of VirtualBox to make sure you don’t have problems.
Another good option is VMWare. They have a free product, VMWare Player, that runs well. The only problem is it doesn’t have native Win8 support, but don’t let that get in the way. This blog post, [Guide]Install Windows 8 on VMware Workstation with VMware Tools, has been helpful for me. Here’s the real trick to getting this to work, as explained in the blog post: instead of loading the OS right away, check the option that say’s you’ll load it manually later. Then, in the hardware configuration for New CD, specify the location of the *.iso file.
Of the two VMs, I prefer VMWare because of it’s display, performance, and ease of use. VirtualBox is easier to install because of the native Win8 support, but it seems cumbersome with display resolution messages popping up and window sizing. In contrast, once you get past the VMWare Player install glitch, everything just works perfectly.
@JoeMayo
Here’s a site, by Lucian Wischik, that contains 101 Async Samples:
http://www.wischik.com/lu/AsyncSilverlight/AsyncSamples.html
There are examples in both C# and VB. Some examples have a selector that lets you toggle between .NET 4.0 and the new Async syntax. Each example has a run button so you can execute and see the return value. Throughout, you’ll see many different ways to use Async. I think it’s a very nice resource.
@JoeMayo
While adding a new feature to the LINQ to Twitter Search API, I made significant changes to the Search entity that will break existing code. The new feature is support for Tweet Entities, a recent addition to Twitter’s Search API. I’ll cover Tweet Entities support after explaining what has changed.
Motivation for Change
When Twitter implemented Tweet Entities for their Search API, they only supported JSON format. LINQ to Twitter used ATOM for Search API queries; so, I didn’t have a choice on data formats. What I found during analysis was that the fields of the JSON format differed significantly from the ATOM format. More specifically, the the ATOM format contains more metadata than what’s necessary in JSON. Since I had to make the switch anyway, I decided to refactor the naming so it matched the JSON format more closely – the benefit being that if you had to look at the Twitter API docs, the match between LINQ to Twitter Search entity property names and the Twitter API docs would be closer. That said, in most cases, the property names are very similar or haven’t changed at all. Overall, the changes, described below, will make the API more approachable and discoverable.
List of Changes
- Search no longer derives from AtomFeed. Instead, all return properties are members of Search. (AtomFeed, AtomEntry, and AtomAuthor types still reside in the library, but they aren’t associated with Search anymore.)
- Returned tweets now reside in the Results property of the Search entity (previously Entries property of AtomFeed), which is a list of SearchEntry.
- SearchEntry has a normal ID, so you no longer need to parse it out like you did with the ID property of AtomEntry.
- The ResultType property is now in a MetaData property, along with number of recent retweets.
- SearchEntry has a CreatedAt property that is a DateTimeOffset of the time returned from Twitter as opposed to being translated in your local time.
- Most existing properties correspond to existing AtomFeed properties, but many names have changed. (i.e. instead of using the Content property, you would now use the Text property)
- Properties no longer supported (don’t appear in the JSON format) include: Alternate, Self, Title, Updated, Language (output), and TwitterWarning.
- The RawResult property of TwitterContext will now contain a JSON formatted response (no longer an ATOM formatted response).
The impact of this change only affects how your application processes returned results from Twitter searches. All input parameters are still the same. These changes facilitate support for Tweet Entities, described next.
The Tweet Entities Enhancement
Tweet Entities are metadata and other bits of information that Twitter extracts from a tweet, saving you the time of parsing the information yourself. Current entities include hashtags, media, urls, and users. Each entity has Start and End position properties in the tweet where it was extracted in addition to other entity-specific details. The following codes shows how to find entities, showing counts of each entity type:
public static void SearchIncludingEntities(TwitterContext twitterCtx)
{
var searchResults =
(from search in twitterCtx.Search
where search.Type == SearchType.Search &&
search.Query == "@rschu" &&
search.IncludeEntities == true &&
search.PageSize == 100
select search)
.SingleOrDefault();
searchResults.Results.ForEach(entry =>
{
Entities entities = entry.Entities;
Console.WriteLine(
"-- Entities --\n" +
"User: " + entities.UserMentions.Count + "\n" +
"Urls: " + entities.UrlMentions.Count + "\n" +
"Hash: " + entities.HashTagMentions.Count + "\n" +
"Media: " + entities.MediaMentions.Count + "\n");
});
}
The Query searches for results from someone I like to follow and whose tweets contain a variety of entity types. Notice that I set IncludeEntities to true to ensure Twitter populates results with entities. Here’s the description of the Search entity so you can see some of the structure and how to find entities:
- Search (this is searchResults above and contains relevant info for the Search instance)
-- … (other properties)
-- Results (List of SearchResult, containing info on tweets and metadata)
--- Entities (Instance of Entities, containing the different entity types)
---- UserMentions (List of UserMention entities)
---- UrlMentions (List of UrlMention entities)
---- HashTagMentions (List of HashTagMention entities)
---- MediaMentions (List of MediaMention entities)
-- … (other properties)
As shown in the code snippet and hierarchy above, the Search.Results.Entities instance contains the entities you can read and use as necessary.
If you’ve previously worked with Status entities in LINQ to Twitter, you might notice similarities. That’s because both the LINQ to Twitter Status and Search entities types are the same.
These changes haven’t been officially released, but you’re welcome to download the LINQ to Twitter source code.
Summary
You’ve seen how I refactored the Search results and how the LINQ to Twitter Search API now supports Tweet Entities. I hope you’ll see that the changes are for the better, trading a bit of discomfort for new functionality.
@JoeMayo
There’s an ongoing discussion in the community about various aspects of the Microsoft Most Valuable Professional (MVP) awards and this is a quick contribution I’ll make to share a few thoughts. Recent events in this discussion include MVPs who either weren’t re-awarded and/or declined their award. There are alignments and differences between their perspectives and mine, particularly in the areas of expectations and values. This is one of my contributions to that on-going discussion.
In it’s simplest form, the MVP program is designed to recognize people who have contributed to the community. Microsoft has provided their definition of an MVP, which I find to be a humbling experience. Some people actively regard themselves as “experts” in their field and live the role through their behavior and words. I’ve met people who describe themselves as “elite” and, regardless of what you think of a person who would make such a declaration, indeed they are often quite capable and their accomplishments are impressive. Perhaps definition, expectation, and reality don’t always align, but no system is perfect and people will often fail to agree on the virtues of that system. My opinion of the MVP award system might not be unique, but there will be people who disagree.
I prefer to subscribe to a school of thought that recognizes the “award” part of the system. Essentially, I did things that Microsoft decides as worthy of recognition. Therefore, they’ve shown appreciation for my efforts by giving me MVP awards. While humbled at the association with a group of respected professionals, I’m mostly grateful for the award and thankful for the recognition. In the United States, we have a common saying, “Don’t look a gift horse in the mouth.”, which means that you shouldn’t be ungrateful when someone gives you a gift. So, I don’t question Microsoft’s motivations, compare whether someone else is more or less deserving, or complain about the quality of the gift. Sometimes it’s good to display grace and thankfulness.
@JoeMayo
I’ve heard people mention, a few times, how they would like for Microsoft to provide a blank template for ASP.NET MVC. The request seems strange because this is something that anyone can do themselves. This isn’t just creating an MVC project and deleting all the items, which I would agree is tedious. Rather, you can create a custom template of any type for reuse and sharing. This blog post shows how to create a custom project template, using the need for a blank MVC template as the use case.
Creating a Base Project
To get started, open Visual Studio. Press Ctrl+Shift+N to create a new project. Then create a new ASP.NET MVC project. The figure below shows how I selected Visual C#/Web from Installed Templates and then selected the ASP.NET MVC 4 Application Template from the list of project types. The name and location are insignificant because this project is an intermediate artifact and can be deleted after the process.

Clicking the OK button, you’ll see another page, allowing you to select the project template type. Here, select Empty Template, shown here:

Here, you might be wondering what this blog post is about if Microsoft already offers a template called “Empty Template”. However, when you click the OK button, you’ll find out that the template isn’t completely empty. You’ll see what I mean by following the steps below on the resulting project.
1. Open the Properties branch and delete AssemblyInfo.cs. This file will be regenerated when you open Properties, click the Application tab, click the Assembly Info button and save new settings. Therefore, you don’t absolutely need it in the template.
2. Open the References folder and you’ll notice many assembly references: some you’ll need and others you might not need. For example, you might want to delete the EntityFramework reference if you use other data access libraries on occasion. You can always add it to a project later, via NuGet. If you look at the file system for the Web app, you’ll see a NuGet packages folder showing how many extra references are being created. If you have NuGet installed, you can execute the following command to remove the package, and it’s associated reference:
> uninstall-package EntityFramework
You can do the same for each of the other packages (and associated references) you want to remove. Otherwise, just delete the reference and associated package folder.
3. Delete the App_Data folder. If you’re like me, your database is already built separately, is never deployed with the application itself, and is rarely and Express version of SQL Server.
4. Content has a default style sheet and jQuery UI themes that you can delete. On any given project, I might use Syncfusion or Telerik components instead of jQuery UI, so having them there isn’t necessary. Additionally, you might have your own CSS Reset file that you prefer instead of the default Site.css.
5. Controllers and Models is already empty, so nothing to do there.
6. The scripts folder contains many *.js files that can be removed. Again, you can remove these via NuGet, as explained in Step #2 above. Otherwise, just delete them. Removing via NuGet will take a few minutes because you’ll receive dependency errors and need to uninstall dependencies (identified in the error message) first.
Tip: If you don’t know the exact package name, just type the first few characters and press Tab, with either fills out the name or shows a list of options.
7. You can remove all the files under Views and Views/Shared, but this might become a little extreme. For example you might need to re-create the Web.config and _ViewStart.cshtml anyway, so the utility of blowing these away might actually be more cumbersome when trying to start a new project. That said, deleting _Layout.cshtml and Error.cshtml is probably fine. If you remove _Layout, you might also remove _ViewStart as it’s default implementation points at _Layout.
8. You can delete Global.asax. it assumes you want areas and global filter registration, which you might or might not care about. Recreating the initial routing isn’t too hard. Alternatively, you can leave Global.asax in-place (because you’ll need it anyway) and delete the parts of the code, such as area registration that you might not need.
9. If you’ve removed all of your packages, you can delete packages.config.
10. You can delete Web.config and its transform files in their entirety, but there’s another option that will keep you from needing to re-add important items. Open web.config and delete the following elements:
a. Delete connectionStrings as it only facilitates writing to a default DB, which you already removed the App_Data folder for.
b. Remove appSettings elements for items you don’t think you’ll need.
c. Your compilation element items are probably important, so you might not want to touch them. Besides, the transform for the Release profile removes the debug option on deployment.
d. Remove the authentication element as it assumes you want forms authentication and refers to a non-existent logon page.
e. The pages element identifies namespaces that you’ll probably want, so you might not want to remove any of them.
f. Remove profile, membership, and rolemanager as they assume you’re using the built-in ASP.NET services.
g. Delete session as you almost never want to run an app in InProc mode.
h. If you know what you’re doing, you can remove system.webserver. Otherwise, you can leave it alone.
i. The runtime settings contain binding redirects so that code trying to reference older MVC components will use newer MVC components instead. Having them there generally doesn’t hurt and can help you avoid havoc when you need the binding redirects and don’t have them. You might want to leave them there.
That’s the last part of Web.config and the last file to delete from the project. Now you can create a custom template based on the choices just made.
Generating the Template
To start the new template creation process, select File –> New Template. You’ll see the first page of the Export Template Wizard, Choose Template Type, shown below:

Make sure Project template is selected and click Next. You’ll see the Select Template Options page, shown below. The Template name will be part of the output file name for the template as well as the project name shown in the New Project window. BlankMvcProject, was selected from the current project name, but you can give it any name you want. Template description, Icon image, and Preview image are what shows up in the New Project template. The template file will be written to the Output location. Selecting Automatically import the template into Visual Studio will make the template available immediately. Display an explorer window on the output files folder will do exactly what it says.

Click Finish and observe that an explorer window pops up in the Visual Studio 2010/My Exported Templates folder with a *.zip file named BlankMvcProject.zip, which contains all the files needed for Visual Studio to offer the template a new project type. Now, you can share and use this template with anyone you like and they can have the same project type.
Using the Template
To share the template, copy the template file (BlankMvcProject) to the Visual Studio 2010\Templates\ProjectTemplates\ folder, under your My Documents folder. You won’t need to do this on your machine if you checked Automatically import the template into Visual Studio while creating the template. However, for everyone else that needs the template, they must add the template to the Visual Studio 2010\Templates\ProjectTemplates\ folder, as just stated. With the template installed, you can create a new project.
To create a new project, based on your new template, open Visual Studio (if not already open) and press Ctrl+Shift+N. Select Visual C# and scroll down the project list until you see the project type named BlankMvcProject. Select BlankMvcProject and click OK.
Final Thoughts
Now you know how to create a bare-bones ASP.NET MVC project. While the discussion focused primarily on removing files, this is an excellent technique for creating custom projects where you might want to either modify existing files or add features that you do use often. Additionally, this technique works for any project type, not just ASP.NET MVC, as it’s a feature of Visual Studio.