[英]windows phone 8: User control cannot be disposed when it was removed from its parent panel?
我有一個帶有內容面板的簡單應用程序頁面,並且在內容面板中添加了一個用戶控件。 當我單擊一個按鈕將其刪除時,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!");
}
從您的代碼中,我可以說它當然不會被廢棄,因為您的MainPage
仍然保留對page
的引用。 嘗試在刪除后將其設置為null:
page = null;
但這還不足以立即處置控件。 您必須等待GC流程,或者稍后再直接調用它:
GC.Collect();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.