您可以采取的一种方法是首先检查对象是否是
FrameworkElement
public static string GetName(object obj)
{
// First see if it is a FrameworkElement
var element = obj as FrameworkElement;
if (element != null)
return element.Name;
// If not, try reflection to get the value of a Name property.
try { return (string) obj.GetType().GetProperty("Name").GetValue(obj, null); }
catch
{
// Last of all, try reflection to get the value of a Name field.
try { return (string) obj.GetType().GetField("Name").GetValue(obj); }
catch { return null; }
}
}