The_Monster
The_Monster

Reputation: 510

WPF - issues with StackPanel

I am new to WPF and i can not figure some things out. I just started an new project and i wanted to make a StackPanel because i saw that on a tutorial. But now i've implemented the StackPanel and i get 2 errors.

The object 'Window' already has a child and cannot add 'StackPanel'. 'Window' can accept only one child. Line 9 Position 116.

The property 'Content' is set more than once.

Can someone explain to me what i am doeing wrong. This is my code:

<Window x:Class="CheckDatabase.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="CheckDatabase" Height="350" Width="525">
<Grid Margin="10,80,10,10" >
    <TextBox TextWrapping="Wrap"/>
</Grid>

<StackPanel Grid.Column="0" Grid.Row="0" HorizontalAlignment="Left" Name="ButtonPanel" VerticalAlignment="Top">
    <Button Margin="0,10,0,10">Button 1</Button>
    <Button Margin="0,10,0,10">Button 2</Button>
</StackPanel>

Thanks in advance

Upvotes: 2

Views: 2500

Answers (3)

Nitin Purohit
Nitin Purohit

Reputation: 18580

Window is a ContentControl and hence can have only one Content. You can do the following to have the expected layout

<Window x:Class="CheckDatabase.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="CheckDatabase" Height="350" Width="525">
<StackPanel>
  <Grid Margin="10,80,10,10" >
    <TextBox TextWrapping="Wrap"/>
  </Grid>

  <StackPanel Grid.Column="0" Grid.Row="0" HorizontalAlignment="Left" Name="ButtonPanel" VerticalAlignment="Top">
    <Button Margin="0,10,0,10">Button 1</Button>
    <Button Margin="0,10,0,10">Button 2</Button>
  </StackPanel>
</StackPanel>

Upvotes: 1

Martin Liversage
Martin Liversage

Reputation: 106826

A Window can only contain one child. However, your Window contains both a Grid and a StackPanel.

To fix this you need to put the StackPanel inside the grid (if that is the intention) or wrap both the Grid and the StackPanel inside another panel that positions the two elements in the way you want.

Upvotes: 5

JanW
JanW

Reputation: 1849

Some Controls like Window can only have a single child. You will have to remove the Grid or either nest another Grid arround your Grid and Stackpanel.

Example:

 <Grid x:Name="outerGrid">
     <Grid x:Name="innerGrid"></Grid>
     <StackPanel x:Name="innerStackPanel></StackPanel>
 </Grid>

Upvotes: 1

Related Questions