user1336827
user1336827

Reputation: 1826

Rich text box keep selected highlighted when focus is lost

I am creating a simple wysiwyg editor by using a dockpanel with some buttons for changing font size and such, and a richtextbox as the main area. I can highlight text and then use the buttons to change the size, and family of the font. However when I click in the "toolbar" the RichTextBox loses focus and the selected text is no longer highlighted. I have found several hacky solutions such as setting e.handled =true; on the lost focus event, this works but if the font size changes for example, the text is now larger than the highlight. Is there a better solution to this?

Here is some stripped down code:

    <DockPanel>
        <DockPanel >
            <ToggleButton Height="24" Margin="3" Name="Bold">
                <TextBlock FontWeight="ExtraBold" Text="B" />
            </ToggleButton>
            <ToggleButton Height="24" Margin="3" Name="Italic">
                <TextBlock FontStyle="Italic" Text="I" />
            </ToggleButton>
            <ToggleButton Height="24" Margin="3" Name="Underline">
                <TextBlock TextDecorations="Underline" Text="U" />
            </ToggleButton>
            <ComboBox Height="24" Margin="3" Name="FontFamily" Width="150" SelectionChanged="FontFamily_SelectionChanged"/>
            <ComboBox Height="24" Margin="3" Name="FontSize" Width="50" IsEditable="True" TextBoxBase.TextChanged="FontSize_TextChanged" />
        </DockPanel>
    </DockPanel>
    <RichTextBox Name="Editor" />

Upvotes: 0

Views: 1599

Answers (2)

user1336827
user1336827

Reputation: 1826

Ah, The solution to this was to simply use a <toolbar> rather than a <dockpanel> to house my buttons. This seems to do exactly what i want.

Upvotes: 2

HungDL
HungDL

Reputation: 513

Try this:

  private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
    {
        currentSize ++;
        RichTextBox.Selection.ApplyPropertyValue(TextElement.FontSizeProperty, currentSize);
        Keyboard.Focus(RichTextBox);
        RichTextBox.Selection.Select(RichTextBox.Selection.Start, RichTextBox.Selection.End);
    }

Upvotes: 0

Related Questions