Microsoft Gulf Technical Community

The communication portal for the Gulf technical audience

Creating a simple News App on Windows 8 for Beginners

Creating a simple News App on Windows 8 for Beginners

Rate This
  • Comments 6

This tutorial helps a beginner build his first Windows 8 News App in a really simple, easy and quick way, also improving his understanding of the MVVM model that is used in this design.

Basic Start:

    1. Create a New Project –> Windows Store –> Blank App (XAML) (Visual C#).
    2. Delete MainPage.xaml and add a new item to the project. Let this new item be a Grouped Items Page with the title of MainPage.xaml. Doing this automatically adds the Common folder which contains many useful classes like Bindable Base and the Layout Aware Page.
    3. To change the title from “My Application” click on the pageTitle TextBlock or the title in deign view and click on the binding of the Text Property and select go to source. There you will see this XAML code :

<x:String x:Key="AppName">My Application</x:String>

Here change the “My Application” to anything you please like News App.

  1. Delete the itemGridView and itemListView items in the main grid.
  2. Add a ScrollViewer to the second row of the main Grid and reset layout so that it occupies the entire area. As we want a horizontal Scroll viewer, go to the style property of the newly added ScrollViewer and change its value to the HortizontalScrollViewerStyle which is under Local Resource in the binding.
  3. Place a StackPanel inside this ScrollViewer and reset its layout and change its orientation to Horizontal. Also give it a left margin of 120 so that it aligns with the first letter of the Title and a bottom margin as desired. Use a StackPanel and not a grid so that item groups are stacked one after another.

Creating the models:   

    1. A Model is the basic element that is present in your application. In this app we have two models – News and Video
      1. News
        1. Title
        2. ImagePath
        3. Details
        4. ShortTitle
      2. Video
        1. Title
        2. ImagePath – path to the thumbnail of the image
        3. VPath – the link to the video
    2. The models are C# classes that can be created in a new folder in your project. So, add a new folder to your project named models and add a new C# file called news to it. First make the class public and add in the declaration into the class as given below :

public class News
{
    public string title { get; set; }
    public string imgpath { get; set; }
    public string shortTitle { get; set; }
    public string details { get; set; }
}

    1. Similarly create a C# file named Video with the class definition as given below:

public class Video
{
    public string title { get; set; }
    public string imgpath { get; set; }
    public string vpath { get; set; }
    public string shortTitle { get; set; }
}

Creating the View:

    1. The models have been set up so let’s move to the View. We need 3 items in the stack panel -
        1. TopStory grid
        2. News Grid containing a GridView for each News element
        3. News Grid containing a GridView for each Video element

image

    1. Add a grid – Reset Layout – set a specific width (say =500) leaving the height as Auto– rename it TopStoryGrid – make 3 rows
        1. First with a specific height (say 50) for the TextBlock containing “Top Story>”.
        2. An image spanning 2 rows.
        3. A rectangle with a TextBlock to hold the title of the Top story.

image

Further I have added a background to the TopStoryGrid with 50% opacity to give the nice semi-transparent black-grey coloring for the grid.

    1. Copy paste the above grid as the second item of the stack panel and rename it as NewsGrid. This grid will contain 2 rows:
      1. The first containing a Textblock to hold the “News>” caption.
      2. The second containing a gridView which will have the News Items.

So, leaving the title delete the other items in the NewsGrid. Also delete one extra row from the xaml and add a gridView to the second row.

  1. Repeat step 3 and create the VideoGrid with the textblock containing “Video>”
  2.         

Creating the ViewModel:

    1. The models and view have been set up so let’s move to the ViewModels and populate this application with dummy data. A viewmodel is a C# file that holds the data structure and design time data for the view. Create a new folder called ViewModels and add a C# file titled MainPageViewModel. We have 3 main items in our view:
      1. For the first i.e the Top Story, create an object of the class News

private News topstory = new News();
public News Topstory
{
    get
    {
        return topstory;
    }


    set
    {
        SetProperty(ref topstory, value);
    }
}

      1. For the gridview of the news, create a List or ObservableCollection of News and instantiate it in the similar way as above.

private List<News> allnews;
public List<News> Allnews
{
    get
    {
        return allnews;
    }
    set
    {
        SetProperty(ref allnews, value);
    }

}

      1. Similarly create a List for the gridView of the videos.

private List<Video> videos;
public List<Video> Videos
{
    get
    {
        return videos;
    }
    set
    {
        SetProperty(ref videos, value);
    }

}

    1. Add dummy data to the Lists and objects created in the constructor of this class

public class MainPageViewModel : BindableBase
{

    private List<News> allnews;
    public List<News> Allnews
    {
        get
        {
            return allnews;
        }
        set
        {
            SetProperty(ref allnews, value);
        }

    }
    private News topstory = new News();
    public News Topstory
    {
        get
        {
            return topstory;
        }
        set
        {
            SetProperty(ref topstory, value);
        }
    }

    private List<Video> videos;
    public List<Video> Videos
    {
        get
        {
            return videos;
        }
        set
        {
            SetProperty(ref videos, value);
        }

    }
    public MainPageViewModel()
    {
        #region News
        Allnews = new List<News>();
        Allnews.Add(new News
        {

                title = "Paolo Di Canio a 'great move' for Sunderland, says Jeremy Wray",

                shortTitle = "Paolo Di Canio will be 'fantastic' for Sunderland, according to the man who gave him his first managerial job.",

                imgpath = "http://news.bbcimg.co.uk/media/images/66692000/jpg/_66692666_paulo_di_canio_getty.jpg",

            details = "Sample details"

        });
        Allnews.Add(new News
        {
            title = "Cyprus economy 'on the brink', Bank of Cyprus warns",
            shortTitle = "The Cypriot economy is 'on the brink' and desperately requires a liquidity lifeline from Europe, Cyprus' largest bank has warned.",
            imgpath = "http://news.bbcimg.co.uk/media/images/66541000/jpg/_66541436_cypsideatmafp.jpg",
        details = "Sample details"

        });
        Allnews.Add(new News
        {
            title = "Yityish Aynaw: First black Miss Israel will go to the ball",
            shortTitle = "It's been an astonishing three weeks for Yityish Aynaw, an immigrant orphan from Ethiopia, who became the first black Miss Israel last month, and has now been invited to Thursday's gala dinner with visiting US President Barack Obama.",
            imgpath = "http://news.bbcimg.co.uk/media/images/66502000/jpg/_66502758_new-crop-of-miss-israel.jpg",
             details = "Sample details"

        });

        #endregion


        Topstory = new News
        {
            title = "Welfare system reforms are fair, says Iain Duncan Smith",
            imgpath = "http://news.bbcimg.co.uk/media/images/66692000/jpg/_66692078_calculator_eyewire.jpg",
            shortTitle = "Changes to the UK's welfare system are fair, Work and Pensions Secretary Iain Duncan Smith has insisted, as some of the changes came into effect.",
            details = "Sample details"
        };

        #region Videos
        Videos = new List<Video>();
        Videos.Add(new Video
        {
            title = "Giant hailstones batter China's southern provinces",
            shortTitle = "Heavy storms and giant hailstones have left at least nine people dead and caused serious damage across China's southern provinces.",
            imgpath = "http://news.bbcimg.co.uk/media/images/66534000/jpg/_66534519_acarwindshieldbatteredbyhailstones.jpg",
            vpath = "http://static.clipcanvas.com/sample/clipcanvas_14348_offline.mp4"

        });
        Videos.Add(new Video
        {
            title = "Mystery of Chile's crustacean carpet",
            shortTitle = "Authorities in Chile are investigating why thousands of prawns were washed up on a beach in the coastal city of Coronel, covering it with a layer of pink.",
            imgpath = "http://news.bbcimg.co.uk/media/images/66518000/jpg/_66518070_red2.jpg",
            vpath = "http://static.clipcanvas.com/sample/clipcanvas_14348_offline.mp4"

        });
        Videos.Add(new Video
        {
            title = "The Philippines firearms industry booms",
            shortTitle = "Owning a firearm is not illegal in the Philippines and manufacturing guns has become a lucrative job for many locals.",
            imgpath = "http://news.bbcimg.co.uk/media/images/66518000/jpg/_66518018_makinggunsatshootersarms2.jpg",
            vpath = "http://static.clipcanvas.com/sample/clipcanvas_14348_offline.mp4"

        });
}

 

Data Binding:

    1. Build project and now let’s connect the view model to the view.
      1. Set data context of Main Grid as MainPageViewModel
      2. Bind source of the Top Story image to the imgpath of the TopStory object in the MainPageViewModel
      3. Bind the Text property of the Top Story Textblock with the title of the TopStory object in the MainPageViewModel

      1. Bind the ItemSource of the News GridView with the AllNews object (which is the list of news items) in the MainPageViewModel
      2. Bind the ItemSource of the Videos GridView with the Videos object (which is the list of video items) in the MainPageViewModel
      3. Now right click on the added gridView – Edit Additional Templates – Edit generated items (Item Template) – Create empty to edit the Item template of the GridView. Now resize the grid to say width = 200 and height = 200. Make two rows in this grid and let it contain an image that spans the 2 rows and rectangle with a textblock inside in the second row which will contain the title of the news.
      4. Bind the source property of the image to the imgpath of the Allnews object.
      5. Bind the text property of the TextBlock to the title of the Allnews object.

    1. Once done repeat steps 6,7 and 8 for the VideoGrid but when you customize the item template of the gridview add a play image stretched in the first grid to just add the effect of a video.

image

Creating a News Detail Page:

    1. Now let’s make an Item page for displaying the News Item when they are clicked. Add a new item – Item Detail Page. And delete the following code from the XAML to get rid of the flipview
      1. <FlipView
                   x:Name="flipView"
                   AutomationProperties.AutomationId="ItemsFlipView"
                   AutomationProperties.Name="Item Details"
                    TabIndex="1"
                   Grid.RowSpan="2"
                   ItemsSource="{Binding Source={StaticResource itemsViewSource}}">

           <FlipView.ItemContainerStyle>
               <Style TargetType="FlipViewItem">
                   <Setter Property="Margin" Value="0,137,0,0"/>
               </Style>
           </FlipView.ItemContainerStyle>

           <FlipView.ItemTemplate>
               <DataTemplate>

      1. The entire VisualStateManager.VisualStateGroups element in the User Control
      2. </DataTemplate>
             </FlipView.ItemTemplate>
        </FlipView>
    1. Add a static class called selected in a folder called Helpers. This class will help us selecting in the chosen news item.

public static class selected
{
    public static News SelectedNews;
    public static Video SelectedVideo;
}

    1. Create a ViewModel for this page.

public class NewsDetailsPageViewModel : BindableBase
{

        public News news { get; set; }
         public NewsDetailsPageViewModel()
         {
             news = new News
             {
                 title = "News",
                 shortTitle = "This is News Details Page",
                imgpath = "http://4.bp.blogspot.com/-z5YGJb3fOPU/T_6IASiq_tI/AAAAAAAABFk/8isioafcrHA/s1600/NewsFlash_Microphone_bolts_symbol.jpg",
                 details = "Sample details"
             };
     }
}

    1. Now bind the elements of the Page with the viewmodel.
      1. Bind Main Grid’s Datacontext to NewsDeatilsPageViewModel
      2. Bind the Text property of the PageTitle’s Textblock to the Title of the news item in the NewsDeatilsPageViewModel
      3. Bind the Source property of the image in the Rich Text Block to the imgpath of the news item in the NewsDeatilsPageViewModel
    2. Remove

<Paragraph>
    <Run FontWeight="Light" FontSize="26.667" Text="{Binding Title}"/>
    <LineBreak/>
    <LineBreak/>
    <Run FontWeight="Normal" Text="{Binding Subtitle}"/>
< /Paragraph>

    1. And bind the details of the news item to the text in the rich text block by replacing “content” with “news.details” in the below statement

<Run FontWeight="SemiLight" Text="{Binding Content}"/>

Establishing navigation between the pages:

    1. Change the gridView SelectionMode to none and enable the ItemClick.
    2. Create an ItemClick event for the News GridView and add the below code in the class

private void GridView_ItemClick_1(object sender, ItemClickEventArgs e)
{
     var selecteditem = e.ClickedItem as News;
    if (selecteditem == null)
         return;
     selected.SelectedNews = selecteditem;
     this.Frame.Navigate(typeof(NewsDetailPage));
}

Here we are assigning the item that is clicked to the SelectedNews variable of the selected class.

    1. Add the below code to the loadstate method in the NewsDetailPage.xaml.cs

NewsDetailsPageViewModel vm = new NewsDetailsPageViewModel();
vm.news = selected.SelectedNews;
this.MainGrid.DataContext = vm;

Here we have created an object of the viewmodel, set its value to be equal to the chosen news item and then set the data context of the grid to this object.

    1. To use this same page for displaying the top story, add a Tapped event to the TopStoryGrid and define it as given below:

private void TopStoryGrid_Tapped(object sender, TappedRoutedEventArgs e)
{
    var selecteditem = ((sender as Grid).DataContext as MainPageViewModel).Topstory;
    selected.SelectedNews = selecteditem;
    this.Frame.Navigate(typeof(NewsDetailPage));
}

Creating Video Detail Page:

    1. Add an Item Detail Page to the project named VideoDetailPage and remove the entire flipview element.
    2. Add a MediaElement to the second row of the main grid and give it a name say video.
    3. Create a VideoDetailPageViewModel similar to the NewsDetailsPageViewModel.

public class VideoDetailPageViewModel : BindableBase
{
    public Video Video { get; set; }
    public VideoDetailPageViewModel()
    {
        Video = new Video
        {
            title = "Harlem Shake",
            shortTitle = "Do the Harlem Shake",
            imgpath = "http://static.belfasttelegraph.co.uk/incoming/article29085376.ece/ALTERNATES/h342/harlem-shake.jpg",
            vpath = "http://static.clipcanvas.com/sample/clipcanvas_14348_offline.mp4"
        };
    }

}

  1. Establish the navigation between the pages in the similar fashion as above stated.
  2. The source to the MediaElement will have to be type casted so add the below line while creating an object of the viewmodel in the loaded method of the VideoDetailPage:

video.Source = new Uri(vm.Video.vpath);

image

 

Sharing the News Details Page:

    1. Add the following using statements to the top of the NewsDetailsPage

using Windows.ApplicationModel.DataTransfer;

using System.Text;

using Windows.Storage.Streams;

    1. To the Loaded method register the DataRequested event for the CurrentView using the below statement.

DataTransferManager.GetForCurrentView().DataRequested += OnDataRequested;

    1. Add the below statements to the new method created (OnDataRequested)

private void OnDataRequested(DataTransferManager sender, DataRequestedEventArgs args)
{
     var request = args.Request;
     var item = selected.SelectedNews; // this assigns item to the chosen news item
     request.Data.Properties.Title = item.title; //this statement assigns the news title to the title of the share page
    request.Data.Properties.Description = "News";
   string htmlExample = "<p> <img src=\"" + item.imgpath + "\"> "+ item.details+"</p>";//this is the Html format for displaying the text and image on the share page
   string htmlFormat = HtmlFormatHelper.CreateHtmlFormat(htmlExample);
   request.Data.SetHtmlFormat(htmlFormat);

// Because the HTML contains a local image, we need to add it to the ResourceMap.
RandomAccessStreamReference streamRef =
     RandomAccessStreamReference.CreateFromUri(new Uri(item.imgpath));
request.Data.ResourceMap[item.imgpath] = streamRef;

}

  1. Unregister the DataRequested method in the SaveState method.

protected override void SaveState(Dictionary<string, object> pageState)
{
    DataTransferManager.GetForCurrentView().DataRequested -= OnDataRequested;
}

 

 

I have attached the source code of this app with this project for your reference. Enjoy building!

Attachment: NewsAppFinal1.zip
  • The link to the file is just below the display picture of Deepti in case if anyone doesn't find it! :)

  • Wohooo ! Thanks Deepti! It's a really good tutorial for beginners ! :D

  • That's a great tutorial! Good job on in it!

  • Good one even for one who worked on. Net 2.0 3.5

  • excellent. thanks...

  • Deepthi, Amazing. infact my first full fledged trial.. Great work!!

    Any more tutorials of this kind anywhere ??

Page 1 of 1 (6 items)
Leave a Comment
  • Please add 4 and 5 and type the answer here:
  • Post