Question

I have the following code to bold and italicise text in a RichEditBox:

private async void Page_KeyDown(object sender, KeyRoutedEventArgs e)
{
    var state = Window.Current.CoreWindow.GetKeyState(Windows.System.VirtualKey.Control);
    if ((state & CoreVirtualKeyStates.Down) == CoreVirtualKeyStates.Down)
    {
        switch (e.Key)
        {
            case Windows.System.VirtualKey.B:
                await BoldText();
                break;
            case Windows.System.VirtualKey.I:
                await ItaliciseText();
                break;
        }
    }
}

private async Task BoldText()
{
    ITextSelection selectedText = editor.Document.Selection;
    if (selectedText != null)
    {
        ITextCharacterFormat charFormatting = selectedText.CharacterFormat;
        charFormatting.Bold = FormatEffect.Toggle;
        selectedText.CharacterFormat = charFormatting;
    }
}

private async Task ItaliciseText()
{
    ITextSelection selectedText = editor.Document.Selection;
    if (selectedText != null)
    {
        ITextCharacterFormat charFormatting = selectedText.CharacterFormat;
        charFormatting.Italic = FormatEffect.Toggle;
        selectedText.CharacterFormat = charFormatting;
    }
}

BoldText() and ItaliciseText() are also called from buttons on a toolbar.

When Bold is pressed, the selected text is formatted to Bold text correctly.

When CTRL+B is pressed, the selected text is formatted to Bold text correctly.

When Italic is pressed, the selected text is formatted to Italic text correctly

When CTRL+I is pressed, the selected text is formatted to Italic text correctly, but then deleted

I know the formatting is happening because if I press CTRL+Z the text returns in italics. CTRL+I is causing an additional operation after selectedText.CharacterFormat = charFormatting; which wipes the text.

I can't figure out why this is happening as the code is almost identical to the flawless BoldText() code and words perfectly when fired from a button on the toolbar.

Any Ideas?

Was it helpful?

Solution

Ctrl+I may have another handler on it (which might be one causing text deleted), consider setting KeyRoutedEventArgs.Handled = true;, see this, (in this case e.Handled=true;) when you don't want this KeyEvent to be handled else where other than yours.

OTHER TIPS

Why you don't use, it's a good tool, and can download it easily http://www.textcontrol.com/en_US/sites/introduction/?gclid=CPTaj_LQh7wCFcJd3godZA4AZg

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top