Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having multiple controls in one WPF grid cell

Tags:

wpf

cell

grid

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!

like image 307
Shawn Avatar asked Apr 12 '12 21:04

Shawn


2 Answers

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

like image 159
Salvador Sarpi Avatar answered Sep 27 '22 17:09

Salvador Sarpi


You may want to use one of the Container Controls (like a Canvas, DockPanel, StackPanel) in the grid position (Row # + Column #) and then place your controls into that.

This makes it much easier to layout more than one control in a single grid position.

like image 38
Dan Rigby Avatar answered Sep 27 '22 18:09

Dan Rigby