Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 尝试从XAML页创建图像时WPF获取Null错误_C#_Wpf_Xaml_Png - Fatal编程技术网

C# 尝试从XAML页创建图像时WPF获取Null错误

C# 尝试从XAML页创建图像时WPF获取Null错误,c#,wpf,xaml,png,C#,Wpf,Xaml,Png,我是C#编程新手,很难在其他类中引用xaml文件 我正在尝试创建一个程序,该程序将从Xaml页面生成PNG文件。我可以从MainWindow.xaml中捕获画布,但我想从另一个名为overlay.xaml的xaml文件中获取画布 我已经将Overlay.xaml添加为一个页面,但是当我在MainWindow.xaml.cs类中引用它时,我会得到一个空值错误。我的假设是,因为overlay.xaml页面从未初始化,所以所有值都为null。如何导入或初始化overlay.xaml MainWindo

我是C#编程新手,很难在其他类中引用xaml文件

我正在尝试创建一个程序,该程序将从Xaml页面生成PNG文件。我可以从MainWindow.xaml中捕获画布,但我想从另一个名为overlay.xaml的xaml文件中获取画布

我已经将Overlay.xaml添加为一个页面,但是当我在MainWindow.xaml.cs类中引用它时,我会得到一个空值错误。我的假设是,因为overlay.xaml页面从未初始化,所以所有值都为null。如何导入或初始化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");
    }
}
公共部分类主窗口:窗口
{
公共覆盖层2;
公共主窗口()
{
初始化组件();
}
公共无效CaptureImage()
{

Rect Rect=new Rect(overly2.OverylayCanvas.RenderSize);那么,您可以在
主窗口中创建
overly2

public overlay overlay2;

public MainWindow()
{
    InitializeComponent();   
    overlay2 = new Overlay();
}
或者您可以在文件中初始化它


您可以在
main窗口中创建
overlay2

public overlay overlay2;

public MainWindow()
{
    InitializeComponent();   
    overlay2 = new Overlay();
}
或者您可以在文件中初始化它


您是否在代码的其他地方创建了覆盖图(使用new overlay())?您是否在代码的其他地方创建了覆盖图(使用new overlay())?成功了,谢谢。我添加了overlay2=new overlay();成功了,谢谢。我添加了overlay2=new overlay();
<Window x:Class="WpfApplication1...         
     ....
     <WpfApplication1:overlay x:Name="overlay2"></WpfApplication1:overlay>
     ....
</Window>
public partial class MainWindow : Window
{
    // public overlay overlay2; <-- is already declared in xaml.

    public MainWindow()
    {
        InitializeComponent();   
    }