Get height and width of UIElement?

TorbenJ picture TorbenJ · Oct 20, 2012 · Viewed 6.9k times · Source

I currently create a class which inherits from a Popup.

Finally it will be used to show the user a popup with validation rules when editing e.g a TextBox.

Therefore I created ValidationPopup with this constructor so far:

public ValidationPopup(UIElement parent, double width) : base()
{
   this.parent = parent;
   this.width = width;
   InitControl();
}

I would like to set the size of the popup equal to the size of the PlacementTarget parent. In order to allow many different controls to be able to have one of these ValidationPopups I pass an UIElement as parent instead of TextBox etc. My problem is that I have to pass the width and height values of this control when building an instance of ValidationPopup in order to size it properly.

Is it possible to get these values from UIElement? I saw RenderSize on MSDN but it only gives me 0.0 values for width and height.

This is where I setup one instance of ValidationPopup:

txtOperator = new TextBox();
layoutGrid.Children.Add(txtOperator);
operatorVPU = new ValidationPopup(txtOperator, txtOperator.Width);

I tried to use RenderSize but this doesn't work until the whole UI is completly finished.

Is there a way to get Height and Width values of an UIElement at this point? Are there maybe other even better ways to achieve the same result?

Answer

Chen Kinnrot picture Chen Kinnrot · Oct 20, 2012

Sounds like you need to use the ActualWidth/Height properties. If they are still 0 or NaN, you can try executing this code on a later part of the view creation.