Home > Net >  Why is my window changes size upon image loading?
Why is my window changes size upon image loading?

Time:10-23

I have an app that changes window size for no obvious reason. It only has a button and a 400x300px image. When the button is pressed, a black image (400x300px) is created and loaded to Image control, which causes the window to increase up to 1800x1400px. It seems like a weird bug to me. Any idea why is this happening?

MainWindow.xaml:

<Window x:Class="WindowSizeTest.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"
        mc:Ignorable="d"
        Title="MainWindow" SizeToContent="WidthAndHeight">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"/>
            <RowDefinition/>
        </Grid.RowDefinitions>

        <Button Content="Press me" Click="Button_Click"/>

        <Image x:Name="_img" Grid.Row="1" MinWidth="400" MinHeight="300"/>
    </Grid>
</Window>

MainWindow.xaml.cs

using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace WindowSizeTest
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        void Button_Click(object sender, RoutedEventArgs e)
        {
            _img.Source = BitmapSource.Create(
                400,
                300,
                96.0,
                96.0,
                PixelFormats.Gray8,
                null,
                new byte[400 * 300],
                400);
        }
    }
}

CodePudding user response:

Set the Image's Stretch property to None to make sure the Image element uses the exact size of its Source bitmap.

<Image x:Name="_img" MinWidth="400" MinHeight="300" Stretch="None"/>

CodePudding user response:

Handle your window "Loaded" event to resolve this issue:

void Window_Loaded(object sender, RoutedEventArgs e)
{
    this.SizeToContent = SizeToContent.Manual;
}
  • Related