I have a FooUserControl
which subscribes on it's LoadedEvent
. This UserControl
can be placed else where on your gui (on any Window
or inside of any Control
). To avoid leaks, I have implemented some kind of disposing.
The problem with this solution:
If you put the FooUserControl
on a TabItem
of a TabControl
and change the tabs, the OnVisualParentChanged()
is called and the subscription is disposed. If I wouldn't add this method, and you close the TabItem
the subscription is still alive in background, although the UserControl
can be disposed. The same problem will occur with a page
public class FooUserControl : UserControl
{
private IDisposable _Subscription;
public FooUserControl()
{
Loaded += _OnLoaded;
}
private void _OnLoaded(object sender, RoutedEventArgs e)
{
// avoid multiple subscribing
Loaded -= _OnLoaded;
// add hook to parent window to dispose subscription
var parentWindow = Window.GetWindow(this);
if(parentWindow != null)
parentWindow.Closed += _ParentWindowOnClosed;
_Subscription = MyObservableInstance.Subscribe(...);
}
private void _ParentWindowOnClosed(object? sender, EventArgs e)
{
_Dispose();
}
// check if the parent visual has been changed
// can happen if you use the control on a page
protected override void OnVisualParentChanged(DependencyObject oldParent)
{
if (oldParent != null)
{
_Dispose();
}
base.OnVisualParentChanged(oldParent);
}
private void _Dispose()
{
_Subscription?.Dispose();
}
}