I have a client server application.
From the server I get a simple data transfer object.
e.g.
public class Person:BaseObject
{
public string Name { get; set; }
public string Course { get; set; }
public Person( string name )
{
this.Name = name;
}
}
On the client side I have a WPF application and so i have to use INotifyPropertyChanged.
Now i look for a elegant way to implement this in my object. My advantage is that the most dialogs are only displaying, so that there is no reason to implement it there, because in these cases the whole object will be switch (For that i use INotifyPropertyChanged in my ViewModel which contains the object). Now i have situation where a property get changed in a deeper structure and my view didn’t notice it.
I try to solve it with a inheritance and a extension.
I wrote my “own” class.
public class PersonCm : Person
{
public new string Course
{
get
{
return base.Course;
}
set
{
base.Course = value;
this.PropertyChanged( );
}
}
So i got all Property from my base class and “override” only these where i need my INotifyPropertyChanged. To add my functionality i use following two classes:
public class ClientFunctions : INotifyPropertyChanged
{
public static readonly ClientFunctions Instance = new ClientFunctions( );
private ClientFunctions( )
{
// Empty
}
[field: NonSerialized]
public event PropertyChangedEventHandler PropertyChanged;
public bool SetProperty<T>( ref T storage, T value, [CallerMemberName] string propertyName = "" )
{
if ( object.Equals( storage, value ) )
{
return false;
}
storage = value;
this.OnPropertyChanged( propertyName, storage );
return true;
}
public void OnPropertyChanged( string propertyName, object sender )
{
var eventHandler = this.PropertyChanged;
if ( eventHandler != null )
{
eventHandler( this, new PropertyChangedEventArgs( propertyName ) );
}
}
}
A singleton class with the INotifyPropertyChanged code.
public static class Extension
{
public static void PropertyChanged( this BaseObject obj, [CallerMemberName] string propertyName = "" )
{
ClientFunctions.Instance.OnPropertyChanged( propertyName, obj );
}
}
And one Extension which call my singleton class.
My problem now is that each time i call my INotifyPropertyChanged code my PropertyChangedEventHandler is null and i have no idea why.
Does anybody have an idea or an tip for me.
From what I can see you have an object (your
PersonCm) with a property, but when its property changes, the extension method causes theClientFunctions.Instanceobject to raise aPropertyChangedevent. ThatPropertyChangedwill only be subscribed if you’re binding to a property on thatClientFunctions.Instanceobject. The object containing your property must surely implementINotifyPropertyChangeditself with its ownPropertyChangedevent (eg by inheriting a base class).(
PropertyChangedwill be null if there are no subscribers to that event – i.e. nothing is binding to any property on the object.)