开发者

How do I get the dimensions of a WPF element at run-time without specifying them at compile-time

The problem?

<UI:PanelBrowser Margin="12,27,12,32"><开发者_Python百科;/UI:PanelBrowser>

WPF is ridiculous in that not manually specifying properties (Such as Width and Height) in this case causes them to have the values Doulbe.NaN. The problem is that I need to know this number. I'm not going to manually set a width and height in the XAML because that stops it from resizing.

Given the above piece of XAML (this object is a simple subclass of the Border control), how can I get the values of the Width and Height properties at run-time?

Edit :

Wow, I feel ridiculous. I read about ActualWidth and ActualHeight, but they were consistently returning 0 and 0 for me. The reason is that I was testing for these properties in the constructor of the Framework Element, before they were actually initialized. Hope this helps someone who runs into the same issue and testing fallacies. :)


Try using the FrameworkElement.ActualWidth and ActualHeight properties, instead.


The WPF FrameworkElement class provides two DependencyProperties for that purpose: FrameworkElement.ActualWidth and FrameworkElement.ActualHeight will get the rendered width and height at run-time.


You can use elements' ActualWidth and ActualHeight properties to get the values of the width and height when they were drawn.


Use VisualTreeHelper.GetDescendantBounds(Visual Reference), and it return Rect.
Then Check the height of the Rect.
Ex)

Rect bounds = VisualTreeHelper.GetDescendantBounds(element);
double height = bounds.height;

OR
Use UIElement.Measure(Size size), it will assign the Size into DesiredSize.
Ex)

myElement.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));  
double height = myElement.DesiredSize.Height;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜