[英]x:Bind does not work on button_click, works fine in MainPage()
[英]The timer works fine if it's coded inside a button_click event handler, but it doesn't work if it is inside a method
我从网站上找到了计时器代码,并在我的应用程序中使用了它,如果我在button_click处理程序中使用计时器代码,它可以很好地工作,但是我在调用方法时需要使用计时器,所以我确实复制并粘贴了该计时器代码将来自button_click的代码添加到方法中,但计时器始终使我为零。 我如何解决它?
以下是计时器代码。
public partial class Form1 : Form
{
//Timer decleration
DateTime startTime, StopTime;
TimeSpan stoppedTime;
bool reset;
bool startVariabl = true;
// The rest of the code..
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
if (startVariable) startMethod();
//
//The rest of the code...
}
private void startMethod()
{
//Timer
tmDisplay.Enabled = true;
// Reset display to zero
reset = true;
lblElapsed.Text = "00:00.00.0";
// Start timer and get starting time
if (reset)
{
reset = false;
startTime = DateTime.Now;
stoppedTime = new TimeSpan(0);
}
else
{
stoppedTime += DateTime.Now - StopTime;
}
}
private void tmDisplay_Tick(object sender, EventArgs e)
{
DateTime currentTime;
//Determine Ellapsed Time
currentTime = DateTime.Now;
// Display Time
lblElapsed.Text = HMS(currentTime - startTime - stoppedTime);
}
private string HMS(TimeSpan tms)
{
//Format time as string; leaving off last six decimal places.
string s = tms.ToString();
return (s.Substring(0, s.Length - 6));
}
我是新的C#学习者。
如注释中建议的keyboardP所示,您应该添加以下行:
tmDisplay.Tick += new EventHandler(tmDisplay_Tick);
通常,滴答处理程序会设置一次(除非您出于某种原因需要将其切换到其他回调或使其无效),所以我会假设您已经创建了计时器,或者在计时器初始化后(如果您通过某种方法进行了设置),则将其添加到您的Form构造函数中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.