Philippe
Philippe

Reputation: 2007

Make WPF TextBox stretch to available space and not grow with Text

How do I make the TextBox stretch until the button with the three dots, but not cover it when somebody enters a lot of text?

My MainWindow.xaml:

<Window x:Class="Foo.Bar.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:p="clr-namespace:Foo.Bar.Properties"
        Title="MainWindow" Height="350" Width="525">
  <Grid>
    <StackPanel>
      <DockPanel>
        <Label Name="lblFileName" Content="File"></Label>
        <TextBox Name="txbFileName"></TextBox>
        <Button Name="btnOpenFileDialog" Content="..." HorizontalAlignment="Right"></Button>
      </DockPanel>
      <UniformGrid>
        <Button Name="btnFoo" Content="Foo"></Button>
        <Button Name="btnBar" Content="Bar"></Button>
      </UniformGrid>
    </StackPanel>
  </Grid>
</Window>

What it looks like:

Screenshot

Upvotes: 3

Views: 2763

Answers (2)

ouflak
ouflak

Reputation: 2508

You could set the MaxWidth of the TextBox to the width of the space you want to stay inside. This will take a bit of addition and subtraction, and maybe a bit of estimation, but it will work. Having it actually stretch seems a bit odd, but if you really want that in particular, then an example setting might be:

<TextBox Name="txbFileName" MaxWidth=300*></TextBox>

Upvotes: 1

Lukas Kubis
Lukas Kubis

Reputation: 929

To stretch your TextBox set LastChildFill="true" on DockPanel and add TextBox in the end.

Btw. If you're using DockPanel you can use DockPanel.Dock="Right" instead of HorizontalAlignment="Right".

<Grid>
    <StackPanel>
        <DockPanel LastChildFill="True">
            <Label Name="lblFileName" Content="File"></Label>
            <Button Name="btnOpenFileDialog" Content="..." DockPanel.Dock="Right"></Button>
            <TextBox Name="txbFileName"></TextBox>
        </DockPanel>
        <UniformGrid>
            <Button Name="btnFoo" Content="Foo"></Button>
            <Button Name="btnBar" Content="Bar"></Button>
        </UniformGrid>
    </StackPanel>
</Grid>

Upvotes: 5

Related Questions