wingerse
wingerse

Reputation: 3796

Window not Resizing to content

I have a window:

<Window x:Class="HarryPotter.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:HarryPotter"
        mc:Ignorable="d"
        Title="Harry Potter" SizeToContent="WidthAndHeight" Background="Black" WindowStartupLocation="CenterScreen"
        >
    <Viewbox Stretch="Uniform">
        <Canvas Height="640" Width="480" Background="DodgerBlue">

        </Canvas>
    </Viewbox>
</Window>

In the designer, the ViewBox's Width = 480 and Height = 640. So the Window's Width and Height are 488 and 671. This is exactly what I want.

I want the ViewBox to be of the same size as Canvas at startup and window to size to ViewBox's size. Then I want the window to be freely resizable. However, this is not what happens. When the window opens, it's height is my monitor's height.

How can I fix this?

Upvotes: 0

Views: 340

Answers (1)

You are using a ViewBox to fit the content into the available space by stretching it uniformly. However, since you did not define a height or width for the available space (SizeToContent = "WidthAndHeight") it takes up all the space so that it can stretch your canvas.

To experiment you can set Height="50" and see that the window takes all the horizontal space.

To prevent it you have a few options:

  • Set Stretch property of ViewBox to None instead of Uniform.
  • Set a predefined Width or Height for your Window.
  • Set MaxHeight or MaxWidth property of ViewBox.

Upvotes: 1

Related Questions