wpf应用程序中的主窗口子项

wpf应用程序中的主窗口子项,wpf,xaml,window,parent-child,mainwindow,Wpf,Xaml,Window,Parent Child,Mainwindow,我有一些WPF4书籍中的按钮代码,我想从这里显示(不是从XAML),但当我想添加按钮“b”作为主窗口的子窗口时,我得到异常和信息:ContentControl的内容必须是单个元素 我怎样才能用c#?显示你说的这一行 public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); System.Windows.Controls.Button

我有一些WPF4书籍中的按钮代码,我想从这里显示(不是从XAML),但当我想添加按钮“b”作为主窗口的子窗口时,我得到异常和信息:ContentControl的内容必须是单个元素

我怎样才能用c#?

显示你说的这一行

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);
    }
}
无法工作,因为错误指出它需要单个元素(即网格、StackPanel)

在xaml中为网格指定一个名称 MainWindow.xaml

this.AddChild(b);

删除所有这些内容并使用适当的XAML。我已经知道有时候XAML是最好的解决方案,但我想知道这一点,因为我很好奇。所以MainWindow只能有一个子窗口,在这种情况下它是Grid,是吗?正确。。您也可以使用StackPanel、Canvas等任何面板
 <Grid x:Name="root">        
</Grid>
 //this.AddChild(b);   //wont work cant add button to this(MainWindow)
 root.Children.Add(b); //adds button to the Grid of MainWindow