2017-01-01 117 views
2

我想在我的应用程序中显示一个倒数计时器,显示持续时间,直到某个NodaTime.Instant。为此,我有如下设计:在wpf中显示剩余时间

public class Event 
{ 
    private Instant EventStartTime; 
    public Duration TimeLeft { get { return EventStartTime - SystemClock.Instance.Now; } } 
} 

但是当我现在证明它像这样在我看来:

<Label Content="{Binding Event.TimeLeft}" /> 

这并不动态更新。我知道解决方案,我开始计时器来持续触发PropertyChangedEvents,但在这种情况下这看起来有点过分。

有没有干净的方式始终显示给用户留下正确的时间?

回答

0

你需要,只要你想要的标签,以获得更新要么提高PropertyChanged事件的的timeleft财产。这需要Event类来实现INotifyPropertyChanged事件。

另一个选择是明确的更新使用BindingExpression的结合。然后,您可以使用调用的BindingExpression每x秒UpdateTarget()方法DispatcherTimer:

public MainWindow() 
{ 
    InitializeComponent(); 

    System.Windows.Threading.DispatcherTimer timer = new System.Windows.Threading.DispatcherTimer(); 
    timer.Interval = TimeSpan.FromSeconds(1); 
    timer.Tick += (s, e) => 
    { 
     var be = theLabel.GetBindingExpression(Label.ContentProperty); 
     if (be != null) 
      be.UpdateTarget(); 
    }; 
    timer.Start(); 
} 

<Label x:Name="theLabel" Content="{Binding Event.TimeLeft}" /> 

没有刷新数据在WPF结合清洁的方式。

1

WPF依赖于通知它当一个属性的变化,两个是依赖属性或INotifyPropertyChanged的事件的机制。

在您的示例中,通过绑定将Content属性设置为初始值。然而,由于结合从不通知属性值发生了变化,它永远不会更新。

因此,与PropertyChanged事件的计时器解决方案可能是最好的选择。