Metro Style Application – How to Work with Data and Controls Using C#

Introduction:

Using Microsoft .NET framework,
developers can now create a Metro style
application
with C++, C#, VB.Net, HTML5 and JavaScript. Like any other
data driven applications you can display data in Metro application controls too.
Metro Application Type allows developers to create the applications in various
platforms like web, desktop, tablets and mobile devices. In Metro Applications
data can be a simple value, a business object or a collection of business
objects and you can bind data with simple controls like TextBox or with a data
control like ListBox, ListView etc. In this article I will explain, how to bind
different controls to a single item or bind a collection of items to a data
control.

Binding a Single Item to a Control

The following example shows how to bind a
control to a single item. Output will be generated to a text property of a
text box control and the source is a class called ‘Car’.

To
develop this sample application, start Visual
Studio 2011
, select file > new project. This will open new project
dialog box. Now, select language Visual C#. Next you need to select an
application type from the center pane (Windows metro style template type)
“Application” type.

Visual Studio 2011: New Project
Figure 1: Visual Studio 2011: New Project

Next,
enter a name for your project and click Ok. This will save your project in the path
you have mentioned. Visual Studio will also create a project shown in the
screen shot.

Visual Studio 2011: Application 1
Figure 2: Visual Studio 2011: Application 1

To
bind a Car details in a text box, the control’s Text property is set
to a Binding by using a
markup extension. The Car class has three public properties and an override
method ToString(). The
properties are Brand, Model, and Price. The ToString() method is called on a
bound object for display purposes.

The
DataContext property
for the TextBox control is set
to a new Car object to bind it with Car details. Check XAML code.

MainPage.xaml

<UserControl x:Class="DataBinding.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">
        <TextBox x:Name="textBox1" Text="{Binding}" FontSize="28"
         Height="130" Width="420" IsReadOnly="True"
         TextWrapping="Wrap" AcceptsReturn="True" />
    </Grid>
  </UserControl>

MainPage.xaml.cs

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 DataBinding
{
    partial class MainPage
    {
        public MainPage()
        {
            InitializeComponent();
             //Set the data context.
            txtCar.DataContext = new Car("Honda", "Civic", "23000");
        }
 
 
        // A Business object of a Car
        public class Car
        {
            public Car() { }
 
            public Car(string BrandName, string ModelName, string MarketPrice)
            {
                Brand = BrandName;
                Model = ModelName;
                Price = MarketPrice;
            }
 
            public string Brand { get; set; }
            public string Model { get; set; }
            public string Price { get; set; }
 
            // Overriding the ToString method
            public override string ToString()
            {
             return "The Brand New " + Brand + " - " + Model + ", at price: " + Price;
            }
        }
    }
}
 

Output…

“The Brand New Honda – Civic at price:$24000”

Binding a Collection of Items to a Control

In this section we will see how to bind a collection of
business objects to a data control. We will bind data with a Dropdown list.

First, we will create an object called Cars of List<>
collection type, which is a strongly typed list. Then we will add class objects
to this list collection and finally we will bind the object Cars to Dropdown
list with the help of DataContext. Have a look at the XAML code.

MainPage.xaml

<UserControl x:Class="DataBinding.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="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
        <ComboBox x:Name="cboCars" ItemsSource="{Binding}"
        Foreground="Black" FontSize="30" Height="50" Width="780"/>
    </Grid>

</UserControl>

MainPage.xaml.cs

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
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 DataBinding
{
    partial class MainPage
    {
 
        public List<Car> Cars = new List<Car>();
 
        public MainPage()
        {
            InitializeComponent();
 
            // Add items to the collection.
            Cars.Add(new Car("Honda", "Civic", "22000"));
            Cars.Add(new Car("Audi", "A3", "30000"));
            Cars.Add(new Car("BMW", "Alpina", "122000"));
 
            // Set the data context for the combo box.
            cboCars.DataContext = Cars;
        }
 
        // A Business object of a Car
        public class Car
        {
            public Car() { }
 
            public Car(string BrandName, string ModelName, string MarketPrice)
            {
                Brand = BrandName;
                Model = ModelName;
                Price = MarketPrice;
            }
 
            public string Brand { get; set; }
            public string Model { get; set; }
            public string Price { get; set; }
 
            // Overriding the ToString method
            public override string ToString()
            {
             return "The Brand New " + Brand + " - " + Model + ", at price: " + Price;
            }
        }
 
    }
 
  }
 
 

Output…

Main Page XAML Output
Figure 3: Main Page XAML Output

Binding Data in Data Template

You can customize the display of data by using a
DataTemplate. It enables you to customize the items to display in a control.
It uses ContentTemplate or ItemTemplate property of a content or item control. The
following example shows the same list of Cars binding with a Dropdown list box
by using a data template. A Dropdown list box is an ItemsControl, so we
can use the ItemTemplate property.

MainPage.xaml

<UserControl x:Class="DataBinding.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">
        <ComboBox x:Name="cboCars" ItemsSource="{Binding}" Foreground="Black" FontSize="30" Height="Auto" Margin="301,232,576,502">
            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal" Margin="2">
                        <TextBlock Text="{Binding Brand}" Margin="2" />
                        <TextBlock Text="-" Margin="2" />
                        <TextBlock Text="{Binding Model}" Margin="10,2,0,2" />
                        <TextBlock Text=", at Price:" Margin="2" />
                        <TextBlock Text="{Binding Price}" Margin="10,2,0,2" />
                    </StackPanel>
                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>
    </Grid>
   
</UserControl>

In this XAML code, you can see the data template definition.
The data template contains a StackPanel with five TextBlock controls. Three
of the TextBlock controls are bound to the Brand, Model and Price properties of
a Car object. The other two TextBlock controls display static text. As in the
previous example, this binding is done with data context to be set to the list
of Cars.

MainPage.xaml.cs

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
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 DataBinding
{
    partial class MainPage
    {
 
        public List<Car> Cars = new List<Car>();
 
        public MainPage()
        {
            InitializeComponent();
 
            // Add items to the collection.
            Cars.Add(new Car("Honda", "Civic", ""));
            Cars.Add(new Car("Audi", "A3", "30000"));
            Cars.Add(new Car("BMW", "Alpina", "122000"));
 
            // Set the data context for the combo box.
            cboCars.DataContext = Cars;
        }
 
        // A Business object of a Car
        public class Car
        {
            public Car() { }
 
            public Car(string BrandName, string ModelName, string MarketPrice)
            {
                Brand = BrandName;
                Model = ModelName;
                Price = MarketPrice;
            }
 
            public string Brand { get; set; }
            public string Model { get; set; }
            public string Price { get; set; }

        }
 
    }
 
  }
 

Main Page XAML Output
Figure 4: Main Page XAML Output

List of New Binding Controls

I
have mentioned a list of new controls, which can be used in your Metro style
application.

ApplicationBar – Provides a toolbar for displaying application-specific commands.

<ApplicationBar VerticalAlignment="Bottom">
   <StackPanel Orientation="Horizontal">
       <!--ApplicationBar buttons use a style defined by the application.-->
       <Button Style="{StaticResource AppBarButtonStyle}" HorizontalAlignment="Right">Back</Button>
   </StackPanel>
</ApplicationBar>

CarouselPanel- Represents a panel that presents its items on a surface with a viewport, and includes
scrolling capabilities and item virtualization.

CaptureElement – Represents
a media capture from a capture device, for example recorded video content.

FlipView – Displays
a collection of items that the user can flip through one item at a time.

<FlipView Width="350" Height="150">
     <FlipViewItem>
        <Image Width="100" Height="100" Source="Images/Logo.png"/>
     </FlipViewItem>
     <FlipViewItem>
        <Image Width="100" Height="100" Source="Images/SplashScreen.png"/>
     </FlipViewItem>
</FlipView>

JumpViewer
Enables
the user to zoom between two views from a collection of items.

<Grid x:Name="LayoutRoot" Background="Black">
   <JumpViewer x:Name="jumpViewer" VerticalAlignment="Bottom">
   <JumpViewer.JumpView>
     <GridView x:Name="gvCars" Width="1100" 
        ScrollViewer.HorizontalScrollBarVisibility="Visible" Canvas.Left="200">
        <GridView.ItemTemplate>  
          <DataTemplate>
            <StackPanel Orientation="Vertical">
              <TextBlock Text="{Binding Brand}" Width="220" Height="10"        FontSize="11" />
            <TextBlock Text="{Binding Model}" Width="220" Height="10" FontSize="11" />
            </StackPanel>
          </DataTemplate>
        </GridView.ItemTemplate>
     </GridView>
   </JumpViewer.JumpView>
  <JumpViewer.ContentView>

ProgressRing – Indicates
progress by displaying a ring.

  <ProgressRing IsActive="True"/>

ToggleSwitch – Represents
a switch that can be toggled between 2 states.

	<ToggleSwitch Header="logo" IsOn="True"/>

VariableSizedWrapGrid – Provides
a grid-style layout panel where each tile/cell can be variable size based on
content. It Provides two attached properties for XAML usage –

	VariableSizedWrapGrid.ColumnSpan

	VariableSizedWrapGrid.RowSpan

These attached properties can be set on any child elements
in the VariableSizedWrapGrid in order to have particular child elements
use a spanning logic for layout.

<VariableSizedWrapGrid>
            <Image Name="Cars" VariableSizedWrapGrid.ColumnSpan="2" VariableSizedWrapGrid.RowSpan="2"/>
</VariableSizedWrapGrid>

WrapGrid – Positions
child elements sequentially from left to right or top to bottom. When elements
extend beyond the container edge, elements are positioned in the next row or
column.

<WrapGrid FlowDirection="LeftToRight">
   <TextBlock Text="{Binding Brand}" Width="220" Height="10" FontSize="11" />
   <Image Name="MyBigImage" Height="20px" Width="20px" />
</WrapGrid>

Conclusion

Metro style apps are full screen
apps and development is very easy. Microsoft .NET APIs for Metro style apps
provide a managed environment for the development of apps using C# or Visual
Basic. Enhancements are still in progress and hopefully in the near future
developers will get many more tools and features.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read