0
votes

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.

1
"I have added code to sizechanged event which resizes controls as a ratio of form size". This does not make any sense. WPF provides a powerful layout system. Start reading here: docs.microsoft.com/en-us/dotnet/framework/wpf/advanced/layout. Then use a Grid as container element.Clemens
I now understand that the Grid was the best way to go, but I was hoping I would be able to deal with this issue without going back and reworking the form by addressing this in code. Is this possible?Ritchie
I'd strongly recommend to stop any effort in that direction, and just use proper layout. It is a waste of time.Clemens
If I can workout or have suggested a fix that I can implement in an hour or two it will not be a waste of time, reworking the whole layout if such a fix is available is. If the answer is a straight no, there is no way to change the size of a control in code once the window is maximized then fair enough I will have to rework the form. This is a one off and for my next project I am sure to take onboard your advice and implement the 'proper layout' as describedRitchie

1 Answers

3
votes

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%.