0
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        System.Windows.Controls.Button b = new System.Windows.Controls.Button(); 
        System.Windows.Shapes.Rectangle r = new System.Windows.Shapes.Rectangle(); 
        r.Width = 40; 
        r.Height = 40; 
        r.Fill = System.Windows.Media.Brushes.Black; 
        b.Content = r; // Make the square the content of the Button
        this.AddChild(b);
    }
}

I have code for button from some WPF 4 book, and i want to display from here ( not from XAML), but when i want to add button 'b' as a child of main window i get exception and info : Content of a ContentControl must be a single element.

How can i display it in c#?

Kamiel
  • 21
  • 3

1 Answers1

0

As you say this line

this.AddChild(b);

wont work as the error points out it requires a single element (ie Grid, StackPanel)

Give your Grid in xaml a name MainWindow.xaml

 <Grid x:Name="root">        
</Grid>

and add your button to the Grid in MainWindow.xaml.cs

 //this.AddChild(b);   //wont work cant add button to this(MainWindow)
 root.Children.Add(b); //adds button to the Grid of MainWindow
SWilko
  • 3,542
  • 1
  • 16
  • 26