代码之家  ›  专栏  ›  技术社区  ›  devios1

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

  •  5
  • devios1  · 技术社区  · 14 年前

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

    1 回复  |  直到 14 年前
        1
  •  7
  •   Joseph Sturtevant    14 年前

    您可以采取的一种方法是首先检查对象是否是 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; }
        }
    }
    
    推荐文章