There is noone listening to PropertyChanged
, which will then be null when trying to call it. Use an OnPropertyChanged
method instead:
private void OnPropertyChanged(string propertyName){
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
// With C# 6 this can be replaced with
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public string MyProperty
{
get { return my; }
set
{
if (my == value)
return;
my = value;
OnPropertyChanged("MyProperty");
}
}
To avoid it being null
you have to subscribe to it, for instance from your main method:
static void Main(string[] args){
Cls s = new Cls();
s.PropertyChanged += (sender, args) => MessageBox.Show("MyProperty changed!");
s.print();
}
which is a fancy way of writing
static void Main(string[] args){
Cls s = new Cls();
s.PropertyChanged += ShowMessage;
s.print();
}
private void ShowMessage(object sender, PropertyChangedEventArgs args){
MessageBox.Show("MyProperty changed!");
}
Whatever is more clear to you.
You can read more about events here