2010-06-17 65 views
4

給定對XAML中定義的對象的引用,是否可以確定x(對象是否爲x):對象具有的名稱,還是我只能通過訪問FrameworkElement.Name屬性來執行此操作(如果對象是FrameworkElement) ?你可以採取如何從代碼中獲取x:對象的名稱?

+1

你擁有的對象引用將基於的名稱對象已經,不是嗎?你還有什麼可以獲得在xaml中定義的對象引用? – VoodooChild 2010-06-17 23:34:37

+0

在由IServiceProvider.GetService獲取的自定義MarkupExtension中。 – devios1 2010-06-17 23:46:02

+0

@VoodooChild通過導航可視/邏輯對象樹。 – Neutrino 2013-08-29 15:10:49

回答

5

一種方法是首先檢查如果對象是一個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; } 
    } 
} 
+0

這就是我最終做的......並且還檢查FrameworkContentElement,因爲它們是不同的分支,但都具有Name屬性。 – devios1 2010-06-18 19:50:32

+0

也許在這種情況下,值得使用'dynamic'? – GregRos 2014-03-19 12:31:31