简体   繁体   中英

WPF: RichTextBox selection style properties are reset

I've made a simple text editor (based on RichTextBox) that can bolden/tilt/change font size of selected text. And those things work just fine - eg I can apply both Bold and Italic to the same selection.

I recently added "Capitalize" button:

private void buttonCapitalize_Click(object sender, RoutedEventArgs e)
{
    if (!textField.Selection.IsEmpty)
    {
        textField.Selection.Text = textField.Selection.Text.ToUpper();
    }
}

aand it kinda works. Whenever I click it the selected text is capitalized but also other properties (of the current selection only) such as FontStyle, FontWeight are set to normal and FontSize to default.

Is there any better way to implement this?

I run some testing and from my results it seems that the RichTextBox will always take the style from the 1st character BEFORE your selection and not the default style as you mentioned

This probably happens because

textField.Selection.Text = textField.Selection.Text.ToUpper();

will actually create a new string and not edit it (strings are immutable in C#)
If you want to keep your styling I'm guessing that you'll have to iterate over your selection and create it per selected char

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM