测试页面: http://silverlight.services.live.com/invoke/84388/xaml2obj/iframe.html
- using System.IO;
- using System.Text;
- using System.Windows;
- using System.Windows.Controls;
- namespace xaml2obj
- {
- public partial class Page : UserControl
- {
- private TextBox sourceTextBox = new TextBox();
- private TextBox resultTextBox = new TextBox();
- public Page()
- {
- InitializeComponent();
- this.sourceTextBox.AcceptsReturn = true;
- this.resultTextBox.AcceptsReturn = true;
- this.sourceTextBox.TextWrapping = TextWrapping.Wrap;
- this.resultTextBox.TextWrapping = TextWrapping.Wrap;
- Canvas canvas = new Canvas();
- canvas.Width = 800;
- canvas.Height = 600;
- this.sourceTextBox.Width = 600;
- this.sourceTextBox.Height = 300;
- this.resultTextBox.Width = 600;
- this.resultTextBox.Height = 300;
- this.resultTextBox.SetValue(Canvas.TopProperty, 300.0);
- canvas.Children.Add(this.sourceTextBox);
- canvas.Children.Add(this.resultTextBox);
- this.LayoutRoot.Children.Add(canvas);
- this.sourceTextBox.TextChanged += new TextChangedEventHandler(sourceTextBox_TextChanged);
- }
- void sourceTextBox_TextChanged(object sender, TextChangedEventArgs e)
- {
- StringBuilder buffer = new StringBuilder(this.sourceTextBox.Text.Length);
- buffer.Append("{/n");
- buffer.Append(" string xaml = /n");
- StringReader reader = new StringReader(this.sourceTextBox.Text);
- string controlName = string.Empty;
- string firstLine = string.Empty;
- string line;
- int count = 0;
- while ((line = reader.ReadLine()) != null)
- {
- //第一行
- if (count == 0)
- {
- line = line.Trim();
- if (line.StartsWith("<") == true)
- {
- int space = line.IndexOf(' ');
- controlName = line.Substring(1, space);
- firstLine += line.Substring(0, space);
- firstLine += " xmlns=/"http://schemas.microsoft.com/client/2007/" ";
- firstLine += line.Substring(space, line.Length - space);
- }
- line = firstLine;
- }
- count++;
- //第一行
- buffer.Append("/"");
- foreach (char c in line)
- {
- if (c == '/"') buffer.Append('//');
- buffer.Append(c);
- }
- buffer.Append("/" + /n");
- }
- buffer.Remove(buffer.Length - 4, 4);
- buffer.Append(";/n");
- buffer.Append(string.Format("{0} {1} = ({0})System.Windows.Markup.XamlReader.Load(xaml);/n", controlName, controlName.ToLower()));
- buffer.Append("}/n");
- this.resultTextBox.Text = buffer.ToString();
- }
- }
- }