【问题标题】:Change Label content dynamically动态更改标签内容
【发布时间】:2011-09-21 19:51:02
【问题描述】:

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

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

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>

【问题讨论】:

    标签: c# wpf xaml data-binding


    【解决方案1】:

    这是我没有任何绑定的(经过测试并且有效):

    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);
    }
    

    【讨论】:

    • 我做了类似的事情,如你所见。但是,只要调用以下函数,程序就会终止。私人无效 updateTimerLabel(TimeSpan timeToGo) { lblTimer.Content = String.Format("{0:d2}:{1:d2}:{2:d2}", timeToGo.Hours, timeToGo.Minutes, timeToGo.Seconds); }
    • 但是我在一个空项目上尝试了你的代码,它工作正常。我现在可能会使用它。我仍然想知道我的问题是什么......
    • 所以问题出在下面写的定时器上。
    【解决方案2】:

    您确定您使用的是 DispatcherTimer 而不是 Timer?

    【讨论】:

    • 不,我没有使用 DispatcherTimer,我使用的是 System.Threading.Timer。我已经使用 DispatcherTimer 重做了我的代码,现在一切正常。有什么区别?
    • Timer 将使用主线程,DispatcherTimer 将使用 UIThread。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-25
    • 1970-01-01
    • 2017-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多