2012-02-03 10 views
0

Windows Phone 7.5(mango)のデータベースアプリケーションを開発しています。私は(ボタンをタップしている間に) "検索中..."というテキストでテキストブロックを更新しようとしています。このボタンは大きなテーブルで時間のかかる検索を実行します。しかし、私が試みていることはすべて失敗です!ここで私が使用したコードスニペットの1つです。これを達成する方法はありますか?私が何が間違っているのか理解するのを助ける助けがあれば感謝しますタップ中にWindows phoneのテキストブロックを更新します。

private void btnSearch_Tap(object sender, GestureEventArgs e) 
{ 
    workerThread = new Thread(new ThreadStart(turnVisibilityOn)); 
    workerThread.Start(); 
    while (!workerThread.IsAlive) ; 
    Thread.Sleep(500); 

    //Search database takes about 15 sec on windows phone device! 
    Procedures[] results = CSDatabase.RunQuery<Procedures>(@"select Code, Description from tblLibraries where Description like '%" + 
    textBox1.Text + "%' or Code like '%" + textBox1.Text + "%'"); 

    this.MyListBox.ItemsSource = results; 

    // Of course this not work 
    Search1.Text = "" 

} 

private void turnVisibilityOn() 
{ 
    // Inform the user updating the Search1 textblock 
    // UIThread is a static class -Dispatcher.BeginInvoke(action)- 
    UIThread.Invoke(() => Search1.Text = "Searching..."); 

} 


public static class UIThread 
{ 
    private static readonly Dispatcher Dispatcher; 

     static UIThread() 
     { 
     // Store a reference to the current Dispatcher once per application 
     Dispatcher = Deployment.Current.Dispatcher; 
     } 

     /// <summary> 
     /// Invokes the given action on the UI thread - if the current thread is the UI thread this will just invoke the action directly on 
     /// the current thread so it can be safely called without the calling method being aware of which thread it is on. 
     /// </summary> 
    public static void Invoke(Action action) 
    { 
     if (Dispatcher.CheckAccess()) 
     action.Invoke(); 
     else 
     Dispatcher.BeginInvoke(action); 
    } 
} 

答えて

0

問題が正しく理解されているかどうかわかりません。 「検索中...」というテキストが表示されませんか? The

// Of course this not work 
Search1.Text = "" 

回線が動作しません。 (なぜ「これはうまくいかないのですか?」)なぜ、それはうまくいかないのですか?

なぜバックグラウンドスレッドでテキストを "Searching ..."に変更するのか分かりません。あなたはいつものUI要素を操作する必要が

private void btnSearch_Tap(object sender, GestureEventArgs e) 
{ 
    Search1.Text = "Searching..." 

    ThreadPool.QueueUserWorkItem(p => 
    { 
     Procedures[] results = CSDatabase.RunQuery<Procedures>(@"select Code, Description from tblLibraries where Description like '%" + 
     textBox1.Text + "%' or Code like '%" + textBox1.Text + "%'"); 

     // Dispatch manipulation of UI elements: 
     Dispatcher.BeginInvoke(() => 
     { 
      this.MyListBox.ItemsSource = results; 
      Search1.Text = ""; 
     }); 
    }) ; 
} 

:あなたは、UIスレッドでそれを行うと、バックグラウンドスレッドで時間のかかる作業を作ることができ、このようなものは、(私はThreadPoolのを使用してに切り替え) UIスレッド(イベントハンドラが実行されるスレッド)で、時間のかかる作業をバックグラウンドスレッドで行う必要があります。

+0

はい、この方法が優れています。 – Nikolas

関連する問題