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?
The source of the
Eventas well as theEventHandlerare local. Therefore they will be collected when theUserControlitself is collected.When the
UserControlis collected there will be no other object that is keeping your eventHandler alive. Therefore you do not need to manually implement ‘lifetime management’.