来自 WebService 的 LINQ 查询填充列表框

LINQ Query Filling Listbox From WebService

我编写了一个简单的 Web 服务,允许我插入我的 SQL 数据库(工作正常)并从我的 SQL 数据库检索信息(目前不工作)。我正在尝试将信息放入列表中,然后将该信息显示到通用 windows 应用程序的列表框中。这是我的登录名:

网络服务

  [OperationContract]
  List<TBL_My_Info> FindInfo(string uid);

  public List<TBL_My_Info> FindInfo(string uid)
    {
        DataClasses1DataContext context = new DataClasses1DataContext();
        var res = from r in context.TBL_My_Info where r.User_Name == uid select r;
        return res.ToList();
    }

通用网络应用程序

     private void btnView_Click(object sender, RoutedEventArgs e)
    {
        string s = txtNameFind.Text;
        this.Content = new Page1(s);
    }       

     public Page1(string s)
    {
        this.InitializeComponent();
        LoadData(s);          
    }

    private async void LoadData(string s)
    {
        var client = new ServiceReference1.Service1Client();
        var res = await client.FindMyInfoAsync(s);
        articleMyInfoListBox.ItemsSource = res;
    }

XAML

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <ListBox x:Name="articleMyInfoListBox"></ListBox>
</Grid>

我知道我需要 myListBox.ItemSource = res; 之类的东西,但 res 在 ItemSource 之后没有显示为选项。我已经使用 using myapp.ServiceReference1;.

引用了我的 Web 服务

所以简而言之,我要做的是用返回的信息列表填充列表框,知道信息来自网络服务....

如果我做错了,有更好的方法,请告诉我。我对 LINQ 的经验为零,但对 SQL 的经验却很丰富。所以当然,SQL 会更可取..

编辑

我目前正在我的列表框中返回这个

using InsertAppTest.ServiceReference1.TBL_My_Info;

为服务客户端生成的方法是异步的,并且是 Task 的 return 个实例,因此您需要正确地 await 它们才能真正获得 "res" return 值。尝试这样的事情:

private void btnView_Click(object sender, RoutedEventArgs e)
 {
     string s = txtNameFind.Text;
     this.Content = new Page1(s);
 }

public Page1(string s)
{
    this.InitializeComponent();
    LoadData(s);
}  

private async void LoadData(string s)
{
    var client = new ServiceReference1.Service1Client();
    var res = await client.FindInfoAsync(s);
    listBox.ItemsSource = res;
}

这应该可行,但可能有更好的方法来构建您的异步调用 - 我只是不太了解您要完成的任务。

编辑

您的 XAML 必须设置 DisplayMemberPath 属性 以便它知道要显示 TBL_My_Info 上的 属性。现在它可能只是在每个实例上执行 ToString()

如果 TBL_My_Info 看起来像这样:

public class TBL_My_Info
{
    public int Id { get; set; }
    public string Name { get; set; }
}

那么你的 XAML 应该是这样的:

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <ListBox x:Name="articleMyInfoListBox" DisplayMemberPath="Name"></ListBox>
</Grid>