简体   繁体   English

在TextBox上输入KeyDown,将空值保存到数据库中

[英]KeyDown Enter on the TextBox saves null value to the DataBase

Having strange behaviour. 具有奇怪的行为。 I am creating some sort of chat, in scope of which I have a TextBox, (which holds new message) and a method which sends this text to a database as a new message. 我正在创建某种形式的聊天,在该聊天的范围内,我有一个TextBox(用于保存新消息)和一种将文本作为新消息发送到数据库的方法。 I am calling for the sendMessage method in two separated ways: 我正在以两种单独的方式调用sendMessage方法:
1. By clicking (Click) on a button; 1.单击按钮上的(单击);
2. By pressing enter (KeyDown) on the TextBox. 2.在文本框上按Enter键(KeyDown)。

Now the strange behaviour: Click event saves the Text, all is ok. 现在,奇怪的行为:Click事件保存了Text,一切正常。
Enter key - sends one of two: Enter键-发送以下两个之一:
Or null (if in the current Controler session Enter key is the first, who invokes sendMessage); 或为null(如果在当前的Controler会话中,Enter键是第一个调用sendMessage的用户);否则为null。
Or the last saved message, which was invoked by Click. 或最后一次保存的消息(由Click调用)。

Here are the code snipets: 以下是代码片段:

XAML XAML

<Border Name="tbWriteMessage"
        Grid.Column="0"
        Grid.Row="2"
        Background="White"
        Width="{Binding Path=ActualWidth, ElementName=Ruler}"
        BorderBrush="{StaticResource BlueBrush}"
        BorderThickness="0,2,0,0">
    <TextBox Style="{StaticResource EnterMessageWatermark}"
             Text="{Binding Message}"
             KeyDown="tbNewMessage_KeyDown"
             x:Name="tbNewMessage"
             MaxHeight="21"/>
</Border>
<Button Style="{StaticResource Button}" 
        Name="btnEnviar"
        Click="btnEnviar_Click"
        Grid.Column="1"
        Grid.Row="2"
        VerticalAlignment="Top"
        Width="100"
        Height="23"
        Content="Enviar"
        BorderThickness="2,2,0,0"/>

CS CS

private void sendMessage()
{
    _viewModel.SaveNewMessage();
    tbNewMessage.Clear();
}

private void btnEnviar_Click(object sender, RoutedEventArgs e)
{
    sendMessage();
}

private void tbNewMessage_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Enter)
    {   
        sendMessage();
    }   
}

Would be more than grateful for pointing me the best approach in solving this obstacle. 将不胜感激为我指出解决这一障碍的最佳方法。
Thank you in advance! 先感谢您!

Ok, I found a workaround which is not so bad. 好的,我找到了一种不错的解决方法。
On key Enter I do: 在回车键上执行:
1. Send focus on different object (in my case it was the button, but it does not really matter). 1.将焦点放在另一个对象上(在我的情况下是按钮,但这并不重要)。
2. invoke sendMessage. 2.调用sendMessage。
3. set focus back on TextBox. 3.将焦点重新放在TextBox上。

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

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