获取它来自Click事件处理程序的行

获取它来自Click事件处理程序的行

本文介绍了在列中单击按钮,获取它来自Click事件处理程序的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've set the itemsource of my WPF Datagrid to a List of Objects returned from my DAL. I've also added an extra column which contains a button, the 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>

这很好。但是,在 Button_Click 方法上,有什么方法可以让我在按钮所在的数据网格上获取行?更具体地说,我对象的属性之一是 Id,我希望能够将其传递到事件处理程序中另一种形式的构造函数中。

This renders fine. However on the Button_Click method, is there any way I can get the row on the datagrid where the button resides? More specifically, one of the properties of my objects is "Id", and I'd like to be able to pass this into 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"
    }

也许我在xml中需要一些额外的东西,或者也许我打算这是回旋处吗?

Perhaps I need something extra in my xaml, or maybe I'm going about this in a roundabout way? Any help/advice appreciated.

推荐答案

基本上,您的按钮将继承行数据对象的datacontext。我将其称为MyObject,并希望您想要的是MyObject.ID。

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
}

这篇关于在列中单击按钮,获取它来自Click事件处理程序的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 14:10