定时器实现的数据绑定

无法弄清楚为什么这个计时器没有显示信息。 计时器被assembly到TimeEntry中更新TextBlock的方法。 绑定似乎不起作用,我不明白如何正确地做到这一点。 我看过MSDN网站。 他们只给出了基础知识:还不够。

码:

TimeEntry.xaml.cs

public partial class TimeEntry : UserControl { public static readonly DependencyProperty timeSpentProperty = DependencyProperty.Register("timeSpent", typeof(TimeSpan), typeof(TimeEntry), new FrameworkPropertyMetadata(TimeSpan.Zero)); #region Properties public TimeSpan timeSpent { get { return (TimeSpan)GetValue(TimeEntry.timeSpentProperty); } set { SetValue(TimeEntry.timeSpentProperty, value); } } #endregion static TimeEntry() { } public TimeEntry(int id) { DataContext = this; this.InitializeComponent(); //code } } 

TimeEntry.xaml

      

SessionManager.cs

  public class SessionManager : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; [NonSerialized] private Timer _timer; [NonSerialized] private Stopwatch _clockWatch; [NonSerialized] private DateTime _dtStartTime; private Session current_session; public string strStartTime { get { return _dtStartTime.ToString(); } private set { } } public SessionManager() { _clockWatch = new Stopwatch(); _timer = new Timer(1000);//one second _timer.Elapsed += clockWatch_Elapsed; _dtStartTime = DateTime.Now; CurrentSession = new Session(); } ///  /// Registered to Timer.Elapsed Event /// (See constructor) ///  public void clockWatch_Elapsed(object sender, ElapsedEventArgs e) { if (CurrentSession != null) { //update the timespent variable of the current timeEntry if (CurrentSession.currentTimeEntry != null) { CurrentSession.currentTimeEntry.timeSpent = _clockWatch.Elapsed; calculateTotalTime(); } } } private void OnPropertyChanged([CallerMemberName] string member_name = "") { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(member_name)); } } } 

你必须这样改变。 因为你做错了路。

  1. 想一想,哪个属性必须更新。 您想要的财产是timeSpent 。 然后,您的TimeEntry类必须实现INotifyPropertyChanged事件。

  2. timeSpent属性不需要依赖属性。 因为您在’elapsed’事件中手动分配它。

  3. 您的xaml必须与您的class级相关联。 换句话说,你的身体(xaml)必须有灵魂(类实例)。

  4. 您已在步骤3中绑定模型。现在您可以像这样简单绑定。

在此处输入图像描述 在此处输入图像描述

步骤2的说明。(依赖属性)

您当前的使用情况是manually assignment 。 在您的情况下,不需要依赖属性

在此处输入图像描述

如果您想使用如下图像,您的属性timeSpent必须具有依赖属性。

在此处输入图像描述