Determine size of SizeToContent WPF Window before

2019-04-05 04:39发布

问题:

I have a window in my WPF application that is displayed on occasion. When it is shown it is faded in with an annimation, and when closed it is faded out. Nothing fancy, just a storyboard that modifies the opacity. Actually the window is never really closed, the opacity is just faded out to 0 where it remains until its to be displayed again.

This window is an informative window and doesn't always show the same content. It is sized to content (Width and Height) and works well in that regard. The user chooses the basic area of the screen for it to be displayed (TopLeft, TopRight, Center, BottomLeft, BottomRight).

Before the window is faded in the content is updated. Because the window is sized to content it increases or descreases in size. The width and height can change.

When positioning the window, lets say, in the bottom right corner, I simply take the WorkingArea of the screen (width and height) and then minus the width/height of the window to get the Top and Left position that I need.

The logic works, but the trouble I am having is the Window's Height and Width is not returning the size it is after the content was updated, but is returning the size it was the last time it was displayed. I am assuming this is because it hasn't yet been rendered with the new content.

This causes me grief becuase if the Window is larger than it was the last time it obviously extends off the screen.

I tried positioning the window in the OnContentRendered event, but this only fires once when the Window is created, not after the content has been updated, when the opacity is set to 0.

Does anyone have any idea how I might get an accurate width and height of this window before it is faded in?

Any help would be appreciated!!

回答1:

I found the answer to my own question. After updating the content a simple call to the window's UpdateLayout() method forces an update. Calls to the width and height then return accurate values.