简体   繁体   English

为什么设置要捕获的特定键时 WPF TextBox.KeyDown 事件不会触发?

[英]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.我试过让它专注于更改字体大小的主富文本框和父窗口,但它似乎根本没有触发e.Key == System.Windows.Input.Key.Return ,因为我尝试使用断点来查看它是否会命中它。 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.顺便说一句,我使用占位符 18 的原因是为了防止测试时出现异常。 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. RichTextBox本身已经处理了 ENTER 键: RichTextBox.AcceptsReturn默认为true ,这会导致在按下 ENTER 键时插入新行。

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 :通过将AcceptsReturn设置为false来禁用此行为(如果您想阻止用户显式添加新行。输入的文本仍会换行):

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

Or handle the tunneling PreviewKeyDown event instead of the bubbling KeyDown :或处理隧道PreviewKeyDown事件而不是冒泡KeyDown

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM