Reputation: 5944
I create WPF application with Entity Framework(code first) .I have this model
public class Person
{
public int Id {get; set;}
public string Name {get; set;}
public virtual Country Country {get ;set;}
}
public class Country
{
public int Id {get; set;}
public string Name {get; set;}
}
I want to display the information from Person in the DataGrid - name person and name country. Display the name of the country does not work. I have tried several options, this latest, but name of county not display.
<DataGrid name ="gridPerson" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn
Binding="{Binding Name}"
Header="Person Name" />
<DataGridComboBoxColumn
Header="CountryName"
SelectedItemBinding="{Binding County}"
SelectedValueBinding="{Binding Path=Id}"
SelectedValuePath="Name" />
</DataGrid.Columns>
</DataGrid>
code behind
private void Window_Loaded(object sender, RoutedEventArgs e)
{
personContext = new PersonContext();
personContext.Persons.Load();
personContext.Counties.Load();
gridPerson.ItemSource = personContext.Persons.local;
}
public class PersonContext : DbContext
{
public DbSet<Person> Persons { get; set; }
public DbSet<Country> Countries { get; set; }
}
How to display the name of the country from my model in the DataGridComboBoxColumn?
Upvotes: 2
Views: 2160
Reputation: 2947
There is a typo:
SelectedItemBinding="{Binding County}"
Should be:
SelectedItemBinding="{Binding Country}"
Watch for binding errors in the Output window!
Upvotes: 0
Reputation: 1122
You need to specify DisplayMemberPath
for the ComboBox.
<DataGrid name ="gridPerson" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Name}" Header="Person Name" />
<DataGridComboBoxColumn Header="CountryName" SelectedItemBinding="{Binding County}" SelectedValueBinding="{Binding Path=Id}" SelectedValuePath="Name" DisplayMemberPath="Name" />
</DataGrid.Columns>
</DataGrid
Upvotes: 1