将DataGridComboBoxColumn与模型绑定

时间:2013-07-30 07:49:27

标签: c# wpf data-binding datagridcomboboxcolumn

我使用Entity Framework创建WPF应用程序(代码优先)。我有这个模型

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

我想显示DataGrid中Person的信息 - 名称person和name country。显示国家名称不起作用。我已经尝试了几个选项,这是最新的,但是县名不显示。

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

背后的代码

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

如何在DataGridComboBoxColumn中显示我的模型中的国家/地区名称?

2 个答案:

答案 0 :(得分:1)

您需要为ComboBox指定DisplayMemberPath

<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

答案 1 :(得分:0)

有一个拼写错误:

SelectedItemBinding="{Binding County}"

应该是:

SelectedItemBinding="{Binding Country}"

在“输出”窗口中查看绑定错误!