WPF DataGrid – 列中的button,从Click事件处理程序中获取它所在的行
我已经将WPF Datagrid的itemsource设置为从我的DAL返回的对象列表。 我还添加了一个包含button的额外列,下面是xaml。
<toolkit:DataGridTemplateColumn MinWidth="100" Header="View"> <toolkit:DataGridTemplateColumn.CellTemplate> <DataTemplate> <Button Click="Button_Click">View Details</Button> </DataTemplate> </toolkit:DataGridTemplateColumn.CellTemplate> </toolkit:DataGridTemplateColumn> 这呈现罚款。 然而,在Button_Click方法,有没有什么办法可以得到button所在的数据网格上的行? 更具体地说,我的对象的属性之一是“ID”,我希望能够传递到事件处理程序中的另一种forms的构造函数。
 private void Button_Click(object sender, RoutedEventArgs e) { //I need to know which row this button is on so I can retrieve the "id" } 
也许我需要在xaml中额外添加一些东西,或者我可以用迂回的方式来解决这个问题? 任何帮助/build议表示赞赏。
基本上你的button将inheritance行数据对象的datacontext。 我称之为MyObject,并希望MyObject.ID是你想要的。
 private void Button_Click(object sender, RoutedEventArgs e) { MyObject obj = ((FrameworkElement)sender).DataContext as MyObject; //Do whatever you wanted to do with MyObject.ID } 
另一种方法是将ID绑定到button的CommandParameter属性上:
 <Button Click="Button_Click" CommandParameter="{Binding Path=ID}">View Details</Button> 
那么你可以像这样在代码中访问它:
 private void Button_Click(object sender, RoutedEventArgs e) { object ID = ((Button)sender).CommandParameter; } 
另一种绑定到命令参数DataContext和尊重MVVM的方式,比如Jobi Joy说buttoninheritancedatacontext表格行。
XAML中的button
 <RadButton Content="..." Command="{Binding RowActionCommand}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=Self}, Path=DataContext}"/> 
命令实现
 public void Execute(object parameter) { if (parameter is MyObject) { } } 
 MyObject obj= (MyObject)((Button)e.Source).DataContext; 
如果你的DataGrid的DataContext是一个DataView对象(DataTable的DefaultView属性),那么你也可以这样做:
 private void Button_Click(object sender, RoutedEventArgs e) { DataRowView row = (DataRowView)((Button)e.Source).DataContext; }