我第一次嘗試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