#1,064 – Limiting ViewBox to Scale in Just One Direction

When you use a ViewBox to scale some content, by default it scales the content either larger or smaller than the default size of the content.

You can change this behavior by setting the StretchDirection of the ViewBox to one of the following values:

  • Both (the default) – allow scaling both up and down, relative to the default size of the content
  • UpOnly – Only allow scaling larger than default size of content
  • DownOnly – Only allow scaling smaller than default size of content

If you make the ViewBox a size at which scaling of the content is not allowed, the content will be clipped or whitespace will be added.

        <Viewbox StretchDirection="UpOnly">
            <Canvas Background="Bisque" Width="200" Height="100">
                <Line X1="5" Y1="5" X2="195" Y2="95"
                        Stroke="Black"/>
                <Label Canvas.Left="80" Canvas.Top="5" Content="Howdy"/>
                <Ellipse Height="30" Width="50" Stroke="Blue" StrokeThickness="2"
                            Canvas.Left="140" Canvas.Top="5"/>
            </Canvas>
        </Viewbox>

1064-001

#278 – Allow an Image to Get Bigger, But Not Smaller (or Vice Versa)

Normally, when you set the Stretch property of an Image control to something other than None, the image can be resized up (larger) or down (smaller), obeying the rule of the specific Stretch value that you specify.

For example, if Stretch is set to Uniform, so that the image stretches to preserve the aspect ratio, you can resize a container window so that the image ends up either larger or smaller than its original size.

Smaller than original:

Larger than original:

If you want to constrain the image so that it can’t go larger or smaller than the original size, you can use the StretchDirection property.

Setting StretchDirection to DownOnly indicates that you can make the image smaller than the original, but not larger.

Setting StretchDirection to UpOnly indicates that you can make the image larger than the original, but not smaller.