试图显示经过的时间,每次圈按钮是点击五个不同的标签xamarin

sirbozc5  于 2023-05-11  发布在  其他
关注(0)|答案(2)|浏览(102)

我试图用C#在Xamarin中做一个秒表。我点击开始,时间流逝。我点击lap finished,它保存了运行时间以显示Lap1。我再次单击lap finished,它会节省再次显示Lap1的时间,而不是显示Lap2。我想显示每圈时间的每个标签时,圈按钮点击。

private void lapButton_Clicked(object sender, EventArgs e)
    {

        TimeSpan ts = stopWatch.Elapsed;
        string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
        ts.Hours, ts.Minutes, ts.Seconds,
        ts.Milliseconds / 10);

        
        displayLaps1.Text = stopWatch.Elapsed.ToString();
        
        if ((displayLaps1.Text != "") && (displayLaps2.Text == ""))
        {
            displayLaps2.Text = stopWatch.Elapsed.ToString();
        }
        //else if ((displayLaps1.Text != "") && (displayLaps2.Text != ""))
        //{
        //    displayLaps3.Text = stopWatch.Elapsed.ToString();
        //}
        //else if ((displayLaps1.Text != "") && (displayLaps2.Text != "") && (displayLaps3.Text != ""))
        //{
        //    displayLaps4.Text = stopWatch.Elapsed.ToString();
        //}
        //else if (displayLaps4.Text != "")
        //{
        //    displayLaps5.Text = stopWatch.Elapsed.ToString();
        //}

    }
f0ofjuux

f0ofjuux1#

你可以这样做

var labels = new []{displayLaps1, displayLaps2, displayLaps3, displayLaps4}
var firstEmptyLabel= labels.FirstOrDefault(l => string.IsNullOrWhiteSpace(l.Text));
if(firstEmptyLabel!= null){
    firstEmptyLabel.Text = elapsedTime;
}

请注意,如果您希望能够重置,则需要一个清除按钮或其他方法来清除标签。
我也会考虑在列表中添加时间并在UI中显示。这样你就可以保持任何你想要的圈数。

tvz2xvvm

tvz2xvvm2#

我会用圈数器代替

int lap = 0;

private void lapButton_Clicked(object sender, EventArgs e)
    {
        lap++;

        TimeSpan ts = stopWatch.Elapsed;
        string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
        ts.Hours, ts.Minutes, ts.Seconds,
        ts.Milliseconds / 10);

        switch(lap)
        {
           case 1:
             displayLaps1.Text = stopWatch.Elapsed.ToString();
             break;
           case 2:
             displayLaps2.Text = stopWatch.Elapsed.ToString();
             break;
           ...
        }
    }

相关问题