在TextBlock中运行秒表

时间:2011-11-28 21:29:18

标签: c# wpf xaml binding

我正在尝试使用一个文本块来显示秒表的运行时间,但我不确定如何完成此操作。

我尝试使用绑定到秒表的已用方法,但这不会显示任何内容。

<TextBlock Grid.Row="1" Height="23" HorizontalAlignment="Right" Margin="0,0,398,0" Name="textBlockElapsed" Text="{Binding Path=watch.Elapsed, Mode=OneWay}" VerticalAlignment="Top" />

    Stopwatch watch = new Stopwatch();

3 个答案:

答案 0 :(得分:3)

尝试以下示例代码:MainWindow.xaml.cs

public partial class MainWindow : Window
{

    DispatcherTimer dt = new DispatcherTimer();
    Stopwatch stopWatch = new Stopwatch();
    string currentTime = string.Empty;
    public MainWindow()
    {
        InitializeComponent();
        SystemEvents.SessionEnding += new SessionEndingEventHandler(SystemEvents_SessionEnding);
        SystemEvents.SessionSwitch += new SessionSwitchEventHandler(SystemEvents_SessionSwitch);
        dt.Tick += new EventHandler(dt_Tick);
        dt.Interval = new TimeSpan(0, 0, 0, 0, 1);
    }

    void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
    {
        if (Environment.HasShutdownStarted)
        {
            MessageBox.Show("Total amount of time the system logged on:" + ClockTextBlock.Text);
        }

    }

    void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
    {
        switch (e.Reason)
        {
            // ...
            case SessionSwitchReason.SessionLock:
                if (stopWatch.IsRunning)
                    stopWatch.Stop();                    
                break;
            case SessionSwitchReason.SessionUnlock:
                stopWatch.Start();
                dt.Start();
                break;
            case SessionSwitchReason.SessionLogoff:
                MessageBox.Show("Total amount of time the system logged on:" + ClockTextBlock.Text);
                break;
            // ...
        }
    }

    void dt_Tick(object sender, EventArgs e)
    {
        if (stopWatch.IsRunning)
        {
            TimeSpan ts = stopWatch.Elapsed;
            currentTime = String.Format("{0:00}:{1:00}:{2:00}",
                ts.Hours, ts.Minutes, ts.Seconds);
            ClockTextBlock.Text = currentTime;
        }
    }
    private void StartButton_Click(object sender, RoutedEventArgs e)
    {
        stopWatch.Start();
        dt.Start();
    }

    private void StopButton_Click(object sender, RoutedEventArgs e)
    {
        if (stopWatch.IsRunning)
            stopWatch.Stop();
    }

    private void ResetButton_Click(object sender, RoutedEventArgs e)
    {
        stopWatch.Reset();
        stopWatch.Start();
    }
}

MainWindow.xaml:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition />            
        <ColumnDefinition />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="0.3*"/>
        <RowDefinition Height="0.2*"/>

    </Grid.RowDefinitions>
    <TextBlock Name="ClockTextBlock"
            TextAlignment="Center"
            VerticalAlignment="Center"
            FontSize="35" Foreground="Red"
            Grid.ColumnSpan="4"
            Grid.Row="0" />
    <Button Content="Start"
        Name="StartButton"
        Grid.Row="1"
        Grid.Column="0"
        Width="60" Height="35"
        Click="StartButton_Click" />        
    <Button Content="Stop"
        Name="StopButton"
        Grid.Row="1"
        Grid.Column="1"
        Width="60" Height="35"
        Click="StopButton_Click" />
    <Button Content="Reset"
        Name="ResetButton"
        Grid.Row="1"
        Grid.Column="3"
        Width="60" Height="35"
        Click="ResetButton_Click" />       
</Grid>

答案 1 :(得分:2)

Stopwatch没有Elapsed方法。它有一个Elapsed属性,但只有在查询时才会更新。

Lolo's answer显示了如何将Elapsed属性绑定到文本字段。如果您希望显示不断更新,则需要创建一个timer来触发该字段的更新。

答案 2 :(得分:1)

以下是完整示例。

MainWindow.xaml.cs:

public partial class MainWindow : Window, INotifyPropertyChanged
{
    public MainWindow()
    {
        this.Stopwatch = new Stopwatch();
        this.Stopwatch.Start();
        this._timer = new Timer(
            new TimerCallback((s) => this.FirePropertyChanged(this, new PropertyChangedEventArgs("Stopwatch"))),
            null, 1000, 1000);

        InitializeComponent();
    }

    private void FirePropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        if (this.PropertyChanged != null)
        {
            this.PropertyChanged(sender, e);
        }
    }

    private Timer _timer;

    public Stopwatch Stopwatch { get; set; }

    public event PropertyChangedEventHandler PropertyChanged;
}

MainWindow.xaml:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TextBlock Text="{Binding Path=Stopwatch.Elapsed, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
    </Grid>
</Window>