https://github.com/ghuntley/weakeventlistener
The WeakEventListener allows the owner to be garbage collected if its only remaining link is an event handler.
https://github.com/ghuntley/weakeventlistener
iweakeventlistener uap uwp weakeventmanager xamarin xamarin-android xamarin-ios xamarin-mac
Last synced: about 1 month ago
JSON representation
The WeakEventListener allows the owner to be garbage collected if its only remaining link is an event handler.
- Host: GitHub
- URL: https://github.com/ghuntley/weakeventlistener
- Owner: ghuntley
- License: mit
- Created: 2017-08-07T07:18:49.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2017-08-07T08:23:38.000Z (over 7 years ago)
- Last Synced: 2025-03-15T18:53:11.394Z (about 2 months ago)
- Topics: iweakeventlistener, uap, uwp, weakeventmanager, xamarin, xamarin-android, xamarin-ios, xamarin-mac
- Language: C#
- Homepage: https://ghuntley.com/
- Size: 13.7 KB
- Stars: 25
- Watchers: 3
- Forks: 4
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE.md
Awesome Lists containing this project
README

# WeakEventListenerThe WeakEventListener allows the owner to be garbage collected if its only remaining link is an event handler. See https://docs.microsoft.com/en-us/dotnet/framework/wpf/advanced/weak-event-patterns for more information; the wisdom found on that page is applicable for other platforms inc UWP, Xamarin.Mac, Xamarin.iOS & Xamarin.Android.
# Supported Platforms
* netstandard v1.1 (and up)
# Installation
Installation is done via NuGet:PM> Install-Package WeakEventListener
# Usage
```csharp
public class SampleClass
{
public event EventHandler Raisevent;public void DoSomething()
{
OnRaiseEvent();
}protected virtual void OnRaiseEvent()
{
Raisevent?.Invoke(this, EventArgs.Empty);
}
}public void Test_WeakEventListener_Events()
{
bool isOnEventTriggered = false;
bool isOnDetachTriggered = false;SampleClass sample = new SampleClass();
WeakEventListener weak = new WeakEventListener(sample);
weak.OnEventAction = (instance, source, eventArgs) => { isOnEventTriggered = true; };
weak.OnDetachAction = (listener) => { isOnDetachTriggered = true; };sample.Raisevent += weak.OnEvent;
sample.DoSomething();
Assert.True(isOnEventTriggered);weak.Detach();
Assert.True(isOnDetachTriggered);
}
```# With thanks to
* The WeakEventListener was promoted from the [UWPCommunityToolkit](https://github.com/Microsoft/UWPCommunityToolkit) to become this package.