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?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With