13

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.

Andreas Zita
  • 7,232
  • 6
  • 54
  • 115
  • 1
    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 Dec 06 '10 at 10:24

3 Answers3

4

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

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.

Alex Shtoff
  • 2,520
  • 1
  • 25
  • 53
  • Yes but my grid has no explicit size, its cells should expand to its content. The problem is that the textbox-control expands to its content as well... For my scenario its ok if a combobox expands to its content but not for a textbox to do the same. It expands the grid and my window as well because Im using SizeToContent=WidthAndHeight. – Andreas Zita Dec 06 '10 at 10:31
  • So you want your textbox to have fixed width? Is it known at compile time? – Alex Shtoff Dec 06 '10 at 13:31
  • Well, no. It should fill out the entire gives space in the cell but never expand with its text-content. – Andreas Zita Dec 07 '10 at 08:03
1

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>
Dominik Weber
  • 417
  • 2
  • 11