简体   繁体   中英

How to close a usercontrol in the behind file?

I am new to WPF so please understand:

I have a class of usercontrol that implements a screen (dialog) with a grid that contains controls. My code behind file performs a series of checks prior to opening the dialog. If the conditions aren't met, I want to destroy/exit/unload/close the usercontrol. I am using Windows and it seems that I cannot find the call to close the usercontrol. I read up on the questions that had answers such as closing from the parent... however when I try to find the parent via this.Parent, it returns null.

Any advice?

If your conditions aren't met, and you don't even show the usercontrol - don't initialize it.

If you can't avoid that, you have the option of calling Dispose() or letting the GC handle it.

To get the parent from a usercontrol I use this

var parentWindow = Window.GetWindow(this);

But I agree with Andreas if the conditions are not met don't even load it.

A thought could you bind the grids contents remove the usercontrol from the bound object maybe .

Jim

I am guessing you have added your user control in the xaml. That is why you need to even worry about unloading it. Try loading it in the code instead. have a container in your xaml such as a stack panel to hold the user control.

And do not load it unless you conditions aren't met.

eg:

xaml;

<UserControl x:Class="UserControl2"
         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>
       <StackPanel x:Name="mypanel">                            
       </StackPanel>

    </Grid>
</UserControl>

code;

 if(conditions are true) then
     Dim myusercontrol = New ucMyControl()
     Me.mypanel.Children.Add(myusercontrol)
 end if

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM