Question

I'm a little confused with how ActualWidth or ActualHeight works or how it gets calculated.

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

When I use the above code, I get 30 for ActualWidth and ActualHeight. but when I programmatically define an Ellipse, the ActualWidth and ActualHeight are 0, even if I define the (max)height and (max)width attribute - I don't understand how it can be 0?

Was it helpful?

Solution

ActualWidth and ActualHeight are computed after calling Measure and Arrange.

The layout system of the WPF calls them automatically after inserting the control into the visual tree (at DispatcherPriority.Render IMHO which means they will be queued for execution and the results won't be available instantly).
You can wait for them to become available by queuing an action at DispatcherPriority.Background) or by calling the methods manually.

Example for the dispatcher variant:

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));
}));

Example for the explicit call:

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));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top