Search code examples
wpfgridcell

Having multiple controls in one WPF grid cell


New to WPF and learing through tutorials online and have a couple of questions:

(1) I am trying to have multiple buttons of different widths appear side by side in one WPF grid cell. However, they seem to always stack up on each other. What am I missing out on?

(2) Is it possible to control the absolute starting left position for each button within the grid cell?

Thanks.

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:sys="clr-namespace:System;assembly=mscorlib" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
<ScrollViewer>
    <Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
          xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
          ShowGridLines ="True" >
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="200" />
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="60*" />
        </Grid.ColumnDefinitions>

        <Button Content="Button No. 1" Grid.Row="0" Grid.Column="0" />

        <GridSplitter HorizontalAlignment="Center" Width="6"
                      Grid.Row="0" Grid.Column="1" Grid.RowSpan="3" />

        <Button Content="Button No. 4-2" Grid.Row="0" Grid.Column="2" Width="100" />
        <Button Content="Button No. 4-1" Grid.Row="0" Grid.Column="2" Width="50" />

    </Grid>
</ScrollViewer>
</Page>

Based on the answer from Salvador, this works:

        <Button VerticalAlignment="Top" HorizontalAlignment="Left" Content="Button No. 1" Grid.Row="0" Grid.Column="0" Height="100"/>

        <GridSplitter HorizontalAlignment="Center" Width="6"
                      Grid.Row="0" Grid.Column="1" Grid.RowSpan="3" />

        <Button VerticalAlignment="Top" HorizontalAlignment="Left" Margin="0" Content="Button No. 4-2" Grid.Row="0" Grid.Column="2" Height="100" Width="100" />
        <Button VerticalAlignment="Top" HorizontalAlignment="Left" Margin="400,0,0,0" Content="Button No. 4-1" Grid.Row="0" Grid.Column="2" Height="150" Width="50" />

Thanks!


Solution

  • You are not setting the VerticalAlignment or the HorizontalAlignment property, so by default they are centered.

    You need to set those properties and use them in combination with the Margin property of wpf elements.

    Take a look at this Introduction to WPF Layout