简体   繁体   中英

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" />

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.

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);
    }

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