Wpf 何时释放UserControl事件处理程序?
如果我正在代码隐藏中的UserControl上注册事件。例如:Wpf 何时释放UserControl事件处理程序?,wpf,events,user-controls,dispose,Wpf,Events,User Controls,Dispose,如果我正在代码隐藏中的UserControl上注册事件。例如: public partial class PositionView : UserControl { // If required ViewModel can be accessed using DataContext public PositionViewModel ViewModel { get { return (PositionViewModel) this.DataContext;
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());
}
}
我应该何时处理事件处理程序?没有可挂上的IDisposable
如果我通过xaml绑定到事件,这在生命周期管理方面会是一个更干净的解决方案吗?事件的源以及事件处理程序的源都是本地的。因此,当收集
UserControl
本身时,将收集它们
收集
UserControl
时,将不会有其他对象使eventHandler保持活动状态。因此,您不需要手动实施“生命周期管理”。好的,但在更一般的情况下,我可能会挂接键盘事件等?i、 当我不想依赖本地作用域时,我怀疑UserControl是否应该绑定到其作用域之外的事件,因为它应该是(数据绑定)单元。键盘事件实际上是在用户控件上触发的,因此您也可以在私有范围内处理这些事件。