Khushi
Khushi

Reputation: 1051

Binding a DataGridTextColumn or DataGridTemplateColumn to a foreign key

I have asked a similar question for Combobox and got a nice answer. Now I ant to bind a DataGridTextColumn to a Foreign Key if possible. Otherwise it would be OK for me to bind a DataGridTemplateColumn to the Foreign Key.

To demonstrate my problem let's have a look at an example :

Suppose I have two tables:

Cusstomer

CustomerID
Name
Gender //ForeignKey

Gender

GenderID
Value

I am using entity framework to auto-generate my Models.

Now I have tried to bind DataGridTemplateColumn as follows:

<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>

But I dont know the correct bindings.

Hope Someone helps.

Upvotes: 0

Views: 682

Answers (1)

aifarfa
aifarfa

Reputation: 3939

{Binding Gender.Value}

for your models

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. btw normalize table for gender is too much. You may consider using check possible column value

Upvotes: 1

Related Questions