C# 动态更改标签内容

C# 动态更改标签内容,c#,wpf,xaml,data-binding,C#,Wpf,Xaml,Data Binding,首先,如果这听起来很愚蠢,我很抱歉,但我对WPF非常陌生。我正在做一个计时器,我想更改标签以显示剩余时间。我尝试过直接更改内容,并通过数据绑定到属性来更改内容。当我做前者时,程序就崩溃了;至于后者,我并不真正理解它是如何工作的,我环顾四周,我所能做的只是从网络上的代码片段中获取一些提示,但它不起作用,因为我不知道我在做什么,我也不知道我哪里出了错 代码:我在MainWindow类上放了很多东西,这不是很好的代码,但对于我的目的来说已经足够好了。当我尝试直接更改内容时,我通过设置timer类调用的

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

代码:我在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>

这是我没有任何绑定的产品(经过测试,可以正常工作):


您确定使用的是Dispatchermer而不是Timer吗?

正如您所看到的,我做了类似的操作。但是,只要调用以下函数,程序就会终止。private void updateTimerLabel(TimeSpan timeToGo){lblTimer.Content=String.Format(“{0:d2}:{1:d2}:{2:d2}”,timeToGo.Hours,timeToGo.Minutes,timeToGo.Seconds);}但是我在一个空项目上尝试了你的代码,效果很好。我现在可能会用它。我仍然想知道我的问题是什么…所以问题是下面写的计时器。不,我没有使用Dispatchermer,我使用的是System.Threading.Timer。我已经使用Dispatchermer重新编写了代码,现在一切都正常了。区别是什么?计时器将使用主线程,分派器将使用UIThread。
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);
}