Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: Expand TextBox by available width but NOT by its content?

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.

like image 479
Andreas Zita Avatar asked Dec 06 '10 10:12

Andreas Zita


2 Answers

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>
like image 83
Dmitry Makhalov Avatar answered Nov 11 '22 14:11

Dmitry Makhalov


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.

like image 21
Alex Shtof Avatar answered Nov 11 '22 12:11

Alex Shtof