WPF中获取匿名(Anonymous)对象的键值方法(例如DataGrid绑定List<无名元素>时)

WPF的C#工程用,不是ASP.NET的。

原文: https://www.telerik.com/forums/bind-get-key-value-from-anonymous-type-linq

 

有时候DataGrid或者ListView绑定的是个匿名对象的List,调试的时候可以看到选中对象的所有key-value。

如果我们自己知道key的名字,怎么取对应的值呢?代码如下:

using System.ComponentModel;

var senderValue = (string) TypeDescriptor.GetProperties(dataItem)["KeyName"].GetValue(dataItem); 

其中dataItem是被绑定的匿名对象,"KeyName"是key(元素名称),用这个方法可以取到对应的值。

简单的Gitee代码库:

https://gitee.com/hwajie/WPF-Anonymous-SelectedItem-Key-Value

原文地址:https://www.cnblogs.com/hwajie/p/10528822.html