How can I get the x:Name of an object from code?
Asked Answered
S

1

8

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)?

Sorrel answered 17/6, 2010 at 23:3 Comment(3)
The object reference you have would be based on the name of the object already, wouldn't it? How else would you have an object reference which is defined in xaml?Brawner
In a custom MarkupExtension, obtained by IServiceProvider.GetService.Sorrel
@Brawner by navigating the visual/logical object tree.Coincidence
I
7

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

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; }
    }
}
Impiety answered 18/6, 2010 at 1:22 Comment(2)
This is what I ended up doing... and also checking for FrameworkContentElement, since they're different branches but both have a Name property.Sorrel
Maybe in this case it's worth using dynamic?Adamsen

© 2022 - 2024 — McMap. All rights reserved.