根据this MSDN Forum Posting,您可以使用命名空间的XamlWriter.Save方法System.Windows.Markup
。我修改了 RichtextBox 的给定示例并进行了测试。
来自 MSDN 链接的 XamlWriter 类的定义:
提供单个静态 Save 方法(多个重载),可用于将提供的运行时对象有限 XAML 序列化为 XAML 标记。
Xaml
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<RichTextBox Height="100" HorizontalAlignment="Left" Margin="10,10,0,0" Name="richTextBox1" VerticalAlignment="Top" Width="200" Background="#FF00F7F7">
<FlowDocument>
<Paragraph>
<Run Text="Hello World"/>
</Paragraph>
</FlowDocument>
</RichTextBox>
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="92,164,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
<Label Content="Label" Height="221" HorizontalAlignment="Left" Margin="216,12,0,0" Name="label1" VerticalAlignment="Top" Width="250" />
</Grid>
</Window>
Xaml.cs
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Markup;
using System.IO;
using System.Xml;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
string savedRichTextBox = XamlWriter.Save(richTextBox1);
File.WriteAllText(@"C:\Temp\Test.xaml", savedRichTextBox);
StringReader stringReader = new StringReader(savedRichTextBox);
XmlReader xmlReader = XmlReader.Create(stringReader);
RichTextBox rtbLoad = (RichTextBox)XamlReader.Load(xmlReader);
label1.Content = rtbLoad;
}
}
}
测试.xaml
<RichTextBox Background="#FF00F7F7" Name="richTextBox1" Width="200" Height="100" Margin="228,173,0,0" HorizontalAlignment="Left" VerticalAlignment="Top" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"><FlowDocument PagePadding="5,0,5,0" AllowDrop="True"><Paragraph>Hello World</Paragraph></FlowDocument></RichTextBox>