Wow, what a long title. :) Here is a better description of what the scenario is. You have a Silverlight application that uses a DataGrid. The DataGrid is bound to a list of Person objects for example. You add a Button to the DataGrid by creating a DataGridTemplateColumn.CellTemplate and putting the Button in it. You want the button to select the row that contains that button, and you want access to the data in that row.
There are really two questions, but the very closely related:
- How do I select the row that contains the button that is clicked?
- How do I get data for the selected row?
The scenario is not that difficult or uncommon, but the solution was not obvious to me. This may be because I am new to Silverlight, and have most my experience in ASP.NET. The good news is that it is really easy.
Here is what I figured out.
First let’s show the DataGrid in the .xaml file to see how the Button was added in the first place. This example has an Edit button in the first column, and two other columns just to show that there would normally be other columns.
The answer to both questions is really quite simple once we are armed with the knowledge that the Button has a property named DataContext. The DataContext property contains the entity related to row that is clicked.
Here is all we need in our Edit button Click event handler. In this example, I the sender is the Button that was clicked so we can cast it to a Button. The button has a DataContext so we can get the entity related to that row. If we want to access the data in the entity we will need to cast it to the appropriate type since it is of type object when returned from btn.DataContext. When we set the MyDataGrid.SelectedItem = entity this changes the MyDataGrid.SelectedIndex property and the UI is updated with the new selected row selected (highlighted). In this case, I use a MessageBox to show that we are getting the selected row index and the correct data from the other columns.