尝试从 XAML 页面创建图像时 WPF 出现 Null 错误

WPF getting Null error when trying to create image from XAML page

我是 C# 编程的新手,在不同的 class 中引用 xaml 文件有困难。

我正在尝试创建一个程序,该程序将从 Xaml 页面生成 PNG 文件。我能够从 MainWindow.xaml 中捕获 Canvas,但我想从另一个名为 overlay.xaml 的 XAMl 文件中捕获它。

我已经将 Overlay.xaml 添加为一个页面,但是每当我在 MainWindow.xaml.cs class 中引用它时,我都会收到 NULL 值错误。我的假设是,因为 overlay.xaml 页面从未初始化,所以所有值都是空的。如何导入或初始化 overlay.xaml?

MainWindow.xaml.cs

public partial class MainWindow : Window
{
    public overlay overlay2;
    public MainWindow()
    {
        InitializeComponent();   
    }

    public void CaptureImage()
    {
        Rect rect = new Rect(overlay2.OverylayCanvas.RenderSize);  <--- Returns the null error
        RenderTargetBitmap rtb = new RenderTargetBitmap((int)rect.Right,
            (int)rect.Bottom, 96d, 96d, System.Windows.Media.PixelFormats.Default);
        rtb.Render(overlay2.OverylayCanvas);
        //encode as PNG
        BitmapEncoder pngEncoder = new PngBitmapEncoder();
        pngEncoder.Frames.Add(BitmapFrame.Create(rtb));

        //Save to memory
        System.IO.MemoryStream ms = new System.IO.MemoryStream();

        pngEncoder.Save(ms);
        ms.Close();
        System.IO.File.WriteAllBytes("Generated_Image.png", ms.ToArray());
        Console.WriteLine("Done");
    }
}

Overlay.xaml

<Page x:Class="WpfApplication1.overlay"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
  xmlns:local="clr-namespace:ScoreboardUpdate"
  mc:Ignorable="d" 
  d:DesignHeight="150" d:DesignWidth="500"
  Title="overlay">

<Canvas x:Name="OverylayCanvas" Canvas.Left="0" Canvas.Top="20" x:FieldModifier="public">
    <Rectangle Fill="#FFF4F4F5" Height="72" Canvas.Left="58" Stroke="Black" Canvas.Top="37" Width="258"/>
</Canvas>

好吧,您可以在 MainWindow 构造函数中创建 overlay2

public overlay overlay2;

public MainWindow()
{
    InitializeComponent();   
    overlay2 = new Overlay();
}

或者您可以在 MainWindow.xaml 文件中对其进行初始化。

<Window x:Class="WpfApplication1...         
     ....
     <WpfApplication1:overlay x:Name="overlay2"></WpfApplication1:overlay>
     ....
</Window>

那么你应该从 MainWindow.xaml.cs 中删除 overlay2 声明,因为它已经在 xaml 文件中声明了。

public partial class MainWindow : Window
{
    // public overlay overlay2; <-- is already declared in xaml.

    public MainWindow()
    {
        InitializeComponent();   
    }