I
I
Ilya2013-12-02 08:12:21
WPF
Ilya, 2013-12-02 08:12:21

How do I implement INotifyPropertyChanged to automatically update the data in the DataGrid?

I am making a desktop application using Entity Framework on WPF.
Wrote the following class.

public class PlavkaViewModel : INotifyPropertyChanged
    {
        private Model.MagnesiumEntities _dataContext;
        public ObservableCollection<Model.plavka> Plavkas { get; private set; }
 
        public PlavkaViewModel()
        {
            _dataContext = new Model.MagnesiumEntities();
            Plavkas = new ObservableCollection<Model.plavka>(_dataContext.plavkas);  
        }
 
        public void SaveChanges()
        {
            _dataContext.SaveChanges();
        }
 
        #region INotifyPropertyChanged
         // (Что мне тут делать?)
        /// <summary>
        /// Событие, которое мы должны вызывать каждый раз когда хотим сообщить об изменении данных. 
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;
 
        /// <summary>
        /// Метод для вызова события об изменении свойства ViewModel.
        /// </summary>
        /// <param name="propertyName"></param>
        private void RaisePropertyChanged(string propertyName)
        {
            if (PropertyChanged == null)
            {
                return;
            }
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
 
        #endregion
    }

And then tied it to the DataGrid. Everything is displayed well. But how can I make it so that when the data in the database changes (for example, from another client), this would immediately be displayed in the table?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Guketlev, 2013-12-02
@Yavanosta

you need one of two things:
1) somehow notify other clients that something has changed in the database. here you will need an application server through which all requests will go, and which will send notifications to clients
2) once every n seconds, check if something has changed in the database

A
Artem Skopintsev, 2013-12-02
@SharperX

You must add a call to the PropertyChanged event for each property that needs to be updated.
for example

public class People : INotifyPropertyChanged
{
      public event PropertyChangedEventHandler PropertyChanged;

      private string _firstName;

      public string FirstName
      {
            get { return _firstName; }
            set
            {
                _firstName = value;
                PropertyChanged(this, new PropertyChangedEventArgs("FirstName"));
            }
      }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question