我一直在寻找超过 30 分钟,但我根本无法弄清楚问题是什么。我有一个TabControl
,它的项目将由用户关闭。由于每个TabItem
都以某种方式连接到自定义控件和多个对象,每个对象都使用大量内存,因此我想处置与 this 一起使用的所有对象TabItem
。
为了更清楚并在这里为您节省大量代码,简化情况:
<UserControl x:Class="myProject.GridFour"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<ScrollViewer Height="Auto" Margin="0" Name="scrollViewer11" Width="Auto" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto"></ScrollViewer>
<ScrollViewer Grid.Column="1" Height="Auto" Name="scrollViewer12" Width="Auto" Margin="0" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto"></ScrollViewer>
<ScrollViewer Grid.Row="1"> Height="Auto" Name="scrollViewer21" Width="Auto" Margin="0" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto"></ScrollViewer>
<ScrollViewer Height="Auto" Name="scrollViewer22" Width="Auto" Grid.Column="1" Margin="0" Grid.Row="1" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto"></ScrollViewer>
</Grid>
</UserControl>
现在我设置对应的tabitem的内容:
GridFour myControl = new GridFour();
myTabItem.Content = myControl;
我也有自定义对象,每个对象都包含一个网格,它作为内容添加到我的用户控件的滚动查看器中:
class MyClass
{
internal Grid _grid = new Grid();
internal Image _image = new Image() {Width = Double.NaN, Height = Double.NaN HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Stretch = Stretch.Fill};
//... a lot of variables, data, images and methods...
}
MyClass[] myObject = new MyClass[4];
for(int i = 0; i < 4; i++)
{
myObject[i] = new MyClass();
myObject[i]._grid.Children.Add(_image); //that actually happens when I initialise the object, it is just to show how everything is connected
}
myControl.scrollViewer11.Content = myObject[0]._grid;
myControl.scrollViewer12.Content = myObject[1]._grid;
myControl.scrollViewer21.Content = myObject[2]._grid;
myControl.scrollViewer22.Content = myObject[3]._grid;
现在,当用户想要关闭 tabitem 时,显然我也想摆脱 myControl 和每个对象 myObject。我试图通过 IDisposable 对它们调用 Dispose 方法,但这总是抛出 NullReferenceException ,我根本不知道为什么。
我可能应该提到每个 myObject 都在 aDictionary<string, MyClass>
中,但是在调用 dispose 之前我从那里删除了该对象。