Search code examples
wpftextbox

Make textbox width automatically changable in Stackpanel which is in Border, WPF


I wanted to put Button in TextBox, but as I found it's not possible so I decided to do something like this:

enter image description here

Xaml for this looks as shown below:

<Border Grid.Row="4" Grid.Column="2" Margin="10,0,10,0" 
            BorderBrush="Gray" BorderThickness="1">
        <StackPanel Orientation="Horizontal" Margin="0,0,0,0">
            <TextBox BorderBrush="LightGray" BorderThickness="1" Text="{Binding WaybillNumber}" 
                     Width="245"/>
            <Button  Content="*" Width="15" BorderThickness="1"/>
        </StackPanel>
    </Border>

The problem I have is that, when I resize my window (decreasing width) my Button dissapears:

enter image description here

I want it to behave as DateTimePicker does. I have tried many ways to make TextBox width auto adjustable ( * in width isn't correct input, auto decreases width of TextBox, I also tried to define style resource in StackPanel resources for TextBox width, but it doesn't work too), but Haven't found correct way yet.


Solution

  • Replace the StackPanel with a Grid:

    <Border Margin="10,0,10,0" BorderBrush="Gray" BorderThickness="1">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="Auto" />
            </Grid.ColumnDefinitions>
            <TextBox BorderBrush="LightGray" BorderThickness="1" Text="{Binding WaybillNumber}" />
            <Button Grid.Column="1" Content="*" Width="15" BorderThickness="1"/>
        </Grid>
    </Border>