【发布时间】:2011-05-10 12:49:09
【问题描述】:
我正在尝试使用我的 silverlight 应用程序调用 wcf 服务,但我在理解模型如何将结果返回给视图模型时遇到了一些麻烦。在我的视图模型中,我有以下命令:
public DelegateCommand GetSearchResultCommand
{
get
{
if (this._getSearchResultCommand == null)
this._getSearchResultCommand = new DelegateCommand(GetSearchResultCommandExecute, CanGetSearchResultsCommandExecute);
return this._getSearchResultCommand;
}
}
private void GetSearchResultCommandExecute(object parameter)
{
this.SearchResults = this._DataModel.GetSearchResults(this.SearchTerm);
}
/// <summary>
/// Bindable property for SearchResults
/// </summary>
public ObservableCollection<QueryResponse> SearchResults
{
get
{
return this._SearchResults;
}
private set
{
if (this._SearchResults == value)
return;
// Set the new value and notify
this._SearchResults = value;
this.NotifyPropertyChanged("SearchResults");
}
}
然后在我的模型中我有以下代码
public ObservableCollection<QueryResponse> GetSearchResults(string searchQuery)
{
//return type cannot be void needs to be a collection
SearchClient sc = new SearchClient();
//******
//TODO: stubbed in placeholder for Endpoint Address used to retreive proxy address at runtime
// sc.Endpoint.Address = (clientProxy);
//******
sc.QueryCompleted += new EventHandler<QueryCompletedEventArgs>(sc_QueryCompleted);
sc.QueryAsync(new Query { QueryText = searchQuery });
return LastSearchResults;
}
void sc_QueryCompleted(object sender, QueryCompletedEventArgs e)
{
ObservableCollection<QueryResponse> results = new ObservableCollection<QueryResponse>();
results.Add(e.Result);
this.LastSearchResults = results;
}
当我在模型中插入断点时,我看到查询正在执行的位置并在模型中返回结果(this.LastSearchResults = results)但是我似乎无法让这个集合更新/通知视图模型结果。我只使用一个方法和虚拟类生成并运行了一个类似的测试,它似乎可以工作,所以我怀疑问题是由于异步调用/线程造成的。我在 ViewModel 中有 INotifyPropertyChanged 来同步 View 和 ViewModel。我还需要在模型中实现 INotifyPropChng 吗?我是 mvvm 的新手,所以任何关于我应该如何解决这个问题的帮助/示例都将不胜感激。
谢谢,
更新 在进一步的测试中,我将 INotifyPropertyChanged 添加到模型中,并将 Completed 事件更改如下:
void sc_QueryCompleted(object sender, QueryCompletedEventArgs e)
{
ObservableCollection<QueryResponse> results = new ObservableCollection<QueryResponse>();
results.Add(e.Result);
//this.LastSearchResults = results;
SearchResults = results;
}
关注搜索结果我现在看到它已根据 WCF 的结果进行了更新。我的问题仍然存在,这是正确的方法吗?它现在似乎可以工作,但是我很好奇我是否遗漏了其他东西,或者我是否不应该将 INotify 放在模型中。
谢谢,
【问题讨论】:
标签: silverlight mvvm c#-4.0