繁体   English   中英

如何改进WPF倒数计时器的时间格式

[英]How to improve time format of a WPF Countdown timer

我在这里有一个倒数计时器,是否有任何改进它使它看起来更好的时间显示01:09而不是1:9在显示和00:09而不是00:9下面是代码。我需要关于如何做的一些指导。

private int time = 120;
private System.Windows.Threading.DispatcherTimer Timer;

public MainWindow()
{
    InitializeComponent();
    Timer = new System.Windows.Threading.DispatcherTimer();
    Timer.Interval = new TimeSpan(0, 0, 1);
    Timer.Tick += Timer_tick;
    Timer.Start();

}


void Timer_tick(object sender, EventArgs e)
{
    if (time > 0)
    {
    if (time <= 10)
    {
        if (time % 2 == 0)
        {
            tbTime.Foreground = Brushes.Red;
        }
        else
        {
            tbTime.Foreground = Brushes.White;
        }


        time--;

        tbTime.Text = string.Format("00:0{0}:0{1}", time / 60, time % 60);

    }

    else
    {
        time--;
        tbTime.Text = string.Format("00:0{0}:{1}", time / 60, time % 60);


    }

    }
    else
    {
    Timer.Stop();
    }
}

如果您使用DateTime来表示“时间”,您可以轻松地显示它

time.ToString("hh:mm");

如果你坚持使用整数,你可以使用它:

string.Format("00:{0:00}:{1:00}", time / 60, time % 60);

或者按照伊恩的回答使用“d2”

string.Format("00:{0:d2}:{1:d2}", time / 60, time % 60);

您可能希望纯粹在xaml上处理格式并在viewmodel中使用timepan而不是datetime,从viewmodel绑定画笔可能也不错,除非您想使用带值转换器的触发器来检查TotalSeconds是偶数还是奇。

<TextBlock Width="100" Height="24" ForeGround={Binding ForeBrush}>
    <TextBlock.Text>
        <MultiBinding StringFormat="{}{0:00}:{1:00;00}">
            <Binding Path="MyTimeSpan.Minutes"/>
            <Binding Path="MyTimeSpan.Seconds"/>
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM