by Naveen
11. February 2010 15:36
Download Sample Project
In the previous post How to use Silverlight DataGrid I discussed simple use of DataGrid in Silverlight application. Now it is time to start putting together implementation that we have from day to day to applications. One of the tasks that you may come across is that you need to add buttons to each row in the
DataGrid and then handle click events for those buttons. In the previous post I mentioned use of DataGridTemplateColumn to provide custom rendering of columns in the grid. So to add button(s) to your column, you will use the template column and then provide Button control to add them to each row. Following snippet shows how it looks like in my sample application.
<data:DataGrid x:Name="ProductsGrid">
<data:DataGrid.Columns>
<data:DataGridTemplateColumn>
<data:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel>
<Button x:Name="UpdateButton" Content="Update"
Click="UpdateButton_Click"></Button>
</StackPanel>
</DataTemplate>
</data:DataGridTemplateColumn.CellTemplate>
</data:DataGridTemplateColumn>
</data:DataGrid.Columns>
</data:DataGrid>
Handling Click Event For Button In DataGrid
As you can see from the XAML above, I just added handling of Click event on Button control. And in the codebehind provided implementation for it.
private void UpdateButton_Click(object sender, RoutedEventArgs e)
{
var ctl = e.OriginalSource as Button;
if (null != ctl)
{
var product = ctl.DataContext as Product;
if (null != product)
{
var msg = string.Format("{0}, {1}, {2}",
product.ProductID, product.Name, product.ListPrice);
MessageBox.Show(msg);
}
}
}
Accessing Data Associated With Row In DataGrid
When user clicks on the button in datagrid row, the method gets called. Next question you have is how do you access the data associated with the row on which button was clicked. It is very straight forward. When DataGrid rendering takes place, each control in the row is bound to DataContext. This DataContext is the data that was used to render that row. So you simple look at DataContext property of Button control that raised the event and got the actual data object used for that row.
I think this should give you a good starting point on how to add buttons or some other controls in DataGrid rows and how to access data for them as well. In next post I will discuss more of customization of Silverlight DataGrid.