Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to release UserControl event handlers?

If I'm registering events on a UserControl in the code behind. E.g.:

public partial class PositionView : UserControl
{
    // If required ViewModel can be accessed using DataContext 
    public PositionViewModel ViewModel 
    {
        get { return (PositionViewModel) this.DataContext; }
    }

    public PositionView()
    {
        InitializeComponent();

        this.DataContextChanged += new System.Windows.DependencyPropertyChangedEventHandler(PositionView_DataContextChanged);
    }

    void PositionView_DataContextChanged(object sender, System.Windows.DependencyPropertyChangedEventArgs e)
    {
        this.ViewModel.UpdateTotalsChanged.Subscribe(_ => this.PositionGridControl.UpdateTotalSummary());
    }       
}

When should I be disposing of the event handler? There is no IDisposable to hook onto?

If I bind to the event via the xaml will this be a cleaner solution in terms of lifetime management?

like image 366
DanH Avatar asked Nov 27 '25 14:11

DanH


1 Answers

The source of the Event as well as the EventHandler are local. Therefore they will be collected when the UserControl itself is collected.

When the UserControl is collected there will be no other object that is keeping your eventHandler alive. Therefore you do not need to manually implement 'lifetime management'.

like image 76
Myrtle Avatar answered Nov 29 '25 16:11

Myrtle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!