So I have a stopwatch and a开发者_开发百科ll I want is for it to be display on a textblock. How can I do that?
Create a TimerViewModel, that looks something like this:
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));
}
}
}
Instantiate it like so in your code-behind:
public partial class TimerPage : UserControl
{
public TimerPage()
{
InitializeComponent();
timerViewModel = new TimerViewModel();
DataContext = timerViewModel;
}
private TimerViewModel timerViewModel;
}
And then bind it like this:
<Grid x:Name="LayoutRoot" Background="White">
<TextBlock Text="{Binding TimeFromStart}" />
</Grid>
Works like a charm. You'll need to modify the basic concept a bit I'm sure, but the basic idea of having a DispatcherTimer fire the PropertyChanged notification is what's key.
The TimerTextBlock is used to display the elapsed time in a TextBlock and updates the time elapsed after every second. I think you will have to modify it to act as a stop watch.
A Stopwatch is used for measurement between two points in time. It does not emit any kind of event that might drive a binding. You need to use some sort of Timer (the link assumes WPF... other options are available... update your tags) in your model to create change notifications.
精彩评论