如何从代码中获取x:对象的名称?

dev*_*os1 6 wpf xaml code-behind xname

给定对XAML中定义的对象的引用,是否可以确定对象具有什么(如果有)x:Name,或者我是否可以通过访问FrameworkElement.Name属性(如果对象是FrameworkElement)来执行此操作?

Jos*_*ant 5

您可以采取的一种方法是首先检查对象是否为a 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; }
    }
}
Run Code Online (Sandbox Code Playgroud)