[Expand]General Information
[Expand]WinForms Controls
[Expand]ASP.NET Controls and MVC Extensions
[Expand]ASP.NET Bootstrap Controls
[Expand]ASP.NET Core Bootstrap Controls
[Collapse]WPF Controls
  Prerequisites
 [Expand]What's Installed
 [Expand]Common Concepts
 [Collapse]MVVM Framework
  [Expand]ViewModels
  [Expand]Commands
  [Expand]Behaviors
  [Expand]Services
  [Expand]DXBinding
  [Expand]MIF
   Converters
   ViewLocator
   Messenger
   Data Annotation Attributes
   LayoutTreeHelper
   Weak Event
 [Expand]Controls and Libraries
 [Expand]Scaffolding Wizard
 [Expand]Localization
  Redistribution and Deployment
  Get More Help
 [Expand]API Reference
[Expand]Xamarin Controls
[Expand]Windows 10 App Controls
[Expand]Office File API
[Expand]Reporting
[Expand]Report and Dashboard Server
[Expand]Dashboard
[Expand]eXpressApp Framework
[Expand]eXpress Persistent Objects
[Expand]CodeRush
[Expand]CodeRush Classic
[Expand]Cross-Platform Core Libraries
[Expand]Tools and Utilities
 End-User Documentation
View this topic on docs.devexpress.com (Learn more)

Weak Event

Developing an MVVM application may require you to declare events that don't need to be unregistered and don't cause memory leaks. Such events may be useful in organizing the interaction between different modules of the application (for example, data services and view models) and objects that exist throughout the entire application lifecycle.

The WeakEvent class allows you to declare weak events in the delegate void(object sender, object e) format. To declare a weak event, use the following syntax.

Expanded Use Of Closures in Event Handlers

When you subscribe a weak event, that means that the handler is separated by the instance that owns the delegate and the method itself. The instance is stored as a weak reference. This allows you to ignore unsubscribing and to avoid memory leaks. However, this imposes certain limitations when you use a lambda expression as an event handler. Imagine that you have the following subscription:

In this case, the lambda expression contains a closure to a local variable that is declared in the ViewModel's constructor. Since the compiler creates an intermediate object for the defined lambda with closures and this intermediate object is weakly referenced, nothing prevents the Garbage Collector from collecting the intermediate object, so your message handler may never be invoked.

To fix this potential issue with your weak event, declare your local variable as a property/field at the level of the object from which subscription is performed.

In this case, the event handler will be available throughout the entire lifecycle of the owner object.

Is this topic helpful?​​​​​​​