2010-09-10 36 views
2

喂,我如何獲得堆疊面板的實際當前高度?

我想在WPF自定義的StackPanel,它應自動調整自己的孩子的,這取決於面板的高度一定規模。但面板高度是動態的,因爲它延伸到他的父母。當我想要得到的高度(我嘗試了所有的可能性,看代碼),它始終是0或者沒有定義,但在構建解決方案,絕對不爲0 下面的代碼:

XAML:

<my:AutoSizeButtonStackPanel HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>

代碼隱藏:

public class AutoSizeButtonStackPanel : StackPanel 
{ 
    public void AddChild(Button newButton) 
    { 
     double getPanelHeight; 
     getPanelHeight = this.ActualHeight; //is 0 
     getPanelHeight = this.ViewportHeight; //is 0 
     getPanelHeight = this.Height; //is n. def. 
     getPanelHeight = this.DesiredSize.Height; //is 0 
     getPanelHeight = this.RenderSize.Height; //is 0 

     newButton.Height = getPanelHeight/2; 

     this.Children.Add(newButton); 
    } 
} 

回答

3

這可能與辦時你居然查詢this.ActualHeight。在時間AddChild()被稱爲高度真的可能仍然是0因爲the measure pass and the arrange pass可能還沒有經過。一切影響你的孩子的措施和佈局應該在MeasureOverrideArrangeOverride

你應該看看如何編寫自定義面板。那裏有很多這方面的資源。我個人認爲this是一個很好且簡單的教程。

+0

謝謝,很好的教程(即使對我來說足夠簡單:-P) 只需在ArrangeOverride中放置調整大小邏輯,現在它可以工作。 – SpeziFish 2010-09-10 11:43:14

0

的ActualHeight是正確的屬性,但在這裏你讀它的點,高度尚未計算。

請點擊此鏈接,找出建立一個自定義佈局面板的推薦方法:http://www.wpftutorial.net/CustomLayoutPanel.html

+0

我已經知道這個教程,但它不夠深刻,並沒有清除我的問題。 – SpeziFish 2010-09-10 11:45:30