我第一次尝试Windows Phone 7开发。我决定尝试从Expression Blend 4中的默认示例移植一个Silverlight Timer示例。完整Silverlight的定时器示例将TimerModel类绑定到定时器,启动/停止切换开关等。我已经想出了如何创建数据源/数据上下文并将属性绑定到屏幕上的东西。但是,Reset()方法(它是一个void)不会显示在Windows Phone 7应用程序的可绑定选项中。它们都是完全相同的类,但由于某种原因,void方法不可绑定。有什么我需要启用的是完全的Silverlight应用程序,而不是Windows Phone 7?有什么特别的东西使得一个类的属性或方法在数据源时是可绑定的?这仅仅是Windows Phone 7的Silverlight功能子集的限制之一吗?将Windows Phone 7按钮的动作绑定到Expression Blend中的方法4
下面是这个类,它在两个应用程序中都是相同的。我想将按钮的点击绑定到Reset()方法。
namespace Time
{
using System;
using System.ComponentModel;
using System.Windows.Threading;
using System.Windows.Data;
public class TimerModel : INotifyPropertyChanged
{
private bool isRunning;
private DispatcherTimer timer;
private TimeSpan time;
private DateTime lastTick;
public string FormattedTime
{
get
{
return string.Format("{0:#0}:{1:00}:{2:00.00}", this.time.Hours, this.time.Minutes, (this.time.Seconds + (this.time.Milliseconds/1000.0d)));
}
}
private void UpdateTimes()
{
this.NotifyPropertyChanged("FormattedTime");
this.NotifyPropertyChanged("Hours");
this.NotifyPropertyChanged("Minutes");
this.NotifyPropertyChanged("Seconds");
}
public bool Increment
{
get;
set;
}
public int Hours
{
get
{
return this.time.Hours;
}
set
{
this.time = this.time.Add(TimeSpan.FromHours(value - this.time.Hours));
this.UpdateTimes();
}
}
public int Minutes
{
get
{
return this.time.Minutes;
}
set
{
this.time = this.time.Add(TimeSpan.FromMinutes(value - this.time.Minutes));
this.UpdateTimes();
}
}
public int Seconds
{
get
{
return this.time.Seconds;
}
set
{
this.time = this.time.Add(TimeSpan.FromSeconds(value - this.time.Seconds));
this.UpdateTimes();
}
}
public bool IsRunning
{
get { return this.isRunning; }
set
{
if (this.isRunning != value)
{
this.isRunning = value;
if (this.isRunning)
{
this.StartTimer();
}
else
{
this.StopTimer();
}
this.NotifyPropertyChanged("IsRunning");
}
}
}
private void StartTimer()
{
if (this.timer != null)
{
this.StopTimer();
}
this.timer = new DispatcherTimer();
this.timer.Interval = TimeSpan.FromMilliseconds(1);
this.timer.Tick += this.OnTimerTick;
this.lastTick = DateTime.Now;
this.timer.Start();
}
private void StopTimer()
{
if (this.timer != null)
{
this.timer.Stop();
this.timer = null;
}
}
private void OnTimerTick(object sender, EventArgs e)
{
DateTime now = DateTime.Now;
TimeSpan diff = now - this.lastTick;
this.lastTick = now;
if (this.Increment)
{
this.time = this.time.Add(diff);
}
else
{
this.time = this.time.Subtract(diff);
}
if (this.time.TotalMilliseconds <= 0)
{
this.time = TimeSpan.FromMilliseconds(0);
this.IsRunning = false;
}
this.UpdateTimes();
}
public void Reset()
{
this.time = new TimeSpan();
this.UpdateTimes();
}
public TimerModel()
{
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
不错!我最近听说过很多关于Caliburn框架的内容,但还没有研究过它。看起来现在是个好时机。谢谢! – 2011-03-25 03:44:34