namespace TestRichTextBox
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
string str = FlowDocumentToString(RichBox.Document);
xamlStringBox.Text = str;
}
private string FlowDocumentToString(FlowDocument doc)
{
var settings = new XmlWriterSettings { Indent = true, OmitXmlDeclaration = true };
StringBuilder sb = new StringBuilder();
var dm = new XamlDesignerSerializationManager(XmlWriter.Create(sb, settings));
dm.XamlWriterMode = XamlWriterMode.Expression;
XamlWriter.Save(doc, dm);
return sb.ToString();
}
}
}
<Window x:Class="TestRichTextBox.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>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid HorizontalAlignment="Left" Height="300" VerticalAlignment="Top" Width="483" Grid.RowSpan="2" Margin="10,20,0,0">
<TextBox Name="xamlStringBox" HorizontalAlignment="Left" Height="152" Margin="0,138,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="393"/>
<Button Content="Button" HorizontalAlignment="Left" Margin="398,225,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
</Grid>
<RichTextBox Name="RichBox" HorizontalAlignment="Left" Height="127" Margin="10,10,0,0" VerticalAlignment="Top" Width="393">
<FlowDocument>
<Paragraph>
<Run Text=""/>
</Paragraph>
</FlowDocument>
</RichTextBox>
</Grid>
</Window>
Run the sample code and type { in the RichBox at first char, Click the button, the xamlStringBox will show the serialized FlowDocument. The paragraph shows:
<Paragraph>{}{</Paragraph>
Is this a bug? Is there any walk-around?
Thanks