[英]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.