0

I am facing the following scenario:

My application contains a lot of information (stored in classes), the user can search the information for specific words (similar to the file search in Windows).

Once the user hit the search button, the search should begin asynchronously and collect results in the background. The search process can take a long time. Let's say the class which handles the searching is called SearchService (SearchService.cs).

The user can open a results view while the search service is working which contains a datagrid of results that is required to be updated as more results are found.

So basically:

Service is collecting information asynchronously -> View Model should get the already existing results and should be notified of new results -> View with datagrid should be updated asynchronously

How should I implement this? Let's say the View Model exposes an ObservableCollection to the view, but how should that collection be updated from the service?

I am using Prism and MEF.

4

2 回答 2

0

在您Binding的结果对象中,设置这个额外的IsAsync属性:

"{Binding PropertyName, IsAsync=True}"

接下来,在您的视图模型中添加如下方法:

public object RunOnUiThread(Delegate method)
{
    return Dispatcher.Invoke(DispatcherPriority.Normal, method);
}

现在,您可以使用适合您需要的任何参数创建一个回调处理程序委托,并像这样异步调用您的服务:

Model.GetResultsAsync(GotResultsCallbackHandler);

该服务可以存储对回调处理程序的引用,并在有更多结果时调用它。再次在您的视图模型中,您可以获得这样的结果,确保您在 UI 线程上更新 UI:

RunOnUiThread((Action)delegate
{
    ResultsCollection.AddRange(results);
});

这是一种伪代码......如果你不明白,请询问。

于 2013-08-13T13:01:31.150 回答
0

您可以使用 Reactive Extensions (Rx) 来实现此目的。

您的服务可以公开一个返回IObservable收集结果的方法。然后,您的服务可以IObservable在结果被服务收集时发布结果。而且,您的 ViewModel 可以订阅它并在结果到达时IObservable更新ObservableCollectionIObservable

伪代码如下:

服务等级:

public class Service
{
    public IObservable<Result> GetResults()
    {
        //...
    }
}

视图模型类:

public class ViewModel
{
    public ViewModel(Service service)
    {
        service.GetResults().Subscribe(x => Results.Add(x));
    }

    public ObservableCollection<Result> Results { get; set; }
}

阅读有关 Rx 的链接

于 2013-08-13T13:17:40.267 回答