Dynamically Producing XAML files using XamlWriter.Save Method

The XamlWriter.Save is used to serialize the contents of a WPF application as a XAML file. I wrote a small sample in which we will be serializing the WPF objects to a XAML string

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Windows;

using System.Windows.Controls;

using System.IO;

using System.Windows.Data;

using System.Windows.Markup;

using System.Windows.Media;

namespace TestXAML

{

    class Program

    {

    [STAThread ]

        static void Main(string[] args)

        {

           int[] arr = new int[5] ;

            arr[0]=1;

            arr[1]=2;

            arr[2]=3;

            arr[3]=4;

arr[4]=5;

            ListBox objlst=new ListBox() ;

            objlst.ItemsSource = arr;

            objlst.Width = 200;

            StackPanel MyStackPanel=new StackPanel();

            SolidColorBrush brush = new SolidColorBrush();

            brush.Color = Color.FromRgb(200, 100, 255);

            MyStackPanel.Background = brush;

            MyStackPanel.Children.Add(objlst);

            string mystrXAML = XamlWriter.Save(MyStackPanel);

            FileStream fs = File.Create("testfile.xaml");

            StreamWriter sw = new StreamWriter(fs);

            sw.Write(mystrXAML);

            sw.Close();

            fs.Close();

        }

    }

}