I am creating a control in WPF that shows units using a System.Windows.Control.RichTextBox
.
The problem is the RichTextBox control shows a plain text instead of a formatted text. I guess the RichTextBox control has a bug and I don't know how to do it, because it works depending on the computer.
The XAML code is,
<RichTextBox x:FieldModifier="private"
x:Name="TxtItem1"
IsReadOnly="True"
IsHitTestVisible="False"
HorizontalContentAlignment="Center"
VerticalContentAlignment="Center" />
And part of the code behind is:
private static void UpdateDocument(RichTextBox control, DependencyPropertyChangedEventArgs e)
{
string content = e.NewValue as string;
control.Document = content.Html1ToFlowDocument();
}
The function Html1ToFlowDocument converts a string into a FlowDocument. The following image is in a computer that the code goes fine (Windows 7 64 bits):
And the next one does not work (Windows 7 64 bits):
Another approach was using a RTF text but I have the problem.
The code of the function Html1ToFlowDocument,
public static class Html1ToDocument
{
public static FlowDocument Html1ToFlowDocument(this string text)
{
var mcFlowDoc = new FlowDocument();
XmlDocument doc = new XmlDocument();
doc.LoadXml(string.Format("<P>{0}</P>", text));
XmlElement root = doc.GetElementsByTagName("P")[0] as XmlElement;
IEnumerable<Inline> children;
try
{
children = ParseChildren(root);
}
catch (Exception ex)
{
throw new FormatException("Unsupported text.", ex);
}
var paragraph = new Paragraph();
paragraph.Inlines.AddRange(children);
mcFlowDoc.Blocks.Add(paragraph);
return mcFlowDoc;
}
private static IEnumerable<Inline> ParseChildren(XmlElement root)
{
Span sitem;
List<Inline> children;
foreach (XmlNode element in root.ChildNodes)
{
Inline item = null;
if (element is XmlElement)
{
XmlElement xelement = (XmlElement)element;
switch (xelement.Name.ToUpper())
{
case "SUB":
children = ParseChildren(xelement).ToList();
if (children.Count == 1 && children.First() is Run)
{
item = children.First();
item.Typography.Variants = FontVariants.Subscript;
}
else
{
sitem = new Span();
sitem.Typography.Variants = FontVariants.Subscript;
sitem.Inlines.AddRange(children);
item = sitem;
}
break;
case "SUPER":
children = ParseChildren(xelement).ToList();
if (children.Count == 1 && children.First() is Run)
{
item = children.First();
item.Typography.Variants = FontVariants.Superscript;
}
else
{
sitem = new Span();
sitem.Typography.Variants = FontVariants.Superscript;
sitem.Inlines.AddRange(children);
item = sitem;
}
break;
}
yield return item;
}
else if (element is XmlText)
{
item = new Run(element.InnerText);
yield return item;
}
}
}
}