Introduction to data binding for Windows Store Apps

Today we will discuss how to data bind control in windows store applications using c#.

Create a blank windows store apps and open MainPage.xaml and replace the grid with the following code

we will create grid that contain text box , to show the data in

<Grid x:Name="LayoutRoot" Background="#FF0C0C0C">
  <TextBox x:Name="textBox1" Text="{Binding}" FontSize="30"
    Height="120" Width="440" IsReadOnly="True"
    TextWrapping="Wrap" AcceptsReturn="True"/>
<Grid/>

Now open the MainPage.xaml.cs file and repalce the code with the following.

 

we will have class that bind the data to the text field (recording) 

(string artistName, string cdName, DateTime release)

public MainPage()
{
    InitializeComponent();

    // Set the data context to a new Recording.
    textBox1.DataContext = new Recording("Chris Sells", "Chris Sells Live",
        new DateTime(2008, 2, 5));
}

// A simple business object
public class Recording
{
    public Recording() { }

    public Recording(string artistName, string cdName, DateTime release)
    {
        Artist = artistName;
        Name = cdName;
        ReleaseDate = release;
    }

    public string Artist { get; set; }
    public string Name { get; set; }
    public DateTime ReleaseDate { get; set; }

    // Override the ToString method.
    public override string ToString()
    {
        return Name + " by " + Artist + ", Released: " + ReleaseDate.ToString("d");
    }
}

 

Now we will see how to do  add a detail view

similar to xaml file 

we will add three text boxes to bind to the three fields in our class,.

 

<StackPanel x:Name="RecordingDetails>
  <TextBlock Text="{Binding Artist}" FontWeight="Bold" FontSize="30" />
  <TextBlock Text="{Binding Name}" FontStyle="Italic" FontSize="30" />
  <TextBlock Text="{Binding ReleaseDate}" FontSize="30" />
<StackPanel/>

and for the code behind here we will show the data source to our screen

this.DataContext = new CollectionViewSource { Source = MyMusic };

 

46094_4785454486519_768526878_n
Advertisements