I've been working with the new Silverlight4 RichTextBox control (which cannot properly decipher rich text from external apps, like Word, Excel, et al), and have discovered that the only way to get text into control is to set the RichTextBox.Xaml property. However, if you try to set the Xaml property to a non-Xaml string (in other words, a string that is not properly Xaml-ized), you get an exception. So, I came up with this extension method that checks to see if the string resembles a properly Xaml-ized string:
public static bool IsRichTextXaml(string str)
{
bool result = str.StartsWith("<Section xml") && str.EndsWith("</Section>");
return result;
}
For those of you unfortunate enough to have to use VB, here's the code for that:
<System.Runtime.CompilerServices.Extension> _
Public Function IsRichTextXaml(str As String) as Boolean
Dim result as Boolean = str.StartsWith("<Section xml") AndAlso str.EndsWith("</Section>")
Return result
End Function
Once the extension method is in place, you can do this(sorry - C# example only):
string myString = "This is not a Xaml-ized string";
if (myString.IsRichTextXaml())
{
this.myRichTextBox.Xaml = myString;
}
else
{
this.myRichTextBox.Selection.Text = myString;
}
You could also write an alternative extension method that simply converts a string to Xaml if necessary:
public static string MakeAsRichTextXaml(string str)
{
string result = str;
if (!str.IsRichTextXaml())
{
result = String.Format("<Section xml:space=\"preserve\"
HasTrailingParagraphBreakOnPaste=\"False\"
xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">
<Paragraph><Run Text=\"{0}\" /></Paragraph></Section>", result)
}
return result;
}
...or for VB:
<System.Runtime.CompilerServices.Extension> _
Public Function MakeAsRichTextXaml(ByVal str As String) As String
Dim result As String = str
If (Not result.IsRichTextXaml())
result = String.Format("<Section xml:space=""preserve""
HasTrailingParagraphBreakOnPaste=""False""
xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"">
<Paragraph><Run Text=""{0}"" /></Paragraph></Section>", result)
End If
Return result
End Function
Sorry about the formatting in the last two examples, but I had to do something to try to ensure you wouldn't need a horizontal scroll to see it all. Anyway, usage would look like this (again, only a C# example):
string myString = "This is not a Xaml-ized string";
this.myRichTextBox.Xaml = myString.MakeAsRichTextXaml();