【问题标题】:MainWindow child in wpf applicationwpf应用程序中的MainWindow子项
【发布时间】:2015-02-28 00:47:22
【问题描述】:
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# 中显示它?

【问题讨论】:

  • 删除所有内容并使用正确的 XAML。
  • 我已经知道有时 XAML 是最好的解决方案,但我想知道这一点,因为我很好奇。

标签: wpf xaml window parent-child mainwindow


【解决方案1】:

正如你所说的这一行

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

【讨论】:

  • 所以MainWindow只能有一个孩子,在这种情况下是Grid,是吗?
  • 正确.. 你也可以使用 StackPanel、Canvas 等任何面板
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-07
  • 2021-11-10
  • 1970-01-01
  • 1970-01-01
  • 2020-03-06
  • 1970-01-01
  • 2017-03-14
相关资源
最近更新 更多