views:

9731

answers:

4

This seems like it should be easy but I'm stumped. In WPF, I'd like a TextBox that stretches to the width of it's parent, but only to a maximum width. The problem is that I want it to be left justified within its parent. To get it to stretch you have to use HorizontalAlignment="Stretch", but then the result is centered. I've experimented with HorizontalContentAlignment, but it doesn't seem to do anything.

How do I get this blue text box to grow with the size of the window, have a maximum width of 200 pixels, and be left justified?

<Page
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&gt;
  <StackPanel>  
    <TextBox Background="Azure" Text="Hello" HorizontalAlignment="Stretch" MaxWidth="200" />
  </StackPanel>
</Page>

Am I making this too hard? What's the trick? Thanks!

+1  A: 
<Grid>
    <Grid.ColumnDefinitions>
     <ColumnDefinition Width="*" MaxWidth="200"/>
    </Grid.ColumnDefinitions>

    <TextBox Background="Azure" Text="Hello" />
</Grid>

HTH, Kent

Kent Boogaart
I think you need to set VerticalAlignment="Top" for the textbox.. seems to be stretch by default.
Gishu
+4  A: 

You can set HorizontalAlignment to Left, set your MaxWidth and then bind Width to the ActualWidth of the parent element

<Page
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&gt;
  <StackPanel Name="Container">   
    <TextBox Background="Azure" 
    Width="{Binding ElementName=Container,Path=ActualWidth}"
    Text="Hello" HorizontalAlignment="Left" MaxWidth="200" />
  </StackPanel>
</Page>
Nir
Doesn't autoresize.. Seems to be fit to content.. am I missing something?
Gishu
This seems to crash my silverlight player
resopollution
+1  A: 

Both answers given worked for the problem I stated -- Thanks!

In my real application though, I was trying to constrain a panel inside of a ScrollViewer and Kent's method didn't handle that very well for some reason I didn't bother to track down. Basically the controls could expand beyond the MaxWidth setting and defeated my intent.

Nir's technique worked well and didn't have the problem with the ScrollViewer, though there is one minor thing to watch out for. You want to be sure the right and left margins on the TextBox are set to 0 or they'll get in the way. I also changed the binding to use ViewportWidth instead of ActualWidth to avoid issues when the vertical scrollbar appeared.

Scott Bussinger
A: 

You can use this for the Width of your DataTemplate:

Width="{Binding ActualWidth,RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ScrollContentPresenter}}}"

Make sure your DataTemplate root has Margin="0" (you can use some panel as the root and set the Margin to the children of that root)

xyzzer