Silverlight UI Dispatcher - 正确实现

时间:2013-01-03 12:41:59

标签: silverlight-4.0 silverlight-5.0


我对使用Dispatcher有点困惑。我在xap中有5个网格,我试图将每个网格与来自WCF服务的数据绑定起来

void MainPage_Loaded(object sender, RoutedEventArgs e)
    {
        System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(GetData));
        //This is followed by getting data for other grids
    }

    private void GetData(object state)
    {
        Dispatcher.BeginInvoke(delegate()
          {
              WCFservice.ReadDataCompleted += new EventHandler<ReadDataCompletedEventArgs>(WCFservice_GetData);
              WCFservice.ReadDataAsync();
          });

    }

    void WCFservice_GetData(object sender, ReadDataCompletedEventArgs e)
    {
        //is this correct 
        myGrid.ItemsSource = myCollection;
        //OR should I use dispatcher here as well when I bind to the grid
        Deployment.Current.Dispatcher.BeginInvoke(() => { myGrid.ItemsSource = myCollection; }); 
    }

1 个答案:

答案 0 :(得分:0)

正确的实施如下

private void GetData(object state)
{
    //dont use dispatcher here
          WCFservice.ReadDataCompleted += new EventHandler<ReadDataCompletedEventArgs>(WCFservice_GetData);
          WCFservice.ReadDataAsync();


}

void WCFservice_GetData(object sender, ReadDataCompletedEventArgs e)
{
    //use dispatcher here 
    Deployment.Current.Dispatcher.BeginInvoke(() => { myGrid.ItemsSource = myCollection; }); 
}