Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

c# - MVVM datagrid binding

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...