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

时间:2022-03-29 04:53:14

Given a reference to an object defined in XAML, is it possible to determine what (if any) x:Name the object has, or can I only do this by accessing the FrameworkElement.Name property (if the object is a FrameworkElement)?

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

1 个解决方案

#1


5  

One approach you could take is to first check if the object is a FrameworkElement, and if not, try reflection to get the name:

您可以采取的一种方法是首先检查对象是否是FrameworkElement,如果没有,请尝试使用reflection来获取名称:

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; }
    }
}

#1


5  

One approach you could take is to first check if the object is a FrameworkElement, and if not, try reflection to get the name:

您可以采取的一种方法是首先检查对象是否是FrameworkElement,如果没有,请尝试使用reflection来获取名称:

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; }
    }
}