[英]Get SelectedItem value from DataGrid
I have a DataGrid in my WPF application as below. 我的WPF应用程序中有一个DataGrid ,如下所示。
<DataGrid Name="stDataGrid" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Edit" CanUserResize="False" Width="SizeToHeader">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button" Click="btnEdit_Click">
<StackPanel>
<Image Source="images/edit.png"/>
</StackPanel>
</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Binding="{Binding Path=Name}" Header="Name" IsReadOnly="True"></DataGridTextColumn>
<DataGridTextColumn Binding="{Binding Path=Age}" Header="Age" IsReadOnly="True"></DataGridTextColumn>
<DataGridTextColumn Binding="{Binding Path=Sex}" Header="Sex" IsReadOnly="True"></DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
Binding data into DataGrid like this. 这样将数据绑定到DataGrid中。
using (var context = new CLASS_DBEntities())
{
var query = from s in context.STUDENT
orderby s.STUDENT_NAME
select new {s.STUDENT_ID, Name = s.STUDENT_NAME, Age = s.STUDENT_AGE,
Sex = s.STUDENT_SEX};
stDataGrid.ItemsSource = query.ToList();
}
When user click Button in DataGrid, I need to get STUDENT_ID
value. 当用户单击DataGrid中的Button时,我需要获取
STUDENT_ID
值。 How can i do this ? 我怎样才能做到这一点 ?
Set an attached property of the same type as student_id
on your button and bind it relativly to the datacontext.student_id
of the DataGridRow control which should be the parent to all yours cells in a row. 在按钮上设置一个与
student_id
类型相同的附加属性,并将其相对地绑定到DataGridRow控件的datacontext.student_id
,该控件应该是您所有连续单元格的父级。
Once you enter btnEdit_Click
method just read out the value from your attached property. 输入
btnEdit_Click
方法后,只需从附加属性中读取值即可。
Finally found answer by myself. 终于自己找到答案了。
in btnEdit_Click
method, 在
btnEdit_Click
方法中,
dynamic customerRow = stDataGrid.SelectedItem;
MessageBox.Show(customerRow.STUDENT_ID+"");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.