user3925079
user3925079

Reputation:

XAML - How do I align controls next to each other in a StackPanel

I've been trying to align the controls in the following code next to each other. But it doesn't seem to work. First I had it without the StackPanel but then I couldn't really align my Controls properly.

Here is my code:

<StackPanel x:Name="doelenContentPanel" HorizontalAlignment="Center">
    <TextBlock x:Name="txtBOmzet" TextWrapping="Wrap" Text="Omzet:  " Margin="10,58,-10,-58" HorizontalAlignment="Left" />
    <TextBox x:Name="txtbOmzet" Margin="82,58,0,0" TextWrapping="Wrap" Text="" HorizontalAlignment="Center"/>
    <TextBlock x:Name="txtBOmzetMaand" Margin="151,58,0,0" TextWrapping="Wrap" Text="Maand" HorizontalAlignment="Right" />
</StackPanel>

Upvotes: 8

Views: 16134

Answers (2)

user3925079
user3925079

Reputation:

Got it! I added the Orientation="Horizontal" property to the StackPanel. However, this only aligns the content of this specific panel. If, for example, you want to have 2 StackPanel vertically aligned and then have the content of these 2 panels horizontally aligned, you have to do this:

<StackPanel x:Name="contentWrapper" Orientation="Vertical">
    <StackPanel x:Name="doelenContentPanel" Orientation="Horizontal">
    <TextBlock x:Name="txtBOmzet" TextWrapping="Wrap" Text="Omzet:  "  />
    <TextBox x:Name="txtbOmzet" TextWrapping="Wrap" Text="" />
    <TextBlock x:Name="txtBOmzetMaand" TextWrapping="Wrap" Text="Maand" />
</StackPanel>
<StackPanel x:Name="secondPanel" Orientation="Horizontal">
    *this looks familiar to the first panel*
</StackPanel>

Upvotes: 7

user1672994
user1672994

Reputation: 10839

First, don't use the hardcoded Margin property and second remove the HorizontalAlignment from each control. Now to align the control next to each other, set the Orientation property of StackPanel

<StackPanel x:Name="doelenContentPanel" Orientation="Horizontal">
  <TextBlock x:Name="txtBOmzet" TextWrapping="Wrap" Text="Omzet:  "  />
  <TextBox x:Name="txtbOmzet" TextWrapping="Wrap" Text="" />
  <TextBlock x:Name="txtBOmzetMaand" TextWrapping="Wrap" Text="Maand" />
</StackPanel>

Upvotes: 13

Related Questions