How do I get a TextBox to fill a resizable column?

imekon picture imekon · Jul 5, 2011 · Viewed 45k times · Source

I'm trying to get a TextBox to fill the available space in a resizable column. The TextBox is part of a user control:

<UserControl x:Class="TextBoxLayout.FieldControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Label Grid.Column="0">Name</Label>
        <TextBox Grid.Column="1"/>
    </Grid>
</UserControl>

This user control is in a window with a vertical splitter:

<Window x:Class="TextBoxLayout.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:TextBoxLayout"
    Title="Text box layout" Height="400" Width="600">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition MinWidth="100"/>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition MinWidth="100"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition/>
        </Grid.RowDefinitions>

        <local:FieldControl Grid.Column="0" Grid.Row="0" MaxWidth="200" HorizontalAlignment="Left"/>

        <TextBlock Grid.Column="0" Grid.Row="1" Text="Testing"/>

        <GridSplitter Grid.Column="1" Grid.Row="0" Grid.RowSpan="2" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Width="3"/>

        <TextBlock Grid.Column="2" Grid.Row="0" Grid.RowSpan="2" Text="Testing"/>
    </Grid>
</Window>

The problem is the TexTBox appears to be very narrow - what I'd want it to do is fill the left column and resize with the splitter. How do I do that?

Answer

anivas picture anivas · Jul 5, 2011

Use HorizontalAlignment="Stretch" instead of "Left" for FieldControl. Remove MaxWidth if required. Use TextAlignment to align text.