C# DataGrid选定值couldn';无法访问,它正在获取匿名类型对象
我有一个数据网格,它将数据绑定到人、地点和数量。在SelectionChanged事件中,我试图访问数据,但它说该类型是匿名的 如何转换此对象并获取值C# DataGrid选定值couldn';无法访问,它正在获取匿名类型对象,c#,wpf,datagrid,C#,Wpf,Datagrid,我有一个数据网格,它将数据绑定到人、地点和数量。在SelectionChanged事件中,我试图访问数据,但它说该类型是匿名的 如何转换此对象并获取值 任何帮助或建议都将不胜感激 您可以尝试使用反射来获取属性值 private void workgrid_SelectionChanged(object sender, SelectionChangedEventArgs e) { object selectedItem = ((DataGrid)sender).SelectedItem;
任何帮助或建议都将不胜感激 您可以尝试使用反射来获取属性值
private void workgrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
object selectedItem = ((DataGrid)sender).SelectedItem;
Type type = selectedItem.GetType();
string name = (string)type.GetProperty("PersonName").GetValue(selectedItem, null);
int amount = (int)type.GetProperty("Amount").GetValue(selectedItem, null);
string place = (string)type.GetProperty("Place").GetValue(selectedItem, null);
}
不过,推荐的方法是为将用于绑定DataGrid的集合创建自己的类型。这将允许您避免直接绑定到匿名类型
public class AccountInfo
{
public string PersonName { get; set; }
public int Amount { get; set; }
public string Place { get; set; }
}
DataGrid的ItemSource类型是什么?我从实体模型tablevar objResult=从Objenties.PersonAccounts中的c中获取源,选择new{c.PersonName,c.Amount,c.Place};workgrid.ItemsSource=objResult;这是我更新源代码的方式,它很有用。感谢您宝贵的解决方案