給定對XAML中定義的對象的引用,是否可以確定x(對象是否爲x):對象具有的名稱,還是我只能通過訪問FrameworkElement.Name屬性來執行此操作(如果對象是FrameworkElement) ?你可以採取如何從代碼中獲取x:對象的名稱?
4
A
回答
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; }
}
}
你擁有的對象引用將基於的名稱對象已經,不是嗎?你還有什麼可以獲得在xaml中定義的對象引用? – VoodooChild 2010-06-17 23:34:37
在由IServiceProvider.GetService獲取的自定義MarkupExtension中。 – devios1 2010-06-17 23:46:02
@VoodooChild通過導航可視/邏輯對象樹。 – Neutrino 2013-08-29 15:10:49