2014-12-11 104 views
3

我刚刚开始使用Windows Store应用程序开发,我只是想要一个非常简单的应用程序:几乎是一个从左到右填充的progres栏,但即使这个任务显然不适合我。DispatcherTimer不会触发

我有以下代码:

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应用商店应用时,是否需要特别注意特殊情况?我看上去很高,很遗憾在这件事上没有发现任何东西。

回答

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(); 
} 

您设置TimeSpanas 100 seconds。您需要使用五参数重载来获得毫秒。但恕我直言,它更简单,更易于使用FromMilliseconds()方法(如上所述)。

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

+0

谢谢,从我的WPF复制代码时,两个拼写错误,我没有注意到他们中的任何一个xD。非常感谢您帮助我解决这个问题! – 2014-12-11 01:42:30