だから私はストップウォッチを持っていて、それをテキストブロックに表示するだけです。どうやってやるの?
2700 次
3 に答える
4
次のような TimerViewModel を作成します。
public class TimerViewModel : INotifyPropertyChanged
{
public TimerViewModel()
{
timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(1);
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
startTime = DateTime.Now;
}
private DispatcherTimer timer;
private DateTime startTime;
public event PropertyChangedEventHandler PropertyChanged;
public TimeSpan TimeFromStart { get { return DateTime.Now - startTime; } }
private void timer_Tick(object sender, EventArgs e)
{
RaisePropertyChanged("TimeFromStart");
}
private void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
コード ビハインドで次のようにインスタンス化します。
public partial class TimerPage : UserControl
{
public TimerPage()
{
InitializeComponent();
timerViewModel = new TimerViewModel();
DataContext = timerViewModel;
}
private TimerViewModel timerViewModel;
}
そして、次のようにバインドします。
<Grid x:Name="LayoutRoot" Background="White">
<TextBlock Text="{Binding TimeFromStart}" />
</Grid>
魅力のように機能します。確かに基本的な概念を少し変更する必要がありますが、DispatcherTimer で PropertyChanged 通知を発生させるという基本的な考え方が重要です。
于 2011-02-14T04:56:28.877 に答える
1
TimerTextBlockは、経過時間をTextBlockに表示し、1秒ごとに経過時間を更新するために使用されます。ストップウォッチとして機能するように変更する必要があると思います。
于 2011-04-22T07:25:39.877 に答える