0
votes

I've got a WPF RichTextBox which loads RTF content perfectly (English characters). The problem comes when trying to set Japanese characters (e.g. ユーザに) into the editor. When doing this, the result is the following:

After textRange.Load

It seems something about the Encoding ... so I adapted my code to use Unicode instead of UTF8. Anyway, it's not working. My code to load text into the RTF editor is as simple as follows:

private void Window_Loaded(object sender, RoutedEventArgs e) {

            string text = "ユーザに";
            TextRange textRange = new TextRange(MyRichTextBox.Document.ContentStart, MyRichTextBox.Document.ContentEnd);
            textRange.Load(new MemoryStream(Encoding.Unicode.GetBytes(text)), DataFormats.Rtf);
        }

Finally, the XAML layout does not have anything special:

<Window x:Class="Tester.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Loaded="Window_Loaded"
    Title="MainWindow" Height="350" Width="525">
    <Grid>
        <RichTextBox x:Name="MyRichTextBox" Margin="3"></RichTextBox>
    </Grid>
</Window>

Just in case it helps ... I've got installed the Japanese language in this computer, and it looks good. Furthermore, if I paste (ctrl+v) Japanese characters on the editor once it's loaded, it appears to work.

After Control+V

Thanks in advance!

1
Encoding.Unicode.GetBytes(text) what does this default to UTF-8? - johnny 5
@johnny5 what do you mean? - Borja López

1 Answers

0
votes

You can't use raw text as DataFormats.Rtf. However, You can set the TextRange.Text property directly, or use TextRange.Load(new MemoryStream(Encoding.UTF8.GetBytes("ユーザに")), DataFormats.Text).

A rtf document containing the text would actually look like this:

{\rtf
{\ltrch \u12518?\u12540?\u12470?\u12395?}
}

Code:

    var text = 
@"
{\rtf
{\ltrch \u12518?\u12540?\u12470?\u12395?}
}
";

    var range = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd);
    //range.Text = text;
    range.Load(new MemoryStream(Encoding.Default.GetBytes(text)), DataFormats.Rtf);

The unicode can be generated with this line:

string.Concat("ユーザに".Select(x => @"\u" + (int)x + "?"))