如何在WPF DataBinding中处理Linq to SQL Foreign Key关系

时间:2010-01-11 21:04:58

标签: c# wpf linq-to-sql data-binding

我一直在争论这个问题,所以今天我开始了一个新项目并简化了基础知识。我想要做的是有一个列表框,绑定到一个集合,其中包含所示项目的详细视图,如下所示。一切正常,除了引用其他表的项只显示外键。我能够通过linq查询来解决这个问题,但我意识到我使用的方法是hackish。

public partial class Window1 : Window
{
    DataClasses1DataContext db = new DataClasses1DataContext();
    public IEnumerable<Issue> issues = null;

    public Window1()
    {
        InitializeComponent();
        issues = from i in db.Issues
                 select i;
        this.DataContext = issues;
    }

    // The hacked in query that correctly displays the name instead of Key
    private void IssueListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        List<Issue> _issues = issues.ToList();
        int empl = _issues[IssueListBox.SelectedIndex].IssOwner;

        OwnerTextBlock.Text = (from emp in db.Employees
                              where emp.EmpID == empl
                              select emp.EmpFirstName.ToString() + " " + 
                                       emp.EmpLastName.ToString()).Single();            
    }
}

Xaml就像我能做到的那样简单:

<Window.Resources>
    <DataTemplate x:Key="ShowIssueDetail">
        <TextBlock Text="{Binding Path=IssTitle}" FontWeight="Bold" FontSize="14"/>
    </DataTemplate>
</Window.Resources>

    <StackPanel>
    <TextBlock Text="Issues" FontWeight="Bold" />
    <ListBox x:Name="IssueListBox"
              ItemsSource="{Binding}"
              ItemTemplate="{StaticResource ShowIssueDetail}"
              IsSynchronizedWithCurrentItem="True"
              HorizontalContentAlignment="Stretch" SelectionChanged="IssueListBox_SelectionChanged">
    </ListBox>

    <TextBlock Text="{Binding Path=IssDescription}" />
    <TextBlock Text="{Binding Path=IssOwner}" /> <!--I want this to show the name, not the Key-->
    <TextBlock Name='OwnerTextBlock' /> <!--This has the name set in code from the Linq query and works-->
</StackPanel>

我该如何正确地做到这一点?

1 个答案:

答案 0 :(得分:1)

Linq2Sql ORM auto会根据模型中的关系生成表示相关记录的属性。在您的情况下,我猜想如果您将OwnerTextBlock的绑定更改为以下内容 - 您将得到您想要的内容:

<TextBlock Name="OwnerTextBlock" Text="{Binding Employee.FirstName}" /> 

(我只绑定FirstName,因为使用XAML合并名字和姓氏需要MultiBindingIMultiValueConverter实现 - 这超出了这个答案的范围:))

请记住,相关实体之间必须存在ORM关系才能生效。