TheHvidsten
TheHvidsten

Reputation: 4428

Prevent automatic resize of window when content changes

I have made a picture viewer which is a Window with SizeToContent="Width". This looks just the way I want it when I open it with the first picture in a series.

When I go the next picture in the series, which happens to be wider than the previous one, the Window is resized to fit this new picture. The left edge of the Window stays in the same place, but the right edge of the Window is now outside the edge of the screen.

How can I prevent an automatic resize like this?

I do not want to use ResizeMode="NoResize" because I want the user to be able to manually change the size of the Window should he or she want to.

XAML

<Window SizeToContent="Width" WindowStartupLocation="CenterOwner">
    <Grid>
        <DockPanel>
            <Button DockPanel.Dock="Left" 
                    Content="Previous" />
            <Button DockPanel.Dock="Right" 
                    Content="Next" />
            <Image Source="{Binding CurrentImage}" 
                   Stretch="Uniform" 
                   StretchDirection="DownOnly" 
                   RenderOptions.BitmapScalingMode="Fant" />
        </DockPanel>
    </Grid>
</Window>

Upvotes: 1

Views: 1168

Answers (1)

Clemens
Clemens

Reputation: 128061

Reset the SizeToContent property in a Loaded event handler:

public MainWindow()
{
    InitializeComponent();

    Loaded += (o, e) => SizeToContent = SizeToContent.Manual;
}

Or if you don't like code behind:

<Window.Triggers>
    <EventTrigger RoutedEvent="Loaded">
        <BeginStoryboard>
            <Storyboard>
                <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="SizeToContent">
                    <DiscreteObjectKeyFrame KeyTime="0"
                                            Value="{x:Static SizeToContent.Manual}"/>
                </ObjectAnimationUsingKeyFrames>
            </Storyboard>
        </BeginStoryboard>
    </EventTrigger>
</Window.Triggers>

Upvotes: 4

Related Questions