Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm using MVVM for my project and I'm trying to bind a table from my database with a DataGrid. But when I run my application datagrid is empty.

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

and ViewModelBase implements 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; }

What did I do wrong? I checked it with debuger and DataContext contains all lecturers, but ther aren't shown in datagrid.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
189 views
Welcome To Ask or Share your Answers For Others

1 Answer

You have an error in binding. Try this:

<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Lecturers}" >

Code-behind:

private ObservableCollection<Lecturer> _lecturers = new ObservableCollection<Lecturer>();
public ObservableCollection<Lecturer> Lecturers
{
   get { return _lecturers; }
   set { _lecturers = value; }
}

Here is simple example code (LecturerSimpleBinding.zip).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...