Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HorizontalAlignment=Stretch, MaxWidth, and Left aligned at the same time?

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">   <StackPanel>       <TextBox Background="Azure" Text="Hello" HorizontalAlignment="Stretch" MaxWidth="200" />   </StackPanel> </Page> 

What's the trick?

like image 475
Scott Bussinger Avatar asked Nov 11 '08 08:11

Scott Bussinger


2 Answers

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">   <StackPanel Name="Container">        <TextBox Background="Azure"      Width="{Binding ElementName=Container,Path=ActualWidth}"     Text="Hello" HorizontalAlignment="Left" MaxWidth="200" />   </StackPanel> </Page> 
like image 56
Nir Avatar answered Oct 05 '22 22:10

Nir


<Grid>     <Grid.ColumnDefinitions>         <ColumnDefinition Width="*" MaxWidth="200"/>     </Grid.ColumnDefinitions>      <TextBox Background="Azure" Text="Hello" /> </Grid> 
like image 28
Kent Boogaart Avatar answered Oct 05 '22 22:10

Kent Boogaart