如何绑定到数组中的子对象第一个元素?

时间:2016-01-23 10:22:41

标签: wpf xaml

我尝试将数组中的第一封电子邮件显示为DataGrid列中的用户电子邮件。

这就是我获取数据的方式:

IEnumerable<User> dgUsers;
dgUsers = Context.Users.Where(u => u.Location == "UK")
                .Include(j => j.Emails).ToList();

这是我的XAML:

<DataGrid x:Name="dataGrid" ItemsSource="{Binding dgUsers}"  HorizontalAlignment="Stretch" Margin="10,37,10,10" VerticalAlignment="Stretch" 
              CanUserAddRows="False" CanUserDeleteRows="False" IsReadOnly="True" AutoGenerateColumns="False">
        <DataGrid.Columns >
            <DataGridTextColumn Header="Name" Binding="{Binding Name}" />
            <DataGridTextColumn Header="Surname" Binding="{Binding Surname}" />
            <DataGridTextColumn Header="Location" Binding="{Binding Location}" />
            <DataGridTextColumn Header="Email" Binding="{Binding Emails[0].Email}" Width="350"  />
            <DataGridTextColumn Header="LastLogon" Binding="{Binding LastLogon}" />
        </DataGrid.Columns>

    </DataGrid>

用户类定义:

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public string Location { get; set; }
    public DateTime LastLogon { get; set; }
    public virtual ICollection<Mail> Emails { get; set; }
}
public class Mail
{
    public int Id { get; set; }
    public int UserId { get; set; }
    public string Email { get; set; }
}

不确定我做错了什么,网格显示但是电子邮件列是空的?

1 个答案:

答案 0 :(得分:1)

常见的方法是创建UserViewModel,将第一封电子邮件定义为属性。所以你的查询就像是。

IEnumerable<UserViewModel> dgUsers;
dgUsers = Context.Users.Where(u => u.Location == "UK")
                        .Include(j => j.Emails)
                        .Select(u => new UserViewModel() { /* some user properties */ Email = u.Emails.FirstOrDefault() }).ToList();

<强>更新

ICollection接口未声明索引器。因此,我建议您使用IList来解决您的问题。