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();


        }


    }


}

Comments (2)

  1. Heer says:

    Good example  , i believe now we have lots of other good ways to generate XAML.

  2. That's good enough to generate a xaml page like a dummy html page in old times. The main striking idea is to generate something more functional with this. Howz about generating a fresh UI like this (i mean dynamic xaml) and attaching the event-handlers from an existing business-rule .cs class file.

    Does that make any sense?

    • A
Skip to main content