MVVM datagrid binding

前端 未结 5 1580
深忆病人
深忆病人 2020-12-10 16:33

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.

相关标签:
5条回答
  • 2020-12-10 17:04

    MainWindow.xaml.cs: OK

    MainWindow.xaml: OK

    LecturerListViewModel.cs: OK - assuming that GetAllLecturers() method returns an ObservableCollection of 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));
            }
        }
    }
    

    Check this answer: Adding INotifyPropertyChanged to Model?

    0 讨论(0)
  • 2020-12-10 17:11

    Here we go

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

    Then

    private ObservableCollection<Lecturer> lecturers;
    
    public ObservableCollection<Lecturer> Lecturers
    {
        get { return lecturers; }
        set
        {
            lecturers = value;
            this.NotifyPropertyChanged("Lecturers");
        }
    }
    
    0 讨论(0)
  • 2020-12-10 17:13

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

    0 讨论(0)
  • 2020-12-10 17:21

    Lecturers is a field, but data binding works with properties only. Try declaring Lecturers like:

    public ObservableCollection<Lecturer> Lecturers { get; set; }
    
    0 讨论(0)
  • 2020-12-10 17:23

    Sayed Saad above is correct. I see two potential problems with your setup, both of which Sayed resolves.

    1. The example posted in the question doen not implement INotifyPropertyChanged
    2. The CLR property being bound to must be a PUBLIC PROPERTY. Fields will not work, as databindindg works via reflection.
    0 讨论(0)
提交回复
热议问题