0

My problem is:

The user can search an address. If there was nothing found, the user sees an messagebox. He can close it by pressing ENTER. So far, so good. Calling SearchAddresses() can also be started by hitting ENTER. And now the user is in an endless loop because every ENTER (to let the messagebox disappear) starts an new search.

Here the codebehind:

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


private void queryTask_Failed(object sender, TaskFailedEventArgs e)
    {
        //throw new NotImplementedException();
        MessageBox.Show("*", "*", MessageBoxButton.OK);
        isMapNearZoomed = false;
    }

And here the xaml code:

<TextBox Background="Transparent" Name="TxtBoxAddress" Width="200" Text="" KeyUp="TxtBoxAddress_KeyUp"></TextBox>

<Button Content="Suchen" Name="btnSearch" Click="btnSearch_Click" Width="100"></Button>

How can I handle this endless loop in C#?

4

2 回答 2

2

哈哈。那是一个有趣的无限循环。有很多答案。

尝试添加一个全局字符串 _lastValueSearched。

private string _lastValueSearched;

private void TxtBoxAddress_KeyUp(object sender, KeyEventArgs e)
  {
    if (e.Key == Key.Enter && _lastValueSearched != TxtBoxAddress.Text)
      {
        //TxtBoxAddress.LoseFocus();
        btnSearch_Click(sender, e);
        _lastValueSearched = TxtBoxAddress.Text;
      }
  }


private void queryTask_Failed(object sender, TaskFailedEventArgs e)
 {
    //throw new NotImplementedException();
    MessageBox.Show("*", "*", MessageBoxButton.OK);
    isMapNearZoomed = false;
 }

所以在第一次进入内部 TxtBoxAddress 时,lastSearchValue 成为新的搜索值。当他们在消息框上按 enter 时,如果 TxtBoxAddress 文本没有更改,则不会触发 if 语句。

或者,注释掉的行, TxtBoxAddres.LoseFocus() 可以自己工作。这应该将焦点从 TextBox 上移开,因此当用户在消息框上按下 enter 时,TextBox KeyDown 不应触发。

于 2014-09-05T12:52:21.873 回答
0

使用KeyPress事件而不是KeyUp

private void textBox_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == 13) // handle 'Enter' key
        MessageBox.Show("test");
}
于 2014-09-05T12:56:42.547 回答