与异步更新并行编辑文本框

时间:2016-01-11 23:53:12

标签: c# asynchronous textbox

所以在我的项目中,我有一些文本框,它们包含两个角的坐标(纬度和经度)。 textBox由计时器更新(如果接收的值与当前值不同,则从服务器获取值并设置textBoxes)。问题是,我希望textBoxes可用于手动编辑;但是,如果我正在键入数字并且计时器检查当前值,他会看到它与服务器返回的内容不同并立即更改它。有没有办法检查目前是否正在编辑textBox,还是更好的方法来解决此解决方案?

代码(示例,两个角的代码相同):

if (northEastLatitude != double.Parse(neLatTB.Text)) //neLatTB is the textBox
      neLatTB.Text = northEastLatitude.ToString();


else //No answer returned from the server so we need to reset the textBoxes
{
      northEastLatitude = 0;
      northEastLongitude = 0;
      if(neLatTB.Text != "0")
             neLatTB.Text = northEastLatitude.ToString();
      if(neLngTB.Text != "0")
             neLngTB.Text = northEastLongitude.ToString();
}

另外,我为所有textBox都有TextChanged事件的函数(所以当我手动设置坐标时,它会将它们上传到服务器)。有什么方法可以防止在按下点键时调用此函数吗?显然它也调用了事件(标记了文本输入的结尾)。

1 个答案:

答案 0 :(得分:0)

这实际上取决于您的设计,但如果您想使用TextBox来显示可更新的值并且还可以编辑,则必须禁止执行计时器中的代码。 WinForms TextBox没有选项可以显示文本是以编程方式还是通过用户交互进行更改。你必须以某种方式自己做。

有很多方法可以做到courde。一种方法是使用Enter / Leave个事件来检测TextBox何时获得或失去焦点。但是需要在编辑后点击控件中的somwhere。

另一个,您可能希望使用TextChanged事件阻止您的计时器更新字段,直到TextBox中的文字全部输入为止。我会做那样的事情:

Fisrtly我会声明两个bool变量来阻止执行代码部分:

private bool _isDirty; // used when user types text directly
private bool _suppresTextChanged; // used when timer updates value programmatically

之后我会写TextBox.TextChanged事件监听器:

private void neLatTBTextChanged(object sender, EventArgs args)
{
    if(_suppressTextChanged)
        return;
    _isDirty = true; // toggle dirty state

    if(/* text has good format */)
    {
        // Upload changes to server
        _isDirty = false; // end manual edit mode
    }
}

内部计时器方法我会设置:

_suppresTextChanged = true; // on the beginning

if (northEastLatitude != double.Parse(neLatTB.Text)) //neLatTB is the textBox
  neLatTB.Text = northEastLatitude.ToString();
else //No answer returned from the server so we need to reset the textBoxes
{
      northEastLatitude = 0;
      northEastLongitude = 0;
      if(neLatTB.Text != "0")
             neLatTB.Text = northEastLatitude.ToString();
      if(neLngTB.Text != "0")
             neLngTB.Text = northEastLongitude.ToString();
}

_suppresTextChanged = false; // after edit was made

我个人认为这种设计会导致很多问题(考虑当用户停止输入并将TextBox保留在_isDirty状态等时要做什么......)。我不会仅使用TextBox来添加Label来存储来自计时器的数据(可能是用户将要输入的数据),而只是为了输入用户特定值而留下TextBox