在我的WPF C#项目中使用来自DB(Sqlite)的数据填充DataGrid时遇到问题。
我已使用Name(dataGrid_Students)在我的XAML文件中定义了DataGrid:
<DataGrid Name="dataGrid_Students" Grid.Row="0" Grid.Column="0"
RenderOptions.ClearTypeHint="Enabled"
TextOptions.TextFormattingMode="Display"
CanUserAddRows="False"
CanUserDeleteRows="False"
SelectionUnit="FullRow"
AutoGenerateColumns="false"
>
<DataGrid.Columns>
<DataGridTextColumn Header="Index Number" />
<DataGridTextColumn Header="First Name" />
<DataGridTextColumn Header="Last Name" />
</DataGrid.Columns>
</DataGrid>
在我定义了DataGrid组件的Window的构造函数中的C#文件中,我调用了方法initDataGrid();
public StudentForm() {
InitializeComponent();
this.WindowStartupLocation = WindowStartupLocation.CenterScreen;
initDataGrid();
}
其中包含此代码:
private void initDataGrid() {
//dataGrid_Student.DataContext = dbManager.Students; does not work
dataGrid_Student.ItemsSource = dbManager.Students;
}
所以问题是我的DataGrid是空的。我已经检查过我的学生列表是否为空,但它不是,它包含所有数据。那么我为了用Data填充DataGrid还缺少什么?
更新
我的学生班:
[Table("student")]
class Student {
[Key] // this is a primary key in my table
[Column(name:"brind")]
public int Brind { get; set; }
[Column(name:"first_name")]
public string FirstName { get; set; }
[Column(name:"last_name")]
public string LastName { get; set; }
}
将我的属性从Student类绑定到此列:
<DataGrid Name="dataGrid_Student" Grid.Row="0" Grid.Column="0"
RenderOptions.ClearTypeHint="Enabled"
TextOptions.TextFormattingMode="Display"
CanUserAddRows="False"
CanUserDeleteRows="False"
SelectionUnit="FullRow"
AutoGenerateColumns="false"
>
<DataGrid.Columns>
<DataGridTextColumn Header="Index Number" Binding="{Binding Brind}" />
<DataGridTextColumn Header="First Name" Binding="{Binding FirstName}" />
<DataGridTextColumn Header="Last Name" Binding="{Binding LastName}" />
</DataGrid.Columns>
</DataGrid>
DataGrid仍为空。
我的dbManager实例是这个类:
class ManagerDBContext : DbContext {
public ManagerDBContext() : base("Student_DbContext") {
Database.SetInitializer<ManagerDBContext>(null);
}
public DbSet<User> Users { get; set; }
public DbSet<Student> Students { get; set; }
}
答案 0 :(得分:1)
您缺少列的绑定部分,因为您已将AutoGenerateColumns设置为false,
<DataGrid.Columns>
<DataGridTextColumn Header="Index Number" Binding="{Binding IndexNumber}" />
<DataGridTextColumn Header="First Name" Binding="{Binding FirstName}" />
<DataGridTextColumn Header="Last Name" Binding="{Binding LastName}" />
</DataGrid.Columns>
您还需要在绑定时转换为List
private void initDataGrid() {
//dataGrid_Student.DataContext = dbManager.Students; does not work
dataGrid_Student.ItemsSource = dbManager.Students.ToList();
}