Я уже осмотрелся в StackOverflow, и на мой ближайший вопрос был дан ответ 7 лет назад, и он не решил мою проблему.
MainControl.Children.Remove(ChildControl);
это действительно удаляет ChildControl из списка детей,но если я проверю память с помощью диагностических инструментов VS (а именно вкладки «использование памяти»), я смогу увидеть, что объект все еще создается.Я думал, что GC позаботится об этом, но если я продолжу использовать приложение, число экземпляров ChildControl, которые предположительно были удалены, не уменьшится.
РЕДАКТИРОВАТЬ: я пишу фрагмент кодадавая мне эту проблему.
public partial class MainWindow : Window
{
public ILog Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// user control
MainGridUserControl mainGrid;
SelectionProcess selProcess;
ProcessManagerViewModel ProcessManagerContext;
/// <summary>
/// Switch main grid and selection process. True active main grid, false active selection process
/// </summary>
/// <param name="openClose"></param>
public void SwitchMainGridSelectionProcess(bool openClose)
{
InfoLoginViewModel ilvm = (InfoLoginViewModel)SimpleIoc.Default.GetInstance<IInfoLoginViewModel>();
InfoLogin infoLogin = ilvm.ActualInfoLogin;
// if openClose true close selection process user control and open main grid user control
// else close main grid user contorllo and return to selection process user control
if (openClose)
{
MainWindowGrid.Children.Remove(selProcess);
SelectionProcessViewModel spvm = (SelectionProcessViewModel)selProcess.DataContext;
spvm.CloseCommand.Execute(null);
selProcess = null;
mainGrid = new MainGridUserControl(mwvm.LayoutMainGridTop, mwvm.ShowStationTree);
Grid.SetRow(mainGrid, MAINGRID_ROW);
if (this.FindName("MainWindowGrid") is null)
this.RegisterName("MainWindowGrid", mainGrid);
MainWindowGrid.Children.Add(mainGrid);
mwvm.SetOpenProcessToggleButtonCommand.Execute(null);
// set permission process user
mwvm.SetEnableButtonCommand.Execute(infoLogin.ProcessUser);
}
else
{
// if maiGrid null the open process failed. The old selProcess is already present
if (mainGrid != null)
{
if (!(this.FindName("MainWindowGrid") is null))
this.UnregisterName("MainWindowGrid");
MainWindowGrid.Children.Remove(mainGrid); // snapshot diagnostic tool shows this line has no effect on the number of instances of 'mainGrid'
mainGrid = null;
selProcess = new SelectionProcess();
Grid.SetRow(selProcess, MAINGRID_ROW);
MainWindowGrid.Children.Add(selProcess);
// set permission application user
mwvm.SetEnableButtonCommand.Execute(infoLogin.ApplicationUser);
}
}
}
}