2012-03-13 52 views
2

我對ActualWidthActualHeight的工作方式或計算方式感到有點困惑。ActualHeight/ActualWidth

<Ellipse Height="30" Width="30" Name="rightHand" Visibility="Collapsed"> 
    <Ellipse.Fill> 
     <ImageBrush ImageSource="Images/Hand.png" /> 
    </Ellipse.Fill> 
</Ellipse> 

當我使用上面的代碼,我得到30 ActualWidthActualHeight。但是當我以編程方式定義一個橢圓時,即使我定義了(最大)高度和(最大)寬度屬性,我也不明白它是如何可以爲0的,所以ActualWidthActualHeight都是0。

回答

7

ActualWidthActualHeight在呼叫MeasureArrange後計算。

WPF的佈局系統在將控件插入可視化樹(在DispatcherPriority.Render恕我直言,這意味着它們將排隊等待執行並且結果不會立即可用)後自動調用它們。
您可以等待它們變得可用,方法是在DispatcherPriority.Background上排隊執行操作)或手動調用方法。

例如用於調度變體:

Ellipse ellipse = new Ellipse(); 

ellipse.Width = 150; 
ellipse.Height = 300; 

this.grid.Children.Add(ellipse); 

this.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => 
{ 
    MessageBox.Show(String.Format("{0}x{1}", ellipse.ActualWidth, ellipse.ActualHeight)); 
})); 

實施例用於顯式調用:

Ellipse ellipse = new Ellipse(); 

ellipse.Width = 150; 
ellipse.Height = 300; 

ellipse.Measure(new Size(1000, 1000)); 
ellipse.Arrange(new Rect(0, 0, 1000, 1000)); 

MessageBox.Show(String.Format("{0}x{1}", ellipse.ActualWidth, ellipse.ActualHeight));