Search code examples
wpfxamlstackpanel

wpf xaml panel size


I'm sure there is a simple explanation why this is happening but can't seem to find it. From the code below why do my text boxes extend past the window? I would think since i have set the width of them to equal the size of the window that they would align up perfectly... however run this and it is obviously not the case. What am i missing? What would be the proper way of setting the width?

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="300" Width="200">
    <StackPanel Orientation="Horizontal">
        <TextBox Width="100">Hello</TextBox>
        <TextBox Width="100" TextAlignment="Right">World</TextBox>
    </StackPanel>
</Window>

Solution

  • The Width of the Window includes things like the border, and the Height includes things like the titlebar. So you'd need to take those into account when setting the Width/Height. You can use the SizeToContent option on Window to have it size to fit the TextBoxes.

    Like:

    <Window ... SizeToContent="Width"
    

    Or you could replace your StackPanel with a Grid to give each TextBox half of the Window's available width:

    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
    
        <TextBox Grid.Column="0">Hello</TextBox>
        <TextBox Grid.Column="1" TextAlignment="Right">World</TextBox>
    </Grid>