2014-01-17 77 views
0

我正在WPF應用程序, 我必須從谷歌API獲取picasa相冊並綁定到WPF列表視圖。我不得不綁定到2列表視圖和使用Dispatcher.Invoke()。調度程序在一個委託中調用多重控制?

下面的代碼片段:

private void BindPicasa() 
    { 
     //My custom Google helper class. 
     GoogleClass google = new GoogleClass(); 

     ThreadStart start = delegate() 
     { 
      Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, 
       new Action(delegate() 
       { 
        //Fetch the album list 
        List<AlbumClass.Album> album = google.RequestAlbum(GoogleID); 

        //bind to a 1st listview in text title. 
        ListLeftAlbum.DataContext = album; 

        //bind to a 2nd listview in thumbnail preview. 
        ListMainAlbum.Visibility = System.Windows.Visibility.Visible; 
        ListMainAlbum.DataContext = album; 
       })); 
     }; 
     new Thread(start).Start(); 
    } 

的UI會凍結在啓動時, 但是,如果我拿出每個列表視圖,並與自己的調度運行,它是好的,負責用戶界面,但它似乎沒有優雅的方式來這樣做。 任何推薦?謝謝!

private void BindPicasa() 
    { 
     //My custom Google helper class. 
     GoogleClass google = new GoogleClass(); 

     ThreadStart start = delegate() 
     { 
      Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, 
       new Action(delegate() 
       { 
        //Fetch the album list 
        List<AlbumClass.Album> album = google.RequestAlbum(GoogleID); 
       })); 
      ListLeftAlbum.Dispatcher.Invoke(DispatcherPriority.Normal, 
       new Action(delegate() 
       { 
        //bind to a 1st listview in text title. 
        ListLeftAlbum.DataContext = album; 
       })); 
      ListMainAlbum.Dispatcher.Invoke(DispatcherPriority.Normal, 
       new Action(delegate() 
       { 
        //bind to a 2nd listview in thumbnail preview. 
        ListMainAlbum.Visibility = System.Windows.Visibility.Visible; 
        ListMainAlbum.DataContext = album; 
       })); 
     }; 
     new Thread(start).Start(); 
    } 
+1

的伎倆在後臺線程的專輯是你做的冗長的操作('google.RequestAlbum')在調用Dispatcher.Invoke之前在後臺調用。否則,你甚至不需要後臺線程。 – Clemens

+0

實際上你並沒有使用'Thread',這就是爲什麼UI會變得毫無意義 –

回答

1

您的第一個版本是差不多吧,你只需要而不是取調度請求回UI線程

private void BindPicasa() 
{ 
    //My custom Google helper class. 
    GoogleClass google = new GoogleClass(); 

    ThreadStart start = delegate() 
    { 
     //Fetch the album list 
     List<AlbumClass.Album> album = google.RequestAlbum(GoogleID); 

     Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, 
      new Action(delegate() 
      { 
       //bind to a 1st listview in text title. 
       ListLeftAlbum.DataContext = album; 

       //bind to a 2nd listview in thumbnail preview. 
       ListMainAlbum.Visibility = System.Windows.Visibility.Visible; 
       ListMainAlbum.DataContext = album; 
      })); 
    }; 
    new Thread(start).Start(); 
} 
相關問題