Skip to content

Instantly share code, notes, and snippets.

@jkasten2
Last active January 26, 2023 23:47
Show Gist options
  • Save jkasten2/2fc01271055df7fae6a6210c74269d48 to your computer and use it in GitHub Desktop.
Save jkasten2/2fc01271055df7fae6a6210c74269d48 to your computer and use it in GitHub Desktop.
// Example of INotifyPropertyChanged
// * Other examples online were missing consumming the event itself.
// * https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.inotifypropertychanged.propertychanged
// Can try running this example at: https://dotnetfiddle.net/pWjjGo
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
public class Program
{
public static void Main()
{
var model = new MyModel();
model.PropertyChanged += onPropertyChanged;
model.CustomerName = "Josh";
}
static void onPropertyChanged(object sender, PropertyChangedEventArgs e)
{
Console.WriteLine(
"onPropertyChanged:sender: " + sender + " , e.PropertyName: " + e.PropertyName
);
if (e.PropertyName == "CustomerName")
{
// INotifyPropertyChanged API is not ideal
// It's cumbersome for the consumer, it could cleaner if Microsoft used generics instead of requiring a cast
var currentName = ((MyModel)sender).CustomerName;
Console.WriteLine("name is now " + currentName);
}
}
}
class MyModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private string customerNameValue = string.Empty;
public string CustomerName
{
get { return this.customerNameValue; }
set
{
if (value != this.customerNameValue)
{
this.customerNameValue = value;
NotifyPropertyChanged();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment