Reputation: 3
I am new to C# programming and having difficulty referencing a xaml file in a different class.
I am trying to create a program that will generate a PNG file from a Xaml page. I am able to capture the Canvas from the MainWindow.xaml, but I want to grab it from a different XAMl file called overlay.xaml.
I've added the Overlay.xaml as a page but when ever I reference it in the MainWindow.xaml.cs class I get a NULL value error. My assumption is that because the overlay.xaml page is never initialized all the values are null. How do I import, or initialize the 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>
Upvotes: 0
Views: 92
Reputation: 5488
Well, you can create overlay2
in a MainWindow
constructor
public overlay overlay2;
public MainWindow()
{
InitializeComponent();
overlay2 = new Overlay();
}
Or you can initialize it in MainWindow.xaml file.
<Window x:Class="WpfApplication1...
....
<WpfApplication1:overlay x:Name="overlay2"></WpfApplication1:overlay>
....
</Window>
Then you should remove the overlay2
declaration from MainWindow.xaml.cs, because it is already declared in xaml file.
public partial class MainWindow : Window
{
// public overlay overlay2; <-- is already declared in xaml.
public MainWindow()
{
InitializeComponent();
}
Upvotes: 2