WPF: Resize the window to a button size

Sergey 1 Reputation point

Hello, i want be able to resize the whole window to a first button size on that button click. And restore it's original size on next click. I hope that there are some implementations of this kind of functionality, but didn't find it yet.
Could someone share an example or describe the plan how to manage it nicely.

I thought that i should dinamicaly create all other subcontrols and remove them from the grid on button click, to be able to shrink window size to first button only.
Or maybe i can move all controls under the first button and make them invisible, so that only one that button was shown.
Thanks a lot.


Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,701 questions
A language based on Extensible Markup Language (XML) that enables developers to specify a hierarchy of objects with a set of properties and logic.
779 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Hui Liu-MSFT 47,101 Reputation points Microsoft Vendor

    You could use ToggleButton to change the window size and restore the size. For displaying Button, HorizontalAlignment and VerticalAlignment in Grid default to Center. And you could edit other controls first in the code and edit Button last. You can try to refer to the following code.
    The code of xaml:

    <Window x:Class="WindowSizeAndLocation.MainWindow"  
            mc:Ignorable="d" Name="window" WindowStyle="None"   
            Title="Window" Height="450" Width="450">  
        <Grid Name="grid">  
            <TextBlock Height="262" Width="100" HorizontalAlignment="Right" VerticalAlignment="Center" Background="Cornsilk">Growth Complete!</TextBlock>  
            <TextBlock VerticalAlignment="Top" HorizontalAlignment="Center" TextAlignment="Center" Width="100"> hello</TextBlock>  
            <ToggleButton Width="100" Height="30" Checked="ToggleButton_Checked" Unchecked="ToggleButton_Unchecked">size</ToggleButton>  

    The code of xaml.cs:

    private void ToggleButton_Checked(object sender, RoutedEventArgs e)  
          Control control = (Control)sender;  
          this.window.Width = control.Width;  
          this.window.Height = control.Height +20;  
        private void ToggleButton_Unchecked(object sender, RoutedEventArgs e)  
          this.window.Width = 450;  
          this.window.Height = 450;  

    The picture of result:


    If the response is helpful, please click "Accept Answer" and upvote it. 
    Note: Please follow the steps in our [documentation][3] to enable e-mail notifications if you want to receive the related email notification for this thread. 

    [3]: https://learn.microsoft.com/en-us/answers/articles/67444/email-notifications.html