本文共 4488 字,大约阅读时间需要 14 分钟。
有时候,我们需要将WPF中的控件自身的XAML代码输出成文本,那么,我们可以使用System.Windows.Markup.XamlWriter.Save()方法来完成此任务。关于XamlWriter.Save()的示例,我曾经在“在WPF中,如何得到任何Object对象的XAML代码?”()Blog中有所介绍,此处不再赘述。
使用上述方法时,我们发现,输出的XAML代码并不“标准”,不是格式化的XML代码,我们看这样的代码时,会有一种头晕的感觉。那么,怎样输出成已格式化过的XAML代码呢?
答案是借助System.Xml.XmlWriter及对System.Xml.XmlWriterSettings设置来解决。
代码:
以下代码示例演示在txtBoxXamlCode文本框中显示名为“canvasContent”的Canvas控件的自身XAML代码:// Line.xaml中的部分关键代码:<Canvas Width="630" Height="400" Name="canvasContent">// Line.xaml.cs:using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Windows;using System.Windows.Controls;using System.Windows.Data;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Imaging;using System.Windows.Navigation;using Shapes = System.Windows.Shapes;using System.Windows.Markup;using System.Xml;namespace BrawDraw.Com.Book.WPF.Demo.Lines
{ /// <summary> /// Interaction logic for Window1.xaml /// </summary> public partial class LineDemo : Window { public LineDemo() { InitializeComponent(); InitCanvasChildren(); }private void InitCanvasChildren()
{ double angle = 120; double centerX = 200; double centerY = 200; double strokeThickness = 10;for (int i = 0; i < 360; i += (int)angle)
{ Shapes.Line lineRotate = new System.Windows.Shapes.Line(); lineRotate.Stroke = new SolidColorBrush(Colors.Black); lineRotate.X1 = 0; lineRotate.Y1 = centerY; lineRotate.X2 = centerX; lineRotate.Y2 = centerY; lineRotate.StrokeDashArray = new DoubleCollection(new double[] { 0, 3 }); lineRotate.StrokeThickness = strokeThickness; lineRotate.StrokeDashCap = PenLineCap.Round; lineRotate.StrokeStartLineCap = PenLineCap.Round; lineRotate.StrokeEndLineCap = PenLineCap.Round; RotateTransform rt = new RotateTransform(i, centerX, centerY); lineRotate.RenderTransform = rt; canvasContent.Children.Add(lineRotate); } }// 输出显示未格式化的XAML代码
private void btnViewXaml_Click(object sender, RoutedEventArgs e) { txtBoxXamlCode.Text = XamlWriter.Save(canvasContent); }// 输出显示已格式化过的XAML代码 private void btnViewFormattedXaml_Click(object sender, RoutedEventArgs e) { XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.IndentChars = new string(' ', 4); settings.NewLineOnAttributes = true; StringBuilder sb = new StringBuilder(); XmlWriter xmlWriter = XmlWriter.Create(sb, settings); XamlWriter.Save(canvasContent, xmlWriter); txtBoxXamlCode.Text = sb.ToString(); xmlWriter.Close(); sb = null; } }}运行效果图:很明显,后者可读性强得多。
转载地址:http://eticm.baihongyu.com/