2

Am trying to get the content of a textbox whenever enter key is pressed in WPF application.But there is no option for KeyPress.So i used KeyDown event.But each time the control goes to the code behind for every keypress.Is there any efficient alternate for this ?

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

and my 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>
4

1 回答 1

0

在这里,您可以将 ButtonTemplate设置为 TextBox,而不是直接放置 TextBox。这里 Button 设置为IsDefaultie,只要按下 Enter 就会触发其单击事件,并且将 forTextBox AcceptReturn设置为 False,因此当文本框具有焦点时,只要按下 Enter 键,就会触发父按钮单击事件。这样,只有在按下 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 处理程序中,您可以从绑定Tag到的按钮中获取 Text 值。TextBox.Text

     private void Button_Click(object sender, RoutedEventArgs e)
    {
        string text = myButton.Tag.ToString();
        txt_conversation.AppendText(Environment.NewLine+text );
    }
于 2013-10-04T19:24:54.270 回答