2014-12-11 105 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