我正在为我的项目使用MVVM,并且我正在尝试使用DataGrid将数据库中的表绑定。但是当我运行我的应用程序时,datagrid是空的。
MainWindow.xaml.cs:
public MainWindow(){
InitializeComponent();
DataContext = new LecturerListViewModel()
}
MainWindow.xaml:
<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Source=Lecturers}" >
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
<DataGridTextColumn Header="Surname" Binding="{Binding Surname}"/>
<DataGridTextColumn Header="Phone" Binding="{Binding Phone_Number}" />
</DataGrid.Columns>
</DataGrid>
LecturerListViewModel.cs:
public class LecturerListViewModel : ViewModelBase<LecturerListViewModel>
{
public ObservableCollection<Lecturer> Lecturers;
private readonly DataAccess _dataAccess = new DataAccess();
public LecturerListViewModel()
{
Lecturers = GetAllLecturers();
}
和ViewModelBase实现了INotifyPropertyChanged。
Lecturer.cs
public class Lecturer
{
public Lecturer(){}
public int Id_Lecturer { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string Phone_Number { get; set; }
我做错了什么?我用debuger检查了它,DataContext包含了所有讲师,但是数据网格中没有显示。
答案 0 :(得分:9)
绑定时出错。试试这个:
<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Lecturers}" >
代码隐藏:
private ObservableCollection<Lecturer> _lecturers = new ObservableCollection<Lecturer>();
public ObservableCollection<Lecturer> Lecturers
{
get { return _lecturers; }
set { _lecturers = value; }
}
Here是简单的示例代码(LecturerSimpleBinding.zip)。
答案 1 :(得分:6)
我们走了
<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Path=Lecturers}" >
然后
private ObservableCollection<Lecturer> lecturers;
public ObservableCollection<Lecturer> Lecturers
{
get { return lecturers; }
set
{
lecturers = value;
this.NotifyPropertyChanged("Lecturers");
}
}
答案 2 :(得分:6)
答案 3 :(得分:2)
Lecturers
是一个字段,但数据绑定仅适用于属性。尝试声明Lecturers
喜欢:
public ObservableCollection<Lecturer> Lecturers { get; set; }
答案 4 :(得分:1)
MainWindow.xaml.cs :好的
MainWindow.xaml :好的
LecturerListViewModel.cs :好的 - 假设GetAllLecturers()
方法返回ObservableCollection
Lecturer
。
<强> Lecturer.cs 强>:
public class Lecturer : INotifyPropertyChanged
{
//public Lecturer(){} <- not necessary
private int _id;
public int Id
{
get { return _id; }
set
{
_id = value;
OnPropertyChanged("Id");
}
}
// continue doing the above property change to all the properties you want your UI to notice their changes.
...
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}