列中的按钮,在 Click 事件处理程序中获取它来自的行 [英] Button in a column, getting the row from which it came on the Click event handler

查看:27
本文介绍了列中的按钮,在 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"  
    }

也许我的 xaml 需要一些额外的东西,或者我可能会以迂回的方式解决这个问题?任何帮助/建议表示赞赏.

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

推荐答案

基本上你的按钮将继承行数据对象的数据上下文.我将其称为 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 事件处理程序中获取它来自的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆