Search code examples
c#wpfresizemaximize-window

Controls do not resize when maximised but do when resized by dragging - wpf


Question is as per WPF: when I maximize my window, controls do not resize which is unanswered.

I have a WPF form with some controls which are tied to at least two edges of the form. I have added code to sizechanged event which resizes controls as a ratio of form size. The code works well and when the form is resized by dragging the controls resize correctly.

When form is maximized the controls do not resize, save for vertically on the controls attached to both top and bottom of the window.

I have added similar code to the statechanged event however this does nothing. I have tried a straight TextBox1.Width = 300; but this does not change the size once maximised.

Ideally what I want is for say TextBox1.Width = Window.width/3; TextBox1.Margin = My_Margin; Where My_Margin sets the left margin to 1/3 Window.Width. So that the textbox occupies the central third of the window.

EDIT: I understand that the GRID method was the way to go from the start of the project. Is there a workaround I can do at this stage in c# instead of having to rework the form?

EDIT: Have accepted the best answer, though it does not answer the actual question, as it looks like the only option I have. I know that there is a way to resize controls once the form is maximized, I don't have time to find it and no good suggestions came forth.


Solution

  • Use a grid, define columns (with their width) and rows, and place the textbox using Grid.Row and Grid.Column properties. Also in a WPF Grid, * for Width and Height means proportional sizing. So for instance if you have 2 columns defined like these ones

    <Grid.ColumnDefinitions>
         <ColumnDefinition Width="1*"></ColumnDefinition>
         <ColumnDefinition Width="9*"></ColumnDefinition>
    </Grid.ColumnDefinitions>
    

    you are saying to wpf that the first column will occupy the 10% of the total available width, while the second 90%.