c# - c#中的按键事件找出按下的键

标签 c# wpf

每当在 WPF 应用程序中按下回车键时,我都试图获取文本框的内容。但是没有 KeyPress 选项。所以我使用了 KeyDown 事件。但是每次控件都转到每个按键背后的代码。是有什么有效的替代方法吗?

private void txt_chat_KeyDown_1(object sender, KeyEventArgs e)
{
   if (e.Key == Key.Return)
   {
     txt_conversation.AppendText(Environment.NewLine+txt_chat.Text);
   }
   else { return; }
}

和我的 XAML

<RichTextBox IsReadOnly="True"
             ScrollViewer.VerticalScrollBarVisibility="Auto"
             x:Name="txt_conversation"
             HorizontalAlignment="Left"
             Height="150"
             Margin="21,21,0,0"
             VerticalAlignment="Top"
             Width="269">
  <FlowDocument>
    <Paragraph>
      <Run Text="RichTextBox" />
    </Paragraph>
  </FlowDocument>
</RichTextBox>
<TextBox ScrollViewer.VerticalScrollBarVisibility="Auto"
         KeyDown="txt_chat_KeyDown_1"
         x:Name="txt_chat"
         HorizontalAlignment="Left"
         Height="84"
         Margin="51,190,0,0"
         VerticalAlignment="Top"
         Width="209">
</TextBox>

最佳答案

这里不是直接放置 TextBox,而是可以将 Button 及其 Template 设置为 TextBox。这里的 Button 设置为 IsDefault 即只要按下 Enter 就会触发它的点击事件,对于 TextBox AcceptReturn 设置为 False,所以只要在 Textbox 有焦点时按下 Enter 键,父按钮单击事件将被触发。 这样,只有在按下回车键时才会触发事件

  <Button x:Name="myButton" IsDefault="True" Click="Button_Click">
        <Button.Template>
            <ControlTemplate>
                <TextBox AcceptsReturn="False" Text="{Binding Tag, RelativeSource={RelativeSource Mode=TemplatedParent}, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
            </ControlTemplate>
        </Button.Template>
    </Button>

在 Click 处理程序中,您可以从 TextBox.Text 绑定(bind)到的按钮 Tag 获取文本值。

     private void Button_Click(object sender, RoutedEventArgs e)
    {
        string text = myButton.Tag.ToString();
        txt_conversation.AppendText(Environment.NewLine+text );
    }

关于c# - c#中的按键事件找出按下的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19188764/

相关文章:

c# - 创建大列表<T>

c# - 使用转换器的数据触发器不起作用

c# - 生成mysql表主键字符串+数字的最佳方式

c# - 谁负责在传出消息的 SOAP header 中设置 To WS(Ws-Addressing) 命名空间?

c# - 绑定(bind) ComboBox ItemsSource 在 WPF 中不起作用

c# - XamlWriter.Save() 没有序列化 DependencyProperties

c# - 在 C# 中以编程方式调整 wpf 窗口的大小

c# - 私有(private)成员在 API 方法调用中突然为 null

c# - 使用 C# 从 CSV 导出到 MySQL 失败

c# - Process.WorkingSet64 和 Process.PeakWorkingSet64 的区别