Wpf – Textbox will not stretch to fill viewbox

formslayouttextboxviewboxwpf

I want the font size of my labels and textboxes in my LOB form to grow and shrink with window resize or resolution change. To achieve this I've placed my labels and textboxes within viewboxes.

The labels and custom radio buttons behave as I expect, but the textboxes will not stretch horizontally to fill the viewbox (sorry can't post image because of rep). The textboxes will horizontally fill the viewbox if you type into them.

Here is an example of the code which I am working with:

  <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="0.186*"/>
            <ColumnDefinition Width="0.814*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="0.127*"/>
            <RowDefinition Height="0.873*"/>
        </Grid.RowDefinitions>
        <Viewbox Margin="0,0,0.917,0">
            <Label Content="First name:"/>
        </Viewbox>
        <Viewbox Grid.Column="1">
            <TextBox TextWrapping="Wrap"/>
        </Viewbox>
    </Grid>

I've tried placing grid, stackpanel and dockpanel (with LastChildFill="True") within the viewbox and then placing the textboxes within these layout controls but this didn't work either. Is there anyway to get the textboxes to horizontally fill the parent viewbox?

This problem is similar to this: WPF TextBox won't fill in StackPanel but this problem is with stackpanels, not viewboxes.

Best Answer

I think what you want is not easily possible. ViewBox tells its children that they have inifite space, in the measure pass of the layouting. After that, the display is fit into the viewbox. Now a textbox, told to have infinite space, obviously can't stretch. I have 2 solutions, which i think are not what you want, but might be helpful anyway.

The first:

<Viewbox Grid.Column="1" Grid.Row="0" Stretch="Uniform" >
    <Grid Width="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Viewbox}}, Path=ActualWidth}">
      <TextBox TextWrapping="Wrap" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
    </Grid>
</Viewbox>

this will stretch you textbox infact, but disable the behaviour expected from the viewbox. Why? We told the ViewBox to keep the aspect ratio, and set the textbox to fill the whole width of the viewbox, which keeps the size of the textbox.

The second:

would be to add a height to the grid, taken from the label, modified with the scaletransform of its viewbox.

This one i haven't tried, but it would involve a value converter.

In conclusion: There is no easy way to achieve what you want, because of the way the viewbox layouts its children. If you just want to stretch horizontally, my first solution works fine, if you want to scale. My guess is you have to do it yourself.

Related Topic