-1

I am very new to programming. Trying to understand the basic idea of MVVM using this tutorial http://social.technet.microsoft.com/wiki/contents/articles/13536.easy-mvvm-examples-in-extreme-detail.aspx

I removed the interface " : INotifypropertychanged" from this code (Deleted those words). Still this program runs and behaves as intended. Then what is he purpose of INotifyPropertychanged here?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Windows;
using System.Windows.Threading;

namespace MvvmExample.ViewModel
{
    class ViewModelBase : INotifyPropertyChanged
    {
        //basic ViewModelBase
        internal void RaisePropertyChanged(string prop)
        {
            if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(prop)); }
        }
        public event PropertyChangedEventHandler PropertyChanged;

        //Extra Stuff, shows why a base ViewModel is useful
        bool? _CloseWindowFlag;
        public bool? CloseWindowFlag
        {
            get { return _CloseWindowFlag; }
            set
            {
                _CloseWindowFlag = value;
                RaisePropertyChanged("CloseWindowFlag");
            }
        }

        public virtual void CloseWindow(bool? result = true)
        {
            Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
            {
                CloseWindowFlag = CloseWindowFlag == null 
                    ? true 
                    : !CloseWindowFlag;
            }));
        }
    }
}
Muthu Vel
  • 67
  • 9
  • 2
    A WPF Binding inspects the source object of the binding whether it implements the interface. It it does, the Binding attaches a handler for the PropertyChanged event to get notified about property changes. Without the interface declaration, the event would still be present and fired, but the Binding wouldn't be registered as listener and not be updated. – Clemens Oct 01 '16 at 07:12

1 Answers1

3

The main duty of INotifyPropertyChanged is to let the view know that the bound property is being changed. Hence the view will be updated automatically.

To know its working, bind a textbox's text property to a string property in view model. Change the string on a button click. Try with and without INotifyPropertyChanged. Without INotifyPropertyChanged, the textbox text will not change on button click.

INotifyPropertyChanged can also be used to let other view models listen to your current view model's property being changed.

Hope you got the point.

AnjumSKhan
  • 9,647
  • 1
  • 26
  • 38
ViVi
  • 4,339
  • 8
  • 29
  • 52
  • Since i was new to WPF and C# (totally new who has not met any real tutor in life), I was unable to understand your answer. Now I understand it. Since it is advised to avoid "thank you" I did not typed it. – Muthu Vel Oct 11 '16 at 05:38