我有一个带有内容面板的简单应用程序页面,我在内容面板中添加了一个usercontrol。当我单击一个按钮将其删除时,userControl的析构函数没有执行。为什么呢?
这是我的主页:
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Button Grid.Row="0" Content="AddOrRemove" Click="Button_Click"/>
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
</Grid>
</Grid>
按钮点击事件是:
private void Button_Click(object sender, RoutedEventArgs e)
{
if (this.ContentPanel.Children.Count > 0)
{
this.ContentPanel.Children.Clear();
return;
}
page = new PromptPage();
this.ContentPanel.Children.Add(page);
}
PromptPage.xaml:
<Grid x:Name="LayoutRoot" Background="{StaticResource PhoneChromeBrush}">
<StackPanel>
<TextBlock Text="balabalaabcdefghijklmnop1"></TextBlock>
<TextBlock Text="balabalaabcdefghijklmnop2"></TextBlock>
<TextBlock Text="balabalaabcdefghijklmnop3"></TextBlock>
<TextBlock Text="balabalaabcdefghijklmnop4"></TextBlock>
<TextBlock Text="balabalaabcdefghijklmnop5"></TextBlock>
<TextBlock Text="balabalaabcdefghijklmnop6"></TextBlock>
<TextBlock Text="balabalaabcdefghijklmnop7"></TextBlock>
<TextBlock Text="balabalaabcdefghijklmnop8"></TextBlock>
<TextBlock Text="balabalaabcdefghijklmnop9"></TextBlock>
<TextBlock Text="balabalaabcdefghijklmnop10"></TextBlock>
<TextBlock Text="balabalaabcdefghijklmnop11"></TextBlock>
<TextBlock Text="balabalaabcdefghijklmnop12"></TextBlock>
<TextBlock Text="balabalaabcdefghijklmnop13"></TextBlock>
</StackPanel>
</Grid>
PromptPage.xaml.cs:
public PromptPage()
{
InitializeComponent();
}
~PromptPage()
{
System.Diagnostics.Debug.WriteLine("disposed!");
}
答案 0 :(得分:1)
从您的代码中,我可以说当然不会处理它,因为您的MainPage
仍然保留对page
的引用。尝试删除后将其设置为null:
page = null;
但是立即处理控制是不够的。您必须等待GC过程或稍后稍后直接调用它:
GC.Collect();