10

In case we use WPF (Silverlight) Viewbox with Stretch="UniformToFill" or Stretch="Uniform" when it preserves content's native aspect ratio, how could we get knowing the current coefficient of scaling which were applied to the content?

Note: we not always know the exact initial dimensions of the content (for example it's a Grid with lots of stuff in it).

rem
  • 16,745
  • 37
  • 112
  • 180

1 Answers1

18

See this question: Get the size (after it has been "streched") of an item in a ViewBox

Basically, if you have a Viewbox called viewbox, you can get the ScaleTransform like this

ContainerVisual child = VisualTreeHelper.GetChild(viewbox, 0) as ContainerVisual;
ScaleTransform scale = child.Transform as ScaleTransform;

You could also make an extension method for Viewbox which you can call like this

viewbox.GetScaleFactor();

ViewBoxExtensions

public static class ViewBoxExtensions
{
    public static double GetScaleFactor(this Viewbox viewbox)
    {
        if (viewbox.Child == null ||
            (viewbox.Child is FrameworkElement) == false)
        {
            return double.NaN;
        }
        FrameworkElement child = viewbox.Child as FrameworkElement;
        return viewbox.ActualWidth / child.ActualWidth;
    }
}
Community
  • 1
  • 1
Fredrik Hedblad
  • 83,499
  • 23
  • 264
  • 266
  • 1
    Just a quick note to other Silverlight users - even though the question asks about the "WPF (Silverlight)" ViewBox, the solution doesn't work as is for Silverlight as it has no ContainerVisual class. – dlanod Jul 04 '11 at 23:06