Since the UI of WPF is expressed in XAML, we can use this advantage to save the XAML element in WPF as a variety of files. In many cases, this operation is not required. Save the XAML as an image, string, and XPS. Here I have written some methods for your reference.
Note: Before saving the following, make sure that the canvas in the parameter is high and wide.
1. Save canvas as a text file
1: using system. Windows. markup;
2: using system. IO;
1: Public void Export (URI path, canvas surface)
2 :{
3: If (Path = NULL) return;
4: If (surface = NULL) return;
5:
6: String XAML = xamlwriter. Save (surface );
7: file. writealltext (path. localpath, XAML );
8 :}
2. Save the canvas as An XPS file. The XPs namespace is in reachframework. dll.
1: using system. Io. packaging;
2: using system. Windows. XPS;
3: using system. Windows. XPS. packaging;
4: using system. IO;
1: Public void Export (URI path, canvas surface)
2 :{
3: If (Path = NULL) return;
4:
5: Transform transform = surface. layouttransform;
6: surface. layouttransform = NULL;
7:
8: size = new size (surface. Width, surface. Height );
9: surface. Measure (size );
10: surface. Arrange (New rect (size ));
11:
12: Package package = package. Open (path. localpath, filemode. Create );
13: xpsdocument Doc = new xpsdocument (Package );
14: xpsdocumentwriter writer = xpsdocument. createxpsdocumentwriter (DOC );
15: writer. Write (surface );
16: Doc. Close ();
17: package. Close ();
18:
19: surface. layouttransform = transform;
20 :}
3. Save the canvas as an image
1: Public void exporttopng (URI path, canvas surface)
2 :{
3: If (Path = NULL) return;
4:
5: Transform transform = surface. layouttransform;
6: surface. layouttransform = NULL;
7:
8: size = new size (surface. Width, surface. Height );
9: surface. Measure (size );
10: surface. Arrange (New rect (size ));
11:
12: rendertargetbitmap renderbitmap =
13: New rendertargetbitmap (
14: (INT) size. Width,
15: (INT) size. height,
16: 96d,
17: 96d,
18: pixelformats. pbgra32 );
19: renderbitmap. Render (surface );
20:
21: Using (filestream outstream = new filestream (path. localpath, filemode. Create ))
22 :{
23: pngbitmapencoder encoder = new pngbitmapencoder ();
24: encoder. frames. Add (bitmapframe. Create (renderbitmap ));
25: encoder. Save (outstream );
26 :}
27: surface. layouttransform = transform;
28 :}
Conclusion:
These are all used in WPF for win, hoping to help you.