Question

I have a simple application page with a content panel,and I add a usercontrol in the content panel. When I click a button to remove it, the userControl's destructor didn't excute. Why?

Here's my main page:

<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>

the button click event is:

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!");
    }
Was it helpful?

Solution

From your code, I can say of course it won't be disposed because your MainPage still holds the reference to page. Try set it null after remove:

page = null;

But it isn't enough to make the control disposed immediately. You must wait for the GC process or directly call it at some point later:

GC.Collect();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top