WPF DataGrid - the button in the column that receives the row from which it appeared in the Click event handler

I set the items source of my WPF Datagrid to a list of objects returned from my DAL. I also added an extra column that contains the button, xaml is below.

<toolkit:DataGridTemplateColumn MinWidth="100" Header="View"> <toolkit:DataGridTemplateColumn.CellTemplate> <DataTemplate> <Button Click="Button_Click">View Details</Button> </DataTemplate> </toolkit:DataGridTemplateColumn.CellTemplate> </toolkit:DataGridTemplateColumn> 

It is perfectly. However, in the Button_Click method, is there a way to get the row on the datagrid where the button is? In particular, one of the properties of my objects is "Id", and I would like to pass this to the constructor of another form in the event handler.

 private void Button_Click(object sender, RoutedEventArgs e) { //I need to know which row this button is on so I can retrieve the "id" } 

Perhaps I need something extra in my xaml, or maybe I will get around this? Any help / advice appreciated.

+75
c # wpf xaml datagrid datagridview
Jul 23 '09 at 0:26
source share
5 answers

Basically your button inherits the datacontext of a row data object. I call it MyObject and hope that MyObject.ID is what you wanted.

 private void Button_Click(object sender, RoutedEventArgs e) { MyObject obj = ((FrameworkElement)sender).DataContext as MyObject; //Do whatever you wanted to do with MyObject.ID } 
+100
Jul 23 '09 at 2:15
source share

Another way I would like to do this is to bind the identifier to the CommandParameter property of the button:

 <Button Click="Button_Click" CommandParameter="{Binding Path=ID}">View Details</Button> 

Then you can access it, as in the code:

 private void Button_Click(object sender, RoutedEventArgs e) { object ID = ((Button)sender).CommandParameter; } 
+35
Feb 07 '11 at 20:37
source share

Another way that communicates with the parameter of the DataContext command and respects MVVM, for example, Joby Joy says that the button inherits the form string of the datacontext.

Button in XAML

 <RadButton Content="..." Command="{Binding RowActionCommand}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=Self}, Path=DataContext}"/> 

Command execution

 public void Execute(object parameter) { if (parameter is MyObject) { } } 
+8
Nov 15 '13 at 10:17
source share
 MyObject obj= (MyObject)((Button)e.Source).DataContext; 
+3
Apr 25 2018-12-12T00:
source share

If your DataGrid DataContext is a DataView object (DefaultView property for a DataTable), you can also do this:

 private void Button_Click(object sender, RoutedEventArgs e) { DataRowView row = (DataRowView)((Button)e.Source).DataContext; } 
-one
Oct 24 '14 at 4:32
source share



All Articles