【问题标题】:Binding a DataGridTextColumn or DataGridTemplateColumn to a foreign key将 DataGridTextColumn 或 DataGridTemplateColumn 绑定到外键
【发布时间】:2013-12-18 08:20:11
【问题描述】:

我向Combobox 提出了类似的问题,并得到了很好的答案。现在,如果可能的话,我想将DataGridTextColumn 绑定到Foreign Key。否则我可以将DataGridTemplateColumn 绑定到Foreign Key。

为了证明我的问题,让我们看一个例子:

假设我有两张桌子:

客户

CustomerID
Name
Gender //ForeignKey

性别

GenderID
Value

我正在使用entity framework 自动生成我的Models。

现在我尝试如下绑定DataGridTemplateColumn:

<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding DataContext.Customers, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" 
          SelectedItem="{Binding SelectedPatient}" RowDetailsVisibilityMode="VisibleWhenSelected"
          IsReadOnly="True" SelectionMode="Single" SelectionUnit="FullRow" >
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Name}" Header="Patient Name" Width="25*" />
        <!--<DataGridTextColumn Binding="{Binding Gender}" Header="Gender" Width="10*" />-->
        <DataGridTemplateColumn Header="Gender" >
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <ItemsControl ItemsSource="{Binding ???}" >
                        <ItemsControl.ItemTemplate>
                            <DataTemplate>
                                <TextBlock Text="{Binding ???}"/>
                            </DataTemplate>
                        </ItemsControl.ItemTemplate>
                    </ItemsControl>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid>

但我不知道正确的绑定。

希望有人帮忙。

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

    {Binding Gender.Value}

    适用于您的模型

    public class YourViewModel
    {
        public List<Customer> Customers { get; set; }
        public Customer SelectedCustomer { get; set; }
    }
    
    public class Customer
    {
        public int CustomerID { get; set; }
        public string Name { get; set; }
        public Gender Gender { get; set; }
    }
    
    public class Gender
    {
        public int GenderID { get; set; }
        public string Value { get; set; }
    }
    

    ps。顺便说一句,性别标准化表太多了。你可以考虑使用check possible column value

    【讨论】:

    • 谢谢,这是一个非常简单的解决方案。
    • 以后遇到同样问题的用户,请将Patients和SelectedPatients改为Customers和SelectedCustomer。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-06
    • 2012-04-29
    • 1970-01-01
    • 1970-01-01
    • 2011-01-20
    • 1970-01-01
    相关资源
    最近更新 更多