【发布时间】:2011-03-23 13:57:19
【问题描述】:
我的 Silverlight MVVM 应用的 ViewModel 属性是从服务库(不是 WCF 服务)中填充的。
库方法执行一些可能需要一些时间才能完成的操作。操作完成后,返回值被赋给 ViewModel 属性。
由于视图绑定到 ViewModel 属性,它会在属性值更改时自动刷新。但是,在预期的操作过程中,UI 变得无响应,因为它的同步操作。
如何异步执行以下操作?
服务合同与实施:
public class ItemsLoadedEventArgs : EventArgs
{
public List<string> Items { get; set; }
}
public interface ISomeService
{
event EventHandler<ItemsLoadedEventArgs> GetItemsCompleted;
void GetItemsAsync();
}
public class SomeService : ISomeService
{
public event EventHandler<ItemsLoadedEventArgs> GetItemsCompleted;
public void GetItemsAsync()
{
// do something long here
// how to do this long running operation Asynchronously?
// and then notify the subscriber of the Event?
// when the operation is completed fire the event
if(this.GetItemsCompleted != null)
{
this.GetItemsCompleted(this, new ItemsLoadedEventArgs { Items = resulthere });
}
}
}
视图模型:
public class HomeViewModel : ViewModel
{
private ISomeService service;
private ObservableCollection<string> _items;
// Items property is bound to UI
public ObservableCollection<string> Items
{
get { return this._items; }
set
{
this._items = value;
this.RaisePropertyChanged(() => this.Items);
}
}
// DI
public HomeViewModel(ISomeService service)
{
...
this.service = service;
// load items
this.LoadItems();
}
private void LoadItems()
{
this.service.GetItemsCompleted += (s, ea) =>
{
this.Items = new ObservableCollection<string>(ea.Items);
};
this.service.GetItemsAsync();
}
}
问题:
由于数据是在构造函数中加载的,并且操作是同步的,所以 UI 没有响应。
如何异步执行SomeService类的GetItemsAsync方法内部的操作?
【问题讨论】:
标签: silverlight design-patterns silverlight-4.0 asynchronous