按钮,从 Click 事件处理程序中获取它所来自的行

我已经将 WPF Datagrid 的项目源设置为从 DAL 返回的对象列表。我还添加了一个额外的列,其中包含一个按钮,下面是 xaml。

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

这样很好。但是在 按钮 _ 点击方法中,有没有什么办法可以获得按钮所在的 datagrid 行?更具体地说,我的对象的一个属性是“ Id”,我希望能够将其传递到事件处理程序中另一个表单的构造函数中。

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

也许我需要一些额外的东西在我的考试中,或者也许我正在以一种迂回的方式去做这件事?感谢你的帮助/建议。

103761 次浏览

Basically your button will inherit the datacontext of a row data object. I am calling it as MyObject and hope 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
}

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

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

Then you can access it like so in code:

private void Button_Click(object sender, RoutedEventArgs e)
{
object ID = ((Button)sender).CommandParameter;
}
MyObject obj= (MyObject)((Button)e.Source).DataContext;

Another way which binds to command parameter DataContext and respect MVVM like Jobi Joy says button inherits datacontext form row.

Button in XAML

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

Command implementation

public void Execute(object parameter)
{
if (parameter is MyObject)
{


}
}

If your DataGrid's DataContext is a DataView object (the DefaultView property of a DataTable), then you can also do this:

private void Button_Click(object sender, RoutedEventArgs e) {
DataRowView row = (DataRowView)((Button)e.Source).DataContext;
}