2013-02-15 61 views
0

我有一個應該返回UIElementCollection的函數。該函數需要具有children屬性的UIElement(即stackpanel,grid等),但不知道它是哪個UIElement,所以我將它存儲到一個通用對象中。對象的子女

public UIElementCollection retCol (object givenObject){ 
... 
} 

我想返回givenObject的孩子,但我不能找到一種方法,除了鑄造givenObject作爲一個StackPanel或網格這樣做。

有沒有一種方法可以得到givenObject的兒童財產?

回答

0

StackPanelGrid無論從Panel繼承,這樣你就可以改變你的方法:

public UIElementCollection retCol (Panel givenObject){ 
    return givenObject.Children; 
} 

或者,如果你想提供給所有UIElement類型,你可以使它更通用和檢查類型功能:

public UIElementCollection retCol (UIElement givenObject){ 
    if(givenObject is Panel) 
     return ((Panel)givenObject).Children; 
    else if(givenObject is SomeOtherContainer) 
     return ((SomeOtherContainer)givenObject).Children; 

    else 
     return null; 
}