这是我在最近的项目中所做的。
IsBusy属性是我在所有视图模型的基类中所拥有的。它是一个布尔值,如果一个视图想显示某种等待控件(如微调控件或其他),那么这个视图可以绑定到该布尔值上。
_retrieveData字段只是我在构建viewmodel时设置的一个Action。我这样做是因为viewmodel可能以几种不同的方式获取Cars列表 - 所以_retrieveData可能会根据所使用的构造函数在其中包含不同的代码。在_retrieveData获取数据后,它将设置私人支持者_cars与数据。因此,在完成_retrieveData之后,将public Cars设置为具有_cars中新数据的值会导致PropertyChangedEvent使视图知道自己进行更新。
所以效果是,当视图第一次获取数据时,它立即返回,但得到空值。然后几秒钟后,它获得实际数据。在那段时间里,用户界面很快响应。而且,如果用户界面想让用户知道它在后台工作,IsBusy也是如此。
不知道这是否是一种很好的方法来处理它,但它到目前为止一直在为我工作。
public List<Car> Cars
{
get
{
if (this._cars == null)
{
base.IsBusy = true;
// Start a background thread to get the data...
ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object nullObject)
{
this._retrieveData.Invoke();
this.Cars = this._cars;
base.IsBusy = false;
}));
// While waiting on the background thread, return null for now. When the background thread
// completes, the setter will raise OnPropertyChanged and the view will know its time to bind...
return this._cars;
}
return this._cars;
}
set
{
this._cars = value;
base.OnPropertyChanged("Cars");
}
}
传递一个回调函数,当搜索完成后,将更新视图。 – 2010-08-11 18:26:35