Skip to content

MVVM: Clearing the event handlers for ObservableObject #3889

@jtippet

Description

@jtippet

Describe the problem this feature would solve

I'd like to be able to clear out the PropertyChanged and PropertyChanging event handlers on ObservableObject.

I use object.MemberwiseClone() on my model class to cheaply make mutable copies of data. My model types are immutable, so to make any modifications, I clone the object and retarget the ViewModel at the clone. (My approach is inspired by C# records and with expressions, although it's sort of manually cobbled together since UWP doesn't have C# 9 yet.)

The problem is that MemberwiseClone also copies the backing fields of the events, which means that anyone who was subscribed to notifications on the original model instance becomes subscribed to the cloned model instance too. If I manually implement the event in my own class, I can clear it out with PropertyChanged = null;. But I can't do the same when the event is implemented by ObservableObject, since that syntax only works from within the class that implements the event.

Describe the solution

I'd be 100% satisfied if ObservableObject exposed something like this additional method:

protected void ClearEventHandlers()
{
    PropertyChanged = null;
    PropertyChanging = null;
}

Describe alternatives you've considered

I could use reflection to dig out the backing fields, but that's an abstraction violation, and also defeats the performance of MeberwiseClone(). For now, I'm just forking the implementation of ObservableObject into my own class that does offer the ClearEventHandlers() method illustrated above.

Additional context & Screenshots

Note that I am not at all an MVVM expert, so maybe I'm doing something very silly, or overlooking an obvious option. I submit this feature request with humility, and would be only grateful to hear that there's a better way to do this than what I've contemplated above.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions