开发者

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

开发者 https://www.devze.com 2023-01-04 01:51 出处:网络
Given a refere开发者_如何学编程nce 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

Given a refere开发者_如何学编程nce 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)?


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

精彩评论

暂无评论...
验证码 换一张
取 消