Question

I have some custom calculations that changes the dimensions of a control based on the dimensions of a ScrollViewer's viewport. Currently, I make these calculations when getting a ScrollViewer.SizeChanged event. However, it seems like the SizeChanged event executes before the ScrollViewer updates the ViewPort dimensions. My event handler for SizeChanged shows a ScrollViewer sender with the Width and Height updated to the new dimensions but the ViewportWidth and ViewportHeight properties are of the old dimensions.

Is there a way to execute code once those values change?

Was it helpful?

Solution 3

I would suggest you to keep listening to SizeChanged event. Subscribe to that event and ask ScrollViewer about its Viewport inside handler BUT dispatch that request with Background or Loaded prority. Current size of ScrollViewer should be more or less equal to Viewport.

OTHER TIPS

According to MSDN you check the ScrollViewer's ScrollChanged event. When it fires, it means the viewportwidth or viewportheight has changed.

OnScrollChanged Called when a change in scrolling state is detected, such as a change in scroll position, extent, or viewport size.

Had the same problem, where I needed to know the new size of a Viewport when the ScrollViewer is rezised.

SizeChanged is fired before the Viewport is adjusted, therefore to get the new viewport size you can simply take the diff between old and new sizes, passed via SizeChangedEventArgs, and apply it to the current Viewport size like so:

    private void ScrollViewer_SizeChanged(object sender, SizeChangedEventArgs e)
    {
        var sv = sender as ScrollViewer;

        var newViewportHeight = sv.ViewportHeight - e.PreviousSize.Height + e.NewSize.Height;
        var newViewportWidth = sv.ViewportWidth - e.PreviousSize.Width + e.NewSize.Width;
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top