我使用的MVVM为我的项目,我想表从我有一个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的包含了所有的讲师,但是疗法没有在数据网格中。
您在结合有一个错误。 试试这个:
<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Lecturers}" >
代码隐藏:
private ObservableCollection<Lecturer> _lecturers = new ObservableCollection<Lecturer>();
public ObservableCollection<Lecturer> Lecturers
{
get { return _lecturers; }
set { _lecturers = value; }
}
这里是简单的示例代码(LecturerSimpleBinding.zip)。
开始了
<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Path=Lecturers}" >
然后
private ObservableCollection<Lecturer> lecturers;
public ObservableCollection<Lecturer> Lecturers
{
get { return lecturers; }
set
{
lecturers = value;
this.NotifyPropertyChanged("Lecturers");
}
}
上述赛义德·萨阿德是正确的。 我看到您的设置两个潜在的问题,这两个赛义德解决。
- 张贴在问题DOEN的例子不执行INotifyPropertyChanged
- 在CLR属性被绑定到必须是公共财产。 场将无法正常工作,因为databindindg通过反射工作。
Lecturers
是一个领域,但数据绑定,只有性质的作品。 尝试宣告Lecturers
,如:
public ObservableCollection<Lecturer> Lecturers { get; set; }
MainWindow.xaml.cs:OK
MainWindow.xaml:OK
LecturerListViewModel.cs:OK -假设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));
}
}
}
检查这个答案: 添加到INotifyPropertyChanged的模式?