在WPF中使用XamlWriter.Save方法动态产生XAML文件
AndyWan(放飞梦想) [翻译]
2008-1-16 11:14:13
来源:Ashish Thapliyal's Blog
浏览次数: 330
应用于:
  • Windows Presentation Foundation (WPF)
Tags:
在WPF应用程序中,XamlWriter.Save方法经常被用来把WPF应用程序的内容序列化成XAML文件。下面是一个小的例子,我们将把WPF对象序列化成一个XAML字符串:

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

        }

    }

}