我有一个像这样从主窗口打开的窗口
Views.VTestWindow searchViewTest = new VTestWindow(myUser.UserID);
searchViewTest.Closed += SearchViewTest_Closed;
searchViewTest.DataContext = searchContext;
searchViewTest.ShowDialog();
我在绑定(bind)到 viewModel 的 View 中有几个控件。让我感到胃灼热的是一个组合框。我将其 selectedIndex 绑定(bind)到我的 VM 上的属性。如果我删除该绑定(bind),我的探查器会说 VM 已被处置。但是,如果我在那里有绑定(bind)并且组合框被打开(不必更改选择),探查器会说我的 VM 在调用 dispose 后仍然存在。
组合框代码
<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;
关于c# - 绑定(bind)导致我的视图模型留在内存中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29783554/