WPF窗口是否可以包含子窗口

本文关键字:窗口 包含 是否 WPF | 更新日期: 2023-09-27 17:58:37

我有一个WPF窗口:

<Window x:Class="Snapit.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525" WindowState="Maximized"
    ShowInTaskbar="True" AllowsTransparency="True" WindowStyle="None" Opacity="0.1" 
    BorderThickness="25" BorderBrush="Black" Name="myWindow">
<Grid Name="myGrid">
</Grid>
</Window>

我有一个矩形

System.Windows.Shapes.Rectangle myRect = new System.Windows.Shapes.Rectangle();
        myRect = new System.Windows.Shapes.Rectangle();
        myRect.Stroke = System.Windows.Media.Brushes.Yellow;
        myRect.Fill = System.Windows.Media.Brushes.Black;
        myRect.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
        myRect.VerticalAlignment = VerticalAlignment.Center;
        myRect.Height = 50;
        myRect.Width = 50;
        myRect.Opacity = 100;
        myWindow.AddChild(myRect);

但我不能作为孩子添加矩形,错误如下:

{"'The invocation of the constructor on type 'Snapit.MainWindow' that matches the specified binding constraints threw an exception.' Line number '3' and line position '9'."}

我不明白我哪里错了。谢谢

WPF窗口是否可以包含子窗口

您的窗口只能有一个子窗口,它是您的网格。。。如果你想这样做,你应该改变

myWindow.AddChild(myRect);

myGrid.AddChild(myRect);

但是,为什么不使用xaml来编写矩形呢?阅读它会更干净…

将其添加到布局网格而不是窗口,

更改此行,

来自myWindow.AddChild(myRect);

myGrid.AddChild(myRect);

最终代码:

        System.Windows.Shapes.Rectangle myRect = new System.Windows.Shapes.Rectangle();
        myRect = new System.Windows.Shapes.Rectangle();
        myRect.Stroke = System.Windows.Media.Brushes.Yellow;
        myRect.Fill = System.Windows.Media.Brushes.Black;
        myRect.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
        myRect.VerticalAlignment = VerticalAlignment.Center;
        myRect.Height = 50;
        myRect.Width = 50;
        myRect.Opacity = 100;
        myGrid.AddChild(myRect);