Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Width and ActualWidth in WPF?

I am currently working with Panels in WPF, and I noticed that as regards the Width and Height properties, there are also two other properties called ActualWidth and ActualHeight.

ActualWidth

Gets the rendered width of this element. This is a dependency property. (Inherited from FrameworkElement.)

Width

Gets or sets the width of the element. This is a dependency property. (Inherited from FrameworkElement.)

Reference: MSDN

Can anyone point out the differences between the two and when to use either one ?

like image 582
Andreas Grech Avatar asked Mar 03 '09 19:03

Andreas Grech


2 Answers

Width/Height is the requested or layout size. If you set to Auto, then the value is double.NaN when you access the property in code behind.

ActualWidth/ActualHeight and RenderSize.Width/RenderSize.Height both return the element's rendered size, as RenderSize is of type Size. If you want/need the actual size of the item, then use any of these attributes.

like image 195
Muad'Dib Avatar answered Oct 10 '22 17:10

Muad'Dib


I find ActualWidth most useful when I want to bind the width or height of one element to another.

In this simple example I have two buttons arranged side by side and a comment underneath that is constrained to the width of the StackPanel containing the two buttons.

<StackPanel>      <StackPanel Margin="0,12,0,0" Orientation="Horizontal" Name="buttonPanel" HorizontalAlignment="Left" >          <Button Content="Yes - Arm the missile" FontWeight="Bold" HorizontalAlignment="Left"/>          <Button Content="No - Save the world" HorizontalAlignment="Left" Margin="7,0,0,0"/>     </StackPanel>      <TextBlock Text="Please choose whether you want to arm the missile and kill everybody, or save the world by deactivating the missile."                 Width="{Binding Path=ActualWidth,ElementName=buttonPanel}" Margin="0,5,0,0" HorizontalAlignment="Left" TextWrapping="Wrap"/>  </StackPanel> 
like image 26
Simon_Weaver Avatar answered Oct 10 '22 17:10

Simon_Weaver