在DataGrid WPF中获取选定的行项目 [英] Get selected row item in DataGrid WPF

查看:146
本文介绍了在DataGrid WPF中获取选定的行项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 DataGrid 绑定到数据库表,我需要获取DataGrid中所选行的内容,例如,我想显示在 MessageBox 所选行的内容。



DataGrid示例





所以如果我选择第二行,我的 MessageBox 必须显示如下: 646 Jim Biology



谢谢。

解决方案

可以使用SelectedItem属性获取当前选定的对象,然后您可以将其转换为正确的类型。例如,如果您的DataGrid绑定到一系列Customer对象,您可以执行以下操作:

 客户客户=(客户)myDataGrid。 SelectedItem; 

或者您可以将SelectedItem绑定到源类或ViewModel。

 < Grid DataContext =MyViewModel> 
< DataGrid ItemsSource ={Binding Path = Customers}
SelectedItem ={Binding Path = SelectedCustomer,Mode = TwoWay}/>
< / Grid>


I have a DataGrid, bound to Database table, I need to get the content of selected row in DataGrid, for example, I want to show in MessageBox content of selected row.

Example of DataGrid:

So if I select the second row, my MessageBox has to show something like: 646 Jim Biology.

Thanks.

解决方案

You can use the SelectedItem property to get the currently selected object, which you can then cast into the correct type. For instance if your DataGrid is bound to a collection of Customer objects you could do this:

Customer customer = (Customer)myDataGrid.SelectedItem;

Alternatively you can bind SelectedItem to your source class or ViewModel.

<Grid DataContext="MyViewModel">
    <DataGrid ItemsSource="{Binding Path=Customers}"
              SelectedItem="{Binding Path=SelectedCustomer, Mode=TwoWay}"/>
</Grid>    

这篇关于在DataGrid WPF中获取选定的行项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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