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

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


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>


<Grid>    <Grid.ColumnDefinitions>        <ColumnDefinition Width="*" MaxWidth="200"/>    </Grid.ColumnDefinitions>    <TextBox Background="Azure" Text="Hello" /></Grid>


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.