如何使用外部 API 响应填充列表框?
我正在向 API 发出请求,我得到的唯一选项是异步获取响应
var r = (HttpWebRequest)WebRequest.Create(url);
r.BeginGetResponse(new AsyncCallback(ResponseMethod), state);
因此,我构建了获取数据所需的一切,并且它正在工作。但数据是在不同的线程中接收的。我的 ListBox 绑定到 MainViewModel
中存在的 StreamItems
。
public ObservableCollection<StreamItemViewModel> StreamItems { get; private set; }
但我位于不同的线程中,因此我无法直接访问此属性以向其添加新值。当我尝试:
StreamItems.Add(new StreamItemViewModel
{
Content = responseContent
});
我得到:
UnauthorizedAccessException - Invalid cross-thread access.
如何添加从请求中获得的值?
I am making a request to an API, the only option I get is async get response
var r = (HttpWebRequest)WebRequest.Create(url);
r.BeginGetResponse(new AsyncCallback(ResponseMethod), state);
So, I built everything I need to get the data, and it is working. But the data is received in a different thread. My ListBox is bound to StreamItems
that exists in my MainViewModel
.
public ObservableCollection<StreamItemViewModel> StreamItems { get; private set; }
But I am in a different thread, so I cannot directly access this property to add new values to it. When I try:
StreamItems.Add(new StreamItemViewModel
{
Content = responseContent
});
I get:
UnauthorizedAccessException - Invalid cross-thread access.
How can I add values that I got from the request?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您必须在 UI 线程上执行此操作 - 为此您可以使用
Dispatcher.BeginInvoke()
:You have to do this on the UI thread - for that you can use
Dispatcher.BeginInvoke()
: