动态更改标签内容

本文关键字:标签 动态 | 更新日期: 2023-09-27 18:09:08

首先,如果这听起来很愚蠢,我很抱歉,但我对WPF非常陌生。我正在做一个计时器,我想更改Label以显示剩余时间。我尝试过直接更改内容,并通过数据绑定到属性。当我执行前者时,程序会崩溃;至于后者,我真的不明白它是如何工作的,我环顾四周,我所能做的就是从网络上的代码片段中得到一些提示,但它不工作,因为我不知道我在做什么,我也不知道我在哪里出错。

代码:我在MainWindow类上放了很多东西,这不是很好的代码,但对于我的目的来说已经足够好了。当我尝试直接改变内容时,我通过设置一个由timer类调用的委托来实现,当被调用时这样做:

private void updateTimerLabel()
{
  lblTimer.Content = TimeToGo;
}

其中TimeToGo是以下属性:

public String TimeToGo
{ 
   get { return task.TimeToGo.Hours + ":" + 
                task.TimeToGo.Minutes + ":" + task.TimeToGo.Seconds; }            
}

对于绑定尝试,我设置了以下依赖属性:

public static readonly DependencyProperty TimeToGoProperty = DependencyProperty.Register(
          "TimeToGo", typeof(String), typeof(MainWindow));

,并在XAML文件中这样做:

<Window x:Class="ToDoTimer.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="ToDoTimer" Height="210" Width="348" 
        DataContext="{Binding RelativeSource={RelativeSource Self}}">    

    <Grid Width="326" Height="180">
        <Label Content="{Binding TimeToGoProperty}"  Height="63" HorizontalAlignment="Left" Margin="12,12,0,104" Name="lblTimer" VerticalAlignment="Center" FontSize="40" Width="218" FontFamily="Courier New" VerticalContentAlignment="Center" />
    </Grid>
</Window>

动态更改标签内容

这是我没有任何绑定(测试和它的工作):

DispatcherTimer timer = new DispatcherTimer();
DateTime endDate = new DateTime();
TimeSpan timeToGo = new TimeSpan(0, 1, 0);
public MainWindow()
{
    InitializeComponent();
    this.timer.Tick += new EventHandler(timer_Tick);
    this.timer.Interval = new TimeSpan(0, 0, 1);
    this.endDate = DateTime.Now.Add(timeToGo);
    this.timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
    this.lblTimer.Content = this.ToStringTimeSpan(this.endDate - DateTime.Now);
    if (this.endDate == DateTime.Now)
    {
        this.timer.Stop();
    }
}
string ToStringTimeSpan(TimeSpan time)
{
    return String.Format("{0:d2}:{1:d2}:{2:d2}", time.Hours, time.Minutes, time.Seconds);
}

你确定你正在使用DispatcherTimer而不是Timer吗?

相关文章: