问题描述
我有一个 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中获取选定的行项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!