【问题标题】:return result from async operation in mvvm从 mvvm 中的异步操作返回结果
【发布时间】:2011-09-08 16:27:06
【问题描述】:

我有一个名为 CarsList 的视图模型,其主要属性

 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 服务获取汽车集合,并且存在问题,因为它是异步操作。

或者如果列表为空,我应该返回 null,并触发异步操作,并在 asynccompleted 中设置 _cars 以从 wcf 服务产生结果?

【问题讨论】:

  • 不知道你在这里问什么。您似乎正在发出属性更改通知,因此当填充汽车集合时,您的视图绑定应自动得到通知。您面临的具体问题是什么?包括您的视图 xaml 的 sn-p 也会有所帮助。

标签: silverlight-4.0 asynchronous mvvm-light


【解决方案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}"
          .........
          ........./>

【讨论】:

  • 我不能回答你,因为我需要解决那个对象的另一个问题,但现在我和你有同样的想法:)
猜你喜欢
  • 2013-02-13
  • 1970-01-01
  • 2014-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-01
相关资源
最近更新 更多