12
votes

I need a good solution for making a TextBox in a grid to expand to its available space but not expand according to how long the text in it happen to be.

Most solutions I have found is to make a dummy-border and bind to its ActualWidth but its a to hacky solution for me. The border-solution needs a small margin set on the border as well which is not nice at all. Setting it to low will cause the UI to behave very strange. Don't like this solution. There has to be a better one? All I want is for the textbox to not expand with its content. It shouldnt be that hard. Please let me know how to do this.

EDIT:

One odd thing I noticed is that the following code makes the border a lot larger then it has to be:

<Grid>
  <Border Name="dummy1" Background="Red" />
  <TextBox Text="23242342343555554234234444444444423423423432344444444" Width="{Binding ActualWidth, ElementName=dummy1}" />
</Grid>

Replacing the border and textbox order makes the border fit to the textbox nicely, but what I need is the opposite. As said before, setting a Margin (on the border) to at least 0.5 makes it work but with a bit twitchy UI as a result.

3
If you just have a TextBox in a Grid, it should stretch by default to its parent. Are you sure you don't have anything that modifies your HorizontalAlignment property? Are you talking about the Grid control or some other control (like DataGrid or GridView) which you call it Grid?Andrei Pana

3 Answers

4
votes

I used DockPanel to expand to its available space. You must set Margin too:

<DockPanel>
   <TextBox Width="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=DockPanel}, Path=ActualWidth}" Margin="1" />
</DockPanel>
2
votes

HorizontalAlignment=Stretch does not help? AFAIK grid panels stretch their child elements to the available space in their cell when their horizontal alignment is set to Stretch.

1
votes

Did you find out how to solve this problem?

Answer to your Border-problem: You should put your TextBox-Object inside the border.

    <Border Background="Red" Padding="3">
        <Button Content="Button" />
    </Border>