简体   繁体   中英

Why is WPF TextBox.KeyDown event not firing when a specific key to catch is set?

I am making a word processor and I want the user to enter the font size in the text box, and when they press enter, if no text is selected, then the whole box should change in font size. And if text is selected, it should change the size of only that text. However, this only works when the key down event is fired without checking what key was pressed. And it only works with a double literal. No variables.

For examplpe, this kind of works:

private void FontSizeBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
    (new TextRange(rtb.Selection.Start, rtb.Selection.End)).ApplyPropertyValue(TextElement.FontSizeProperty, Convert.ToDouble(18));
}

But this doesn't:

private void FontSizeBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
    if (e.Key == System.Windows.Input.Key.Return)
    {
        (new TextRange(rtb.Selection.Start, rtb.Selection.End)).ApplyPropertyValue(TextElement.FontSizeProperty, Convert.ToDouble(18));
    }
}

I have tried making it focus on the main rich text box whose font size is changed, and on the parent window, but it doesn't seem to even fire the e.Key == System.Windows.Input.Key.Return at all, because I tried using a breakpoint to see if it would hit it. And it did not hit. And so, I am very confused.

How do I make it so that if the enter key is pressed, the value of the text box is the font size of the main rich text box? BTW, the reason I used the placeholder 18 is to prevent exceptions while testing. I wanted to see if it would actually change.

Thanks in advance.

RichTextBox itself already handles the ENTER key: RichTextBox.AcceptsReturn defaults to true , which results in inserting a new line on ENTER key pressed.

Either disable this behavior (in case you want to prevent ther user from adding new lines explicitly. Entered text would still wrap) by setting AcceptsReturn to false :

<RichTextBox x:Name="rtb" 
             AcceptsReturn="False" 
             KeyDown="FontSizeBox_KeyDown" />

Or handle the tunneling PreviewKeyDown event instead of the bubbling KeyDown :

<RichTextBox x:Name="rtb" 
             PreviewKeyDown="FontSizeBox_PreviewKeyDown" />

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