从mvvm中的异步操作返回结果

时间:2011-09-08 07:51:59

标签: silverlight-4.0 asynchronous mvvm-light

我有一个名为CarsList的viewModel,主要属性为

 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);
                    }

                    _cars = value;

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

                    RaisePropertyChanged("Cars");
                }
            }
        }

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

当视图获得_cars并且列表为空时我必须等待从wcf服务获取汽车的集合,并且存在问题,因为它是异步操作。

或者如果list为空,我应该返回null,并且启动异步操作,并在asynccompleted set _cars中生成wcf服务?

1 个答案:

答案 0 :(得分:1)

我只能猜测您正在尝试设置视图绑定和属性更改通知。如果我是对的,我会按如下方式更改您的代码:

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;
   }
} 

然后视图绑定(在DataGrid的情况下)看起来像这样..

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