gpt4 book ai didi

c# - 如何在 TextBlock 中显示变化的时间?

转载 作者:太空宇宙 更新时间:2023-11-03 20:36:09 25 4
gpt4 key购买 nike

所以我有一个秒表,我只想将它显示在文本 block 上。我该怎么做?

最佳答案

创建一个 TimerViewModel,看起来像这样:

public class TimerViewModel : INotifyPropertyChanged
{
public TimerViewModel()
{
timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(1);
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
startTime = DateTime.Now;
}

private DispatcherTimer timer;
private DateTime startTime;
public event PropertyChangedEventHandler PropertyChanged;
public TimeSpan TimeFromStart { get { return DateTime.Now - startTime; } }

private void timer_Tick(object sender, EventArgs e)
{
RaisePropertyChanged("TimeFromStart");
}

private void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}

在您的代码隐藏中像这样实例化它:

public partial class TimerPage : UserControl
{
public TimerPage()
{
InitializeComponent();
timerViewModel = new TimerViewModel();
DataContext = timerViewModel;
}

private TimerViewModel timerViewModel;
}

然后像这样绑定(bind)它:

<Grid x:Name="LayoutRoot" Background="White">
<TextBlock Text="{Binding TimeFromStart}" />
</Grid>

像魅力一样工作。我敢肯定,您需要稍微修改基本概念,但让 DispatcherTimer 触发 PropertyChanged 通知的基本思想才是关键。

关于c# - 如何在 TextBlock 中显示变化的时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4985330/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com