Question

So I'm trying to add a datagrid and a button to my wpf form.

<Window x:Class="Database_Filler.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Database Filler" Height="350" Width="557">

    <DataGrid x:Name="data" HorizontalAlignment="Left" VerticalAlignment="Top" Height="230" Width="520"/>

    <!--<Button Content="Run Query" HorizontalAlignment="Left" Margin="468,294,0,0" VerticalAlignment="Top" Width="75" Click="Button1_Click"/>--> 

</Window>

But whenever I uncomment the button I get the error: "The property 'Content' is set more than once."

Was it helpful?

Solution

Window is ContentControl as such can host only one element. If you want to host more then one element then you need some sort of Panel that can host many children. You can choose from few implementations like Grid, StackPanel, WrapPanel and so on depending on how you want to arrange your items

<Window x:Class="Database_Filler.MainWindow" ...>
    <StackPanel>
        <DataGrid x:Name="data" HorizontalAlignment="Left" VerticalAlignment="Top" Height="230" Width="520"/>
        <Button Content="Run Query" HorizontalAlignment="Left" Margin="468,294,0,0" VerticalAlignment="Top" Width="75" Click="Button1_Click"/>
    </StackPanel>
</Window>

EDIT

Most commonly used Panel types:

  • Grid: Defines a flexible grid area that consists of columns and rows
  • DockPanel: Defines an area where you can arrange child elements either horizontally or vertically, relative to each other.
  • Canvas: Defines an area within which you can explicitly position child elements by using coordinates that are relative to the Canvas area.
  • StackPanel Arranges child elements into a single line that can be oriented horizontally or vertically.
  • WrapPanel Positions child elements in sequential position from left to right, breaking content to the next line at the edge of the containing box. Subsequent ordering happens sequentially from top to bottom or from right to left
  • UniformGrid Provides a way to arrange content in a grid where all the cells in the grid have the same size.

OTHER TIPS

The window can only have one child element. You need to put it e.g. inside a Grid or Stackpanel

<Window x:Class="Database_Filler.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Database Filler" Height="350" Width="557">

    <Stackpanel>
        <DataGrid x:Name="data" HorizontalAlignment="Left" VerticalAlignment="Top" Height="230" Width="520"/>

        <Button Content="Run Query" HorizontalAlignment="Left" Margin="468,294,0,0" VerticalAlignment="Top" Width="75" Click="Button1_Click"/>
    </Stackpanel>

</Window>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top