Thursday, March 25, 2010

Get DataGridRow containing element

Suppose I have a button in a DataGridCell such that on click I wish to perform certain functions (e.g. Delete row).

To detect which button triggered the Click function I can simply use this:
private void btnDeleteRow_Click(object sender, RoutedEventArgs e)
{
HyperlinkButton btn = e.OriginalSource as HyperlinkButton;
DataGridRow row = DataGridRow.GetRowContainingElement(btn);
...
}

However you will realise that getting the row is rather useless because you cannot iterate through the rows in the DataGrid, nor can you get the row index.

The only thing you can iterate through is the ItemsSource (and Columns, but in this case, useless as well). This works quite well.

private void btn_Click(object sender, System.Windows.RoutedEventArgs e)
{
MyData uploadedFiles = (MyData)((FrameworkElement)sender).DataContext;

//access collection and remove element
}

No comments:

Post a Comment