MainWindow孩子在wpf应用程序中

时间:2015-02-28 00:47:23

标签: wpf xaml window parent-child mainwindow

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);
    }
}

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

如何在c#中显示它?

1 个答案:

答案 0 :(得分:0)

正如你所说的这句话

this.AddChild(b);

不会工作,因为错误指出它需要单个元素(即Grid,StackPanel)

为xaml中的网格命名 MainWindow.xaml

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

并将您的按钮添加到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
相关问题