Reputation: 86729
I have a class that implements INotifyPropertyChanged and also has its own concept of properties, a little bit like this:
class sealed MyClass : INotifyPropertyChanged
{
private Dictionary<string, object> _properties;
public object GetProperty(string name)
{
return _properties[name];
}
public object SomeProperty
{
get
{
return GetProperty("SomeProperty");
}
}
}
Note that some common properties also have C# accessors.
I want to raise an event to notify others that a property (whose value is accessed through the GetProperty method) has changed even if this property does not have a corresponding C# accessor.
Assuming that there is no risk of a clash (i.e. inadvertantly raising a property changed event for a C# property whose value has not changed - note that this class is sealed), is there any reason why I can't just use the INotifyPropertyChanged.PropertyChanged
event to notify others, or should I add my own event for this purpose?
Upvotes: 3
Views: 384
Reputation: 35870
Technically, it depends on who has subscribed to PropertyChanged
and what they do in response to the PropertyChanged
event. If they don't try to read a .NET "property", you're fine.
But, that really introduces a coupling and the use of INPC is trying to decouple. INPC at the general case assumes PropertyChanged
means a .NET property (of a given name) has changed and is expected to be the case for all places that use INPC. i.e. you implement INPC because you want to use your object in any place that accepts INPC. If your object can't do that, then it violates the implied contract of INPC. If you have a PropertyChanged
handler that does something different than read a property and you're re-using INPC just because it's there then maybe writing you own interface is a good idea.
Upvotes: 0
Reputation: 292465
As far as I know, there's no harm in raising PropertyChanged
for a property that isn't there, but I don't think it's very useful either. INotifyPropertyChanged
is mostly used by data binding systems (in WinForms, WPF, Silverlight...), and these system don't know how to access your custom "properties".
Now, what you could do is implement ICustomTypeDescriptor
to provide access to your custom properties in a standard way. This works with Windows Forms and WPF, I'm not sure about other frameworks.
Of course, if your intention is not to use this for data binding, you can still use this event to notify consumers of your class that values have changed.
Upvotes: 0
Reputation: 34198
I would suggest that you add your own. Although there's no specific reason that the code would break, INotifyPropertyChanged
has a specific intended usage, and one that is understood by a lot of potential consumers. I'd not personally write code that contradicts that, just in case.
Upvotes: 2