Resize WPF contents controls when window is resized

I created a nice utility in WPF today which contained a treeview, textbox, button and datagrid. The logic and work flow executed as expected, I was very proud of the work. I caught all my errors and exceptions and provided the user with options on how to proceed or correct the error. But the window was kind of small. When a user clicked on the lower right corner and attempted to enlarge the window size, only the window increased in size, the treeview, textbox, button and datagrid all remained the same size. This was not expected. However, as always, WPF supports it by setting the HorizontalAlignment and VerticalAlignment to Stretch. It is pretty straight forward but you need to test it out a little.


In this example, I want the button to remain locked in position (no change) and not increase in size.

<Button Content="Button" Height="23" HorizontalAlignment="Left"
       Margin="12,22,0,0" Name="button1"
       VerticalAlignment="Top" Width="75" />

It is important to set the HorizontalAlignment and VerticalAlignment so that it will not move from the location we currently have it at. The treeview I want to increase vertically but not horizontally, I configure it like this:

<TreeView HorizontalAlignment="Left" Margin="12,51,0,0"
        Name="treeView1" VerticalAlignment="Stretch"
        Width="120" />

Notice the VerticalAlignment property is set to Stretch and importantly, there is no Height property specified. Next I would like the textbox, when I expand the window to increase in size horizontally but not vertically. Therefore I have configured it like below:

<TextBox Height="119" HorizontalAlignment="Stretch"
    Margin="137,50,0,0" Name="textBox1"
    VerticalAlignment="Top" />

Notice here that the HorizontalAlignment property is set to Stretch and importantly, there is no Width property specified. If the width property had been set, then the textbox would be constrained to that width. Lastly, I want my datagrid to expand both horizontally and vertically when the window size is increased and have this configuration:

<DataGrid AutoGenerateColumns="False"
     HorizontalAlignment="Stretch" Margin="137,176,0,0"
     Name="dataGrid1" VerticalAlignment="Stretch" />

Notice that both the VerticalAlignment and HorizontalAlignment properties are set to Stretch and neither the Width nor the Height properties are present.

I wrote another blog about resizing WPF controls here

Download the source

Leave a Comment

Your email address will not be published.