Let's run through a simple DataGrid example.
1. create a new silverlight applicaiton in VS 2010. Name the project SimpledataGrid, and have VS create a web application porject for you.
2. Add the DataGrid to your application. To do this, simply add the DataGrid to the root Grid in your XAML, and set the Margin property to 10 to get some spacing around the grid. In addition, give the DataGrid the name grid. Note that, by default, the Grid's AutoGenerateColumns property is set to true. If you were going to define the columns manually, you would want to set this property to false. Howeve, since you want the grid to create the columns automatically, you can omit the property. The DataGrid definition follows:
<Grid x:Name="LayoutRoot" Background="White">
<sdk:DataGrid Name="grid" Margin="10">
</sdk:DataGrid>
</Grid>
3. Next, build the class that will be bound to the DataGrid. Call the class GridData for simplicity, and give it three properties: Name(string), Age(int), and Mail(Boolean). Also for simplicity, create a static method that will return an ObservableCollection(requies adding a using clause for System.Collection.ObjectModel) containing some sample data that will be bound to the grid. In addition, define the class directly in MainPage.xaml.cs file. This is not really a good idea in the ral world, but for the sake of an example, it will work just fine. Ideally, you will want to define your classes in seperate or even in completely sepatate projects and assemblies. The code for the GridData class follows:
public class GridData
{
public string Name { get; set; }
public int Age { get; set; }
public bool Male { get; set; }
public static ObservableCollection<GridData> GetData()
{
ObservableCollection<GridData> data = new ObservableCollection<GridData>();
data.Add(new GridData()
{
Name="Jone Doe", Age =30, Male=true
});
data.Add(new GridData() { Name = "Jane Doe", Age = 32, Male = false });
data.Add(new GridData() { Name = "Jason Smith", Age = 54, Male = true });
data.Add(new GridData() { Name = "Kayli Jayne", Age = 25, Male = false });
return data;
}
}
4. Now that you hvae the XAMl and the class defined, you can wire them up. To do this, first create an event handler for the Loaded event of the page, as follows:
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
this.grid.ItemsSource = GridData.GetData();
}
5. Build and run the application. If all is well, you should see the DataGrid displayed.