如何从 C# 代码创建和显示 WPF 内容?

How can I create and display WPF content from C# code?

我正在开发 WPF 应用程序,我想从 c# 代码而不是 XML 创建整个 window。

我尝试了下面的代码,但是没有任何反应,没有显示网格。我错过了什么?是否可以这样做或者是否有任何其他解决方案?

public MainWindow()
{
    Grid grd = new Grid();
    grd.Margin = new System.Windows.Thickness(10, 10, 10, 0);
    grd.Background = new SolidColorBrush(Colors.White);
    grd.Height = 104;
    grd.VerticalAlignment = System.Windows.VerticalAlignment.Top;
    grd.ColumnDefinitions.Add(new ColumnDefinition());
    grd.ColumnDefinitions.Add(new ColumnDefinition());
    grd.ColumnDefinitions.Add(new ColumnDefinition());

    RowDefinition row = new RowDefinition();
    row.Height = new System.Windows.GridLength(45);
    grd.RowDefinitions.Add(row);

    row = new RowDefinition();
    row.Height = new System.Windows.GridLength(45);
    grd.RowDefinitions.Add(row);

    row = new RowDefinition();
    row.Height = new System.Windows.GridLength(45);
    grd.RowDefinitions.Add(row);
    InitializeComponent();
}

Grid grd 已创建,但未添加到 Window。

InitializeComponent();
this.Content = grd;

它将替换所有在XAML中声明的内容(如果有的话)。

但是,Grid 是一个 Panel,它本身没有可视化表示,因此 window 没有子元素的 Grid 看起来仍然是空的。尝试 grd.ShowGridLines = true; 查看行和列

Grid documentation 实际上显示了一个大示例,具有等效的 c# 代码和 xaml 标记