Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8932971
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T09:25:36+00:00 2026-06-15T09:25:36+00:00

I was given hints in an other questions on how to implement a MVVM.

  • 0

I was given hints in an other questions on how to implement a MVVM. I had problems passing bind update to the GUI when changes are made in the Student class itself (which occure quiet a lot in my project). Is there a way to easy these things up and have it in a more compact way than implemented yet? Or is this the state of the art to implement MVVM?

class MainWindowViewModel : INotifyPropertyChanged
{
   ObservableCollection<StudentViewModel> studentViewModels = new ObservableCollection<StudentViewModel>();

   public ObservableCollection<StudentViewModel> StudentViewModels
   {
      get { return studentViewModels; }
   }

   public MainWindowViewModel()
   {
      studentViewModels.Add(new StudentViewModel());
      studentViewModels.Add(new StudentViewModel());
      studentViewModels.Add(new StudentViewModel());
   }

   public event PropertyChangedEventHandler PropertyChanged;
   internal void OnPropertyChanged(String propertyName)
   {
      if (PropertyChanged != null)
      {
         PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
      }
   }
}


class StudentViewModel : INotifyPropertyChanged
{
   Student model;
   public String StudentFirstName
   {
      get { return model.StudentFirstName; }
      set { model.StudentFirstName = value; }
   }
   public String StudentLastName
   {
      get { return model.StudentLastName; }
      set { model.StudentLastName = value; }
   }

   public StudentViewModel()
   {
      model = new Student();
      this.model.PropertyChanged += (sender, e) => 
      {
         switch (e.PropertyName)
         {
            case "StudentFirstName": OnPropertyChanged("StudentFirstName"); break;
            case "StudentLastName": OnPropertyChanged("StudentLastName"); break;
            default: break;
         }
      };
   }

   public StudentViewModel(Student model)
   {
      this.model = model;

      this.model.PropertyChanged += (sender, e) =>
      {
         switch (e.PropertyName)
         {
            case "StudentFirstName": OnPropertyChanged("StudentFirstName"); break;
            case "StudentLastName": OnPropertyChanged("StudentLastName"); break;
            default: break;
         }
      ;
   }

   public void changeStudent()
   {
      model.changeStudent();
   }

   public event PropertyChangedEventHandler PropertyChanged;
   internal void OnPropertyChanged(String propertyName)
   {
      if (PropertyChanged != null)
      {
         PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
      }
   }
}



class Student : INotifyPropertyChanged
{
   public String studentFirstName;
   public String StudentFirstName
   {
      get { return studentFirstName; }
      set 
      {
         if (studentFirstName != value)
         {
            studentFirstName = value;
            OnPropertyChanged("StudentFirstName");
         }
      }
   }
   public String studentLastName;
   public String StudentLastName
   {
      get { return this.studentLastName; }
      set
      {
         if (studentLastName != value)
         {
            studentLastName = value;
            OnPropertyChanged("StudentLastName");
         }
      }
   }

   public Student() { }

   public void changeStudent()
   {
      StudentLastName = "McRonald";
   }

   public event PropertyChangedEventHandler PropertyChanged;
   internal void OnPropertyChanged(String propertyName)
   {
      if (PropertyChanged != null)
      {
         PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
      }
   }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T09:25:36+00:00Added an answer on June 15, 2026 at 9:25 am

    I agree with other answers that you should have a look at a MVVM framework. I use MVVM Foundation for my work.

    Wall of text is to follow. I started with MVVM not too long ago as well. This code was of great help for me on my last project.

    Recently I had to work on a class which also needed IEditableObject to manage editing/saving/discarding the object as well as PropertyChanged notifications. Since you mention a way “to easy things up” I am going to post the base classe I used to tie MVVM and Editable Object together. It was a big time saver for me for implementing all other classes.

    The EditableObject inherits from ObservableObject that is part of MVVM Foundation. It takes a struct for the object you are working with as a typeparam.

    If you are familiar with implementation of IEditabeObject, there are editData and backupData variables which hold the data you are currently working with (I am not inheriting from this, I created my own EditableObject). I am using AutoMapper to, basically, create a deep copy (backup) of the data I am working with so that it can be restored. There are other ways to do this (look up Serialization or Value Injection), but I already had AutoMapper in the project so no need for more dlls.

    The EditableObject has abstract methods SaveObject and RemoveObject, which you implement to handle database calls, etc, to remove and save the objects. The Edit of your object is done using BeginEdit and DiscardChanges and SaveChanges.

    The magic happens with the RaisePropertiesChanged method which raises PropertyChanged methods on all decorated properties in your class. So whenever you edit your object and (lets say) discard the changes. The UI is refreshed with back to original values. It also includes IsEditEnabled flag you can bind your UI to. Originally I used PropertyChanged with an empty string, but this would raise it on all properties. Using attributes I ensure it changes only on the properties that I need to update.

    I used your Student Class to implement this and attached the base class below.

    Hope it helps!

    public class Student: EditableObject<WPF.MVVMBase.Student.StudentData>
        {
            #region Struct
    
            public struct StudentData
            {
                public string firstName;
                public string lastName;
            }
    
            #endregion
    
            #region Public Properties
    
            [ObservableProperty]
            public string FirstName
            {
                get
                {
                    return _editData.firstName;
                }
                set
                {
                    _editData.firstName = value;
                    this.RaisePropertyChanged("FirstName");
                }
            }
    
            [ObservableProperty]
            public string LastName
            {
                get
                {
                    return _editData.lastName;
                }
                set
                {
                    _editData.lastName = value;
                    this.RaisePropertyChanged("LastName");
                }
            }
    
            #endregion
    
            #region Methods
    
            protected override bool SaveObject()
            {
                //Save Student Changes to Database
    
                return true;
            }
    
            protected override bool RemoveObject()
            {
                //Remove Student from Database
    
                return true;
            }
    
            #endregion
        }
    

    This is the EditableObject class

    namespace WPF.MVVMBase
    {
        /// <summary>
        /// Property Decorator that marks the Property as Observable. This is used by the EditableObject class to determine for which properties to raise the Property Changed method
        /// </summary>
        public class ObservablePropertyAttribute : System.Attribute{};
    
        /// <summary>
        /// Extends the ObservableObject class. EditableObject implements methods which are used to edit the object as well as raise the Property Changed events.
        /// </summary>
        /// <typeparam name="T">The Struct for the Editable Object</typeparam>
        public abstract class EditableObject<T> : ObservableObject
        {
            #region Private Variables
    
            bool _IsEditEnabled = false;
            bool _IsSelected = false;
    
            protected T _editData;
            protected T _backupData;
    
            #endregion
    
            #region Public Properties
    
            /// <summary>
            /// Controls if the Edit is enabled on the Editable Object
            /// </summary>
            public bool IsEditEnabled
            {
                get
                {
                    return _IsEditEnabled;
                }
                protected set
                {
                    _IsEditEnabled = value;
                    this.RaisePropertyChanged("IsEditEnabled");
                }
            }
    
            /// <summary>
            /// Determines weather the object is Selected. Used with Lists
            /// </summary>
            public bool IsSelected
            {
                get
                {
                    return _IsSelected;
                }
                set
                {
                    _IsSelected = value;
                    this.RaisePropertyChanged("IsSelected");
                }
            }
    
            #endregion
    
            #region Constructor
    
            public EditableObject()
            {
                //Create an instance of the object that will hold the data.
                _editData = Activator.CreateInstance<T>();
            }
    
            #endregion
    
            #region Methods
    
            #region Abstract Methods
    
            /// <summary>
            /// Handle the object saving. This is called by the SaveChanges method.
            /// </summary>
            /// <returns>Indicates if the object was saved successfully</returns>
            protected abstract bool SaveObject();
    
            /// <summary>
            /// Handle the object remove. This is called by the Remove method.
            /// </summary>
            /// <returns>Indicates if the object was removed successfully</returns>
            protected abstract bool RemoveObject();
    
            #endregion
    
            /// <summary>
            /// Begin editing the object. Sets the IsEditEnabled to true and creates a backup of the Data for restoring.
            /// </summary>
            public void BeginEdit()
            {
                IsEditEnabled = true;
                _backupData = Mapper.DynamicMap<T>(_editData);
            }
    
            /// <summary>
            /// Discard any changes made to the object. Set the IsEditEnabled flag to false and restore the data from the Backup.
            /// </summary>
            public void DiscardChanges()
            {
                _editData = _backupData;
                IsEditEnabled = false;
    
                RaisePropertiesChanged(this);
            }
    
            /// <summary>
            /// Save the changes made to the object. Calls the SaveObject method. If save was successfull IsEditEnabled is set to false and backup data is set to current data.
            /// </summary>
            /// <returns>Indicates if the object was saved successfully</returns>
            public bool SaveChanges()
            {
                bool isSaveSuccessfull = SaveObject();
    
                if (isSaveSuccessfull == true)
                {
                    _backupData = _editData;
    
                    IsEditEnabled = false;
    
                    RaisePropertiesChanged(this);
                }
    
                return isSaveSuccessfull;
            }
    
            public bool Remove()
            {
                bool isRemoveSuccessfull = RemoveObject();
                return isRemoveSuccessfull;
            }
    
            /// <summary>
            /// Raises ObservableObject Property Changed for all the decorated methods in the given object so that the interface can refresh accordingly.
            /// </summary>
            /// <param name="baseObject"></param>
            public void RaisePropertiesChanged(object baseObject)
            {
                PropertyInfo[] properties = baseObject.GetType().GetProperties();
                foreach (PropertyInfo property in properties)
                {
                    object[] attributes = property.GetCustomAttributes(true);
    
                    bool isObservableProperty = (from attribute in attributes
                                                 where attribute is ObservablePropertyAttribute
                                                 select attribute).Count() > 0;
    
                    if (isObservableProperty)
                    {
                        RaisePropertyChanged(property.Name);
                    }
                }
            }
    
            #endregion
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I've recently made a change stylistically and wanted to see how other c++ programmers
While researching the use of Table Hints , I came across these two questions:
As some one mentioned in other forum that interviewer has asked the question given
There are some other SO questions about concurrency but they don't quite address my
Given that the web application doesn't have su privileges, I'd like to execute a
Given this method to work on a HTML page in a webbrowser: bool semaphoreForDocCompletedEvent;
Given an NSMutableArray of dynamic CGPoint s, what is the fastest and most efficient
Given a certain date, I want to set the value of a cell with
given a Python class hierarchy, say class Base: def method1 def method2 def method3
Given a MySQL table of real estate data, I would like to generate a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.