【问题标题】:How can I get the x:Name of an object from code?如何从代码中获取对象的 x:Name?
【发布时间】:2011-03-05 05:17:48
【问题描述】:

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

【问题讨论】:

  • 您拥有的对象引用已经基于对象的名称,不是吗?否则您将如何拥有在 xaml 中定义的对象引用?
  • 在自定义的 MarkupExtension 中,由 IServiceProvider.GetService 获取。
  • @VoodooChild 通过导航视觉/逻辑对象树。

标签: wpf xaml code-behind xname


【解决方案1】:

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

【讨论】:

  • 这就是我最终要做的......并且还要检查 FrameworkContentElement,因为它们是不同的分支,但都有一个 Name 属性。
  • 也许在这种情况下值得使用dynamic
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-09
  • 2019-08-29
  • 2011-01-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多