如何在列表框上使用远程数据

时间:2012-03-18 12:21:24

标签: c# windows-phone-7

我正在使用Web服务,因此我在应用程序中添加了服务引用。 我需要在listBox上显示数据。为此我只写了下面的代码,但它没有工作,我一直收到一个错误。我的代码是

public Antocids()

    {

        InitializeComponent();

        ObservableCollection<Class1> p = new ObservableCollection<Class1>();
         ServiceReference3.ProductsClient client = new ServiceReference3.ProductsClient();
        client.getProdDetailsCompleted += new EventHandler<ServiceReference3.getProdDetailsCompletedEventArgs>(client_getProdDetailsCompleted);
        client.getProdDetailsAsync();
    }
    private void client_getProdDetailsCompleted(object sender, ServiceReference3.getProdDetailsCompletedEventArgs e)
    {
        ObservableCollection<Class1> p = e.Result; //here I'm getting the error

        listBox1.DataContext=p; 
    }

请告诉我确切的程序

1 个答案:

答案 0 :(得分:0)

我猜您的服务引用不会返回ObservableCollection<Class1>类型的结果。在这种情况下,将其视为没有任何意义。您应该做的是在收到结果时将元素添加到ObservableCollection:

ObservableCollection<Class1> p = new ObservableCollection<Class1>();
public Antocids()
{

    InitializeComponent();
    listBox1.DataContext=p; 

     ServiceReference3.ProductsClient client = new ServiceReference3.ProductsClient();
    client.getProdDetailsCompleted += new EventHandler<ServiceReference3.getProdDetailsCompletedEventArgs>(client_getProdDetailsCompleted);
    client.getProdDetailsAsync();
}
private void client_getProdDetailsCompleted(object sender, ServiceReference3.getProdDetailsCompletedEventArgs e)
{
    p.Clear(); // assuming you want to clear the data each time you get a new result 
    foreach(var result in e.Result)
      p.Add(result) // assuming that e.Result holds an IEnumerable of Class1. 
}

如果您的服务没有返回某种类型为Class1的集合,那么您需要手动将其解析为Class1,然后将其添加到可观察集合中。