在 DataGrid WPF 中获取选定的行项目 [英] Get selected row item in DataGrid WPF
问题描述
我有一个DataGrid
,绑定到Database表,我需要在DataGrid
中获取选中行的内容,比如我想在中显示MessageBox
所选行的内容.
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.
DataGrid
示例:
因此,如果我选择第二行,我的 MessageBox
必须显示如下内容:646 Jim Biology.
So, if I select the second row, my MessageBox
has to show something like: 646 Jim Biology.
推荐答案
您可以使用 SelectedItem
属性来获取当前选定的对象,然后您可以将其转换为正确的类型.例如,如果您的 DataGrid
绑定到一组 Customer
对象,您可以这样做:
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;
或者,您可以将 SelectedItem
绑定到您的源类或 ViewModel
.
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屋!