C# 与异步更新并行编辑文本框
因此,在我的项目中,我有几个文本框,其中包含两个角的坐标(纬度和经度)。文本框由计时器更新(计时器从服务器获取一个值,如果接收到的值与当前值不同,则设置文本框)。问题是,我希望文本框可以手动编辑;但是,如果我正在键入数字,计时器检查当前值,他会发现它与服务器返回的内容不同,并立即更改。有没有办法检查文本框目前是否正在编辑,或者有更好的办法解决这个问题 代码(示例,两个角的代码相同):C# 与异步更新并行编辑文本框,c#,asynchronous,textbox,C#,Asynchronous,Textbox,因此,在我的项目中,我有几个文本框,其中包含两个角的坐标(纬度和经度)。文本框由计时器更新(计时器从服务器获取一个值,如果接收到的值与当前值不同,则设置文本框)。问题是,我希望文本框可以手动编辑;但是,如果我正在键入数字,计时器检查当前值,他会发现它与服务器返回的内容不同,并立即更改。有没有办法检查文本框目前是否正在编辑,或者有更好的办法解决这个问题 代码(示例,两个角的代码相同): 此外,我还有用于所有文本框的TextChanged事件的函数(因此,当我手动设置坐标时,它会将它们上载到服务器)
此外,我还有用于所有文本框的TextChanged事件的函数(因此,当我手动设置坐标时,它会将它们上载到服务器)。是否有任何方法可以防止每当我按下点键时调用此函数?显然,它也会调用事件(标记输入文本的结束)。这实际上取决于您的设计,但如果您想使用
TextBox
显示可更新的值并进行编辑,则必须抑制计时器中的代码才能执行。WinFormsTextBox
没有选项显示文本是以编程方式更改还是通过用户交互更改。你必须自己去做
库尔德有很多方法可以做到这一点。一种方法是使用输入
/离开
事件来检测文本框
何时获得或失去焦点。但是在编辑之后,需要从控件中单击somwhere
另一个,您可能希望使用TextChanged
事件来防止计时器更新字段,直到TextBox
中的文本全部输入完毕。我会这样做:
首先,我将声明两个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
我个人认为这种设计可能会导致很多问题(考虑当用户停止键入并将
文本框保持在\u isDirty
状态时该怎么办等等)。我不会只使用TextBox
而是添加一个标签来存储来自计时器的数据(可能还有用户将键入的数据),然后离开TextBox
只用于输入用户特定的值。是WinForms还是WPF?没问题,如果有类似问题,我会做什么。:)
_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