Click here to Skip to main content
Click here to Skip to main content
Go to top

Databind XML Feed in Windows 8

, 6 Sep 2013
Rate this:
Please Sign up or sign in to vote.
View a twitter feed in the Windows 8 UI grid - the fast way

Introduction  

NOTE: Since the publishing of this article, Twitter has deprecated it's  REST API v1. The Twitter API will not work with this tutorial. However, the code template can be used with other XML APIs.

Today, I will be going through how easy it is to bind a Twitter API to a Windows 8 UI Grid. In a few lines of code, you will be able to parse XML from the Twitter API into Windows 8 and bind it to the gridview, allowing users to view information quickly and elegantly.

Although I have used Twitter for this example, the concept applies to basically any feed, including JSON (but that's beyond the scope of this tutorial).

The whole project solution can be downloaded here.  

Let's Begin

Let's jump right in. Open up Visual Studio 2012, go to Visual C# > Windows Store > Split App (XAML). Call your project whatever you please, then press Ok. Visual Studio will create the project for you, and you're good to go.

The project created is actually well beyond our needs, so we won't actually use much of the code, and in most cases, you can delete most of the code VS2012 has created for us. But for now, let's add our code.

Here's a summary of what we'll do:

  1. Create a class
  2. Create methods to read and parse the API
  3. Edit the XAML
  4. Done!

Classes

We only need one class for this. So create a new class and call it Tweet.cs. Within it, you will need to have the following properties:

class Tweet  
{ 
    public String Date { get; set; }
    public String UserName { get; set; }
    public String UserMessage { get; set; }
    public String StatusNumber { get; set; }
}

And we're done!

Create a Method

Now go back to Itemspage.xaml.cs and create a method called GetXmlAsync(). Twitter gives you API access to the public feeds of users. For this tutorial, I will be using the feed of Appavate - my front on various app stores.

We will get the twitter feed Async, use a bit of LINQ and bind it to our Tweet properties.

Please see the code below:

public async void GetXmlAsync()
{
    try
    {
        var client = new HttpClient();
        var response = await client.GetAsync(
          "http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=Appavate");
        var text = response.Content.ReadAsStringAsync();

        XElement xmlTweets = XElement.Parse(text.Result);
        IEnumerable<Tweet> data = from tweet in xmlTweets.Descendants("status")
                                      select new Tweet
                                      {
                                          UserName = tweet.Element("user").Value,
                                          UserMessage = tweet.Element("text").Value,
                                          Date = tweet.Element("created_at").Value,
                                          StatusNumber = tweet.Element("id").Value
                                      };
        itemGridView.DataContext = data;
    }
    catch (Exception) // Not best practice
    {
    }
}

Remember to add the method to OnNavigatedTo or to the constructor of ItemsPage.xaml.cs.

Add the relevant namespaces and you're done!

XAML

The XAML needs a small adjustment. Open up ItemsPage.xaml and come down to itemGridView. Here, change the ItemsSource field to ItemsSource="{Binding}".

It should look like this now:

<GridView
        x:Name="itemGridView"
        AutomationProperties.AutomationId="ItemsGridView"
        AutomationProperties.Name="Items"
        TabIndex="1"
        Grid.RowSpan="2"
        Padding="116,136,116,46"
        ItemsSource="{Binding}"
        ItemTemplate="{StaticResource Standard250x250ItemTemplate}"
        SelectionMode="None"
        IsSwipeEnabled="false"
        IsItemClickEnabled="True"
        ItemClick="ItemView_ItemClick"/>

Standard Styles

Now we need to actually bind the data. For this, we will edit the template in the standard styles sheet. So in the project folder, go to Common > StandardStyles.XAML. Scroll down or Ctrl + F to "Standard250x250ItemTemplate".

We will need to make some changes to this. Remember the Tweet class? We're going to add that stuff in here. Within the StackPanel, we can change the bindings of the TextBlocks. Go ahead and change it to our Properties.

It should look like this when you're done:

<DataTemplate x:Key="Standard250x250ItemTemplate">
    <Grid HorizontalAlignment="Left" Width="250" Height="200">
        <StackPanel VerticalAlignment="Bottom" 
                  Background="{StaticResource ListViewItemOverlayBackgroundThemeBrush}">
            <TextBlock Text="{Binding UserMessage}" 
                Foreground="{StaticResource ListViewItemOverlayForegroundThemeBrush}" 
                Style="{StaticResource TitleTextStyle}" 
                Height="Auto" Margin="15,0,15,0"/>
            <TextBlock Text="{Binding UserName}" 
              Foreground="{StaticResource ListViewItemOverlaySecondaryForegroundThemeBrush}" 
              Style="{StaticResource CaptionTextStyle}" 
              TextWrapping="NoWrap" Margin="15,0,15,10"/>
            <TextBlock Text="{Binding Date}" 
              Foreground="{StaticResource ListViewItemOverlaySecondaryForegroundThemeBrush}" 
              Style="{StaticResource CaptionTextStyle}" 
              TextWrapping="NoWrap" Margin="15,0,15,10"/>
        </StackPanel>
    </Grid>
</DataTemplate>

For this tutorial, I don't have an image binded, but it's the same process.

Note: For the purposes of speed, this may be a bit ugly when viewed. But you can always come back to this and make it pretty.

One Last Thing...

Right now, it'll show the feed, but when a user clicks on one of the tweets, the app won't know what to do. Let's fix that:

private void ItemView_ ItemClick(object sender, ItemClickEventArgs e)
{
    string id = ((Tweet)e.ClickedItem).StatusNumber;
    string baselink = "https://twitter.com/Appavate/status/";

    string uri = baselink + id;
    Launcher.LaunchUriAsync(new Uri(uri));
}

This will simply open up a browser and take you to that tweet. You can just as easily implement something that takes the user deeper into your app or somewhere else.

Let's Run It...

We're pretty much done now. Go the solution folder, build, then run it on the local machine or the simulator. The feed should now appear like this on the grid:

You've successfully bound a Twitter feed to the Windows 8 Grid!

Wasn't that easy?

Some Things to Note

  • This won't be the prettiest thing in the world. You'll need to edit some XAML to make it look great.
  • It is kind of useless to users if all it does is show you the feed and doesn't let them go any further. In the class above, there is a property called "statusnumber" which is unique to all tweets. You can use this as a way of pointing users in the right direction.

If you get stuck, I've uploaded the solution here.

If you're still stuck, try StackOverflow, post a comment or flick me an email, I'll be happy to help you.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

JayJanarthanan
Founder Microsoft NZ, Appavate
New Zealand New Zealand
Founder of Appavate and MSP at Microsoft NZ. I specialise in mobile apps for Android, Windows Phone and Windows RT. I also play around with Windows Azure and Amazon Cloud. I also love experimenting with automation technology. Particularly cheap and cost effective ones such as Raspberry Pis.
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
QuestionNot working with the Rest api v1.1 PinmemberJohn Ripper20-Jun-13 3:01 
AnswerRe: Not working with the Rest api v1.1 PinmemberJayJanarthanan6-Sep-13 17:31 
QuestionWOW! It works FIRST time! PinmemberPHenry29-May-13 18:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140922.1 | Last Updated 7 Sep 2013
Article Copyright 2013 by JayJanarthanan
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid