matt-pielat
matt-pielat

Reputation: 1799

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 - e.g. 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?

Upvotes: 0

Views: 375

Answers (1)

Tzah Mama
Tzah Mama

Reputation: 1567

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

Upvotes: 1

Related Questions