Search code examples
wpfxamlbindingcontrolsstackpanel

WPF StackPanel to make the elements' width to be related each other


I'm very new in WPF

In my code, there is a StackPanel and it has 3 children controls.

<StackPanel Background="Green" Orientation="Horizontal">
    <TextBlock Width="200">
    <TextBlock Width=???>
    <TextBlock Width="200>
</StackPanel>

The First and Third TextBlocks have already their Width, but I want to make a Second TextBlock's Width to be dependent on Window's size. it means if Window's Width is 1000 - the 2nd TextBlock's Width should be 600. Probably I should use some Binding, but I'm not sure.

I appreciate your help. Thank you.


Solution

  • You should replace the StackPanel with a Panel that resizes its children, like for example a Grid:

    <Grid Background="Green">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="200" />
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="200" />
        </Grid.ColumnDefinitions>
        <TextBlock />
        <TextBlock Grid.Column="1" />
        <TextBlock Grid.Column="2" />
    </Grid>