XAML simplification of usage INotifyPropertyChanged

Hello,

I want to share some code, wich can simplify usage of INotifyPropertyChanged in XAML.

Take a loot at following fragments:

Snippet

namespace NotifyPropertyChanged
{
    public class BindableBase : INotifyPropertyChanged 
    {
        public event PropertyChangedEventHandler PropertyChanged;
 
        public void RaisePropertyChanged(string propertyName)
        {
            if(PropertyChanged != null)
            {
                PropertyChanged.Invoke(thisnew PropertyChangedEventArgs(propertyName));
            }
        }
    }
}

Class BindableBase now can become as base class for those objects, which need to notify UI about changes in source code. Consider next example:

Snippet

namespace NotifyPropertyChanged
{
    public class Student : BindableBase
    {
        string _firstName;
        public string FirstName
        {
            get
            {
                return _firstName;
            }
            set
            {
                if(value != _firstName)
                {
                    _firstName = value;
                    RaisePropertyChanged(nameof(FirstName));
                }
            }
        }
 
        string _lastName;
 
        public string LastName { get { return _lastName; }
            set
            {
                if(value != _lastName)
                {
                    _lastName = value;
                    RaisePropertyChanged(nameof(LastName));
                }
            }
        }
 
    }
}

In similar ways other classes that need notification about changes in their fields can implement notifications without need of writing similar code over and over again. Just don't forget for usage of DataBinding write something like this:

Snippet

public partial class MainWindow : Window
{
    Student st = new Student();
 
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = st;
    }
 
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        st.LastName = "Ivanov";
    }
}

No Comments

Add a Comment