绑定会导致我的视图模型保留在内存中



我有一个窗口,我从我的主窗口打开,就像这样

Views.VTestWindow searchViewTest = new VTestWindow(myUser.UserID);
searchViewTest.Closed += SearchViewTest_Closed;
searchViewTest.DataContext = searchContext;
searchViewTest.ShowDialog();

我在绑定到视图模型的视图中有几个控件。给我胃灼热的是一个组合盒。我已将其选定索引绑定到 VM 上的属性。如果我删除该绑定,我的探查器会说 VM 已释放。但是,如果我在那里有绑定并且 comboBox 被打开(不必更改选择),探查器会说我的 VM 在调用释放后仍然存在。组合框代码

<ComboBox Width="150" MinHeight="25" SelectedIndex="{Binding SelectedSearchBy}">
      <ComboBox.Items>
        <ComboBoxItem Content="Order Number" />
        <ComboBoxItem Content="Recent Orders" />
        <ComboBoxItem Content="Account (Not Shipped)" />
        <ComboBoxItem Content="Account (Shipped)" />
        <ComboBoxItem Content="Account (All)" />
        <ComboBoxItem Content="Account (Cancelled)" />
        <ComboBoxItem Content="Express" />
        <ComboBoxItem Content="Status" />
        <ComboBoxItem Content="Needs To Be Released" />
      </ComboBox.Items>
</ComboBox>

谁能告诉我为什么会发生这种情况,或者更好的是我将如何解决它?我有仔细检查以确保我没有任何仍在使用的事件处理程序。已清除 VM 将使用的所有列表。我的应用程序相当大,我看到内存使用崩溃,所以我试图找到导致内存问题的每一件小事。

这是我靠近我的窗户

void SearchViewTest_Closed(object sender, EventArgs e)
{
    VTestWindow searchViewTest = sender as VTestWindow;
    searchViewTest.Closed -= SearchViewTest_Closed;
    VmOrderSearch searchContext = searchViewTest.DataContext as VmOrderSearch;
    //Do Stuff here
    searchContext.Dispose();
    searchViewTest.DataContext = null;
    searchViewTest = null;
}

尝试将此代码行添加到适当的位置:

searchViewTest.Closed -= SearchViewTest_Closed;

最新更新