我尝试将 ObservableCollection 与 ListBox 相关联,但出现以下错误:应用程序调用了为不同线程编组的接口。( Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD)
)
Prueba.cs 在课堂上,我有:
public ObservableCollection<WidgetCollectionItem> WidgetsDownloaded(string e)
{
int alertas = 0;
XDocument document = XDocument.Parse(e);
// Obtener el id
//id = document.Root.Element("id").Value;
ObservableCollection<WidgetCollectionItem> Items = new ObservableCollection<WidgetCollectionItem>();
foreach (XElement wid in document.Root.Elements("widget"))
{
WidgetCollectionItem widget = new WidgetCollectionItem();
widget.captionWid = wid.Attribute("caption") != null ? wid.Attribute("caption").Value : null;
ObservableCollection<ServiciosWidgetCollectionItem> ItemsSer = new ObservableCollection<ServiciosWidgetCollectionItem>();
widget.ItemsSer = ItemsSer;
foreach (XElement service in wid.Elements("service"))
{
ServiciosWidgetCollectionItem ser = new ServiciosWidgetCollectionItem();
ser.captionWid = wid.Attribute("caption") != null ? wid.Attribute("caption").Value : null;
ser.nameWid = wid.Attribute("name") != null ? wid.Attribute("name").Value : null;
ser.nameSer = service.Attribute("name") != null ? service.Attribute("name").Value : null;
ser.captionSer = service.Attribute("caption") != null ? service.Attribute("caption").Value : null;
ser.descripcion = service.Attribute("desc") != null ? service.Attribute("desc").Value : null;
ser.valor = service.Element("xvalue") != null ? service.Element("xvalue").Value : null;
ser.color = service.Element("xcolor") != null ? service.Element("xcolor").Value : null;
ser.alerta = service.Element("xalert") != null ? service.Element("xalert").Value : null;
if (ser.alerta != null) { alertas++; }
ItemsSer.Add(ser);
}
Items.Add(widget);
}
return Items;
}
public class ServiciosWidgetCollectionItem
{
public string captionWid { get; set; }
public string captionSer { get; set; }
public string nameWid { get; set; }
public string nameSer { get; set; }
public string descripcion { get; set; }
public string valor { get; set; }
public string color { get; set; }
public string alerta { get; set; }
}
public class WidgetCollectionItem
{
public string captionWid { get; set; }
public ObservableCollection<ServiciosWidgetCollectionItem> ItemsSer { get; set; }
}
并从 MainPage 连接到页面,整个过程工作正常,但是当我插入 ListBox ItemsSouces 时出现错误:
public MainPage()
{
this.InitializeComponent();
Prueba prueba = new Prueba();
var request = (HttpWebRequest)WebRequest.Create(new Uri(ruta));
request.BeginGetResponse(r =>
{
var httpRequest = (HttpWebRequest)r.AsyncState;
var httpResponse = (HttpWebResponse)httpRequest.EndGetResponse(r);
using (var reader = new StreamReader(httpResponse.GetResponseStream()))
{
var response = reader.ReadToEnd();
widgetsList.ItemsSource = prueba.WidgetsDownloaded(response);
}
}, request);
}