开发者

return result from async operation in mvvm

I have a viewModel named CarsList with main property

 public ObservableCollection<Car> Cars
        {
            get
            {
                if (_cars.Count == 0)
                {
                    IsBusy = true;
                    _ws.GetCarsCompleted += new EventHandler<GetCarsCompletedEventArgs>(GetCarsCompleted);
                    _ws.GetCarsAsync(_app.HandlerId);
                }
                return _cars;
            }
            set
            {
                if (_cars != value)
                {
                    if (_cars != null)
                    {
                        Unsubscribe(_cars);
                    }

                开发者_JAVA百科    _cars = value;

                    if (_cars != null)
                    {
                        Subscribe(_cars);
                    }

                    RaisePropertyChanged("Cars");
                }
            }
        }

        private void GetCarsCompleted(object sender, GetCarsCompletedEventArgs e)
        {
            //_cars = e.Result;
            IsBusy = false;
        }

When view gets _cars and the list is empty I must wait to get collection of cars from wcf service, and there is a problem because it is async operation.

Or maybe if list is empty I should return null, and fire async operation, and in asynccompleted set _cars to result from the wcf service?


I can only guess that you are trying to set up a view binding and property change notification. If I am right I would change you code as follows:

public void GetCars(Int32 handlerId)
{
  _ws.GetCarsCompleted += new EventHandler<GetCarsCompletedEventArgs>GetCarsCompleted);  
   IsBusy = true; 
   _ws.GetCarsAsync(handlerId); 
}

public ObservableCollection<Car> Cars
{
get
{
 return _cars;
}
set
{
 if (_cars != value)
 {
  _cars = value; 
  RaisePropertyChanged("Cars");
 }
}

private void GetCarsCompleted(object sender, GetCarsCompletedEventArgs e)
{
   _ws.GetCarsCompleted -= new EventHandler<GetCarsCompletedEventArgs>GetCarsCompleted); 
   IsBusy = false;    

   if (e.Error != null)
   {
    //Error handler
   }
   else
   {
     Cars = e.Result;
   }
} 

And then the view binding (in the case of a DataGrid) would look something like this..

<DataGrid IsReadOnly="True"
          ItemsSource="{Binding Cars}"
          .........
          ........./>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜