DispatcherTimer不会触发

时间:2014-12-11 01:17:00

标签: c# .net windows-store-apps

我刚刚开始使用Windows应用商店应用程序开发,我只想要一个非常简单的应用程序:几乎是一个从左到右填充的进度条,但即使是这项任务显然也不适合我。

我有以下代码:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace TimeLoader
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        private DispatcherTimer refreshTimer;

        public MainPage()
        {
            this.InitializeComponent();
        }

        void refreshTimer_Tick(object sender, object e)
        {
            TimePassedBar.Value += 5;
        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            TimePassedBar.Value = 50;
            new DispatcherTimer();
            this.refreshTimer = new DispatcherTimer();
            this.refreshTimer.Interval = new TimeSpan(0, 0, 0, 100);
            this.refreshTimer.Tick += refreshTimer_Tick;
            this.refreshTimer.Start();
        }
    }
}

<Page
    x:Class="TimeLoader.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:TimeLoader"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" Loaded="Page_Loaded">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Grid.RowDefinitions>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <ProgressBar Grid.Row="0" Grid.Column="0" Height="150" Value="75" VerticalAlignment="Center" Name="TimePassedBar"/>
    </Grid>
</Page>

现在,当我在WPF中执行此操作时,相同的安装程序工作正常,但是当我启动构建为Windows商店应用程序的代码时,Tick事件永远不会触发。在构建Windows应用商店应用时,是否需要特别注意?我看起来很高低,很遗憾没有发现这件事。

1 个答案:

答案 0 :(得分:4)

您的代码运行正常。你没等多久就注意到了。 :)

private void Page_Loaded(object sender, RoutedEventArgs e)
{
    TimePassedBar.Value = 50;
    this.refreshTimer = new DispatcherTimer();
    this.refreshTimer.Interval = TimeSpan.FromMilliseconds(100);
    this.refreshTimer.Tick += refreshTimer_Tick;
    this.refreshTimer.Start();
}

您正在设置TimeSpan as 100 seconds。您需要使用五参数重载来获得毫秒。但恕我直言,使用FromMilliseconds()方法(如上所述)更容易,更易读。

此外,您不需要两次创建DispatcherTimer对象,尤其是当您要完全忽略第一个对象时。 :)