如何关闭后台文件中的usercontrol?

时间:2014-03-18 22:31:18

标签: c# wpf xaml user-controls

我是WPF新手所以请理解:

我有一类usercontrol,它实现了一个屏幕(对话框),其中包含一个包含控件的网格。我的代码隐藏文件在打开对话框之前执行一系列检查。如果条件不满足,我想销毁/退出/卸载/关闭usercontrol。我正在使用Windows,似乎我找不到关闭usercontrol的调用。我读到了有问题的问题,例如从父母那里关闭......但是当我试图通过this.Parent找到父母时,它会返回null。

有什么建议吗?

3 个答案:

答案 0 :(得分:0)

如果您的条件不符合,并且您甚至没有显示用户控件 - 请不要初始化它。

如果你无法避免,你可以选择调用Dispose()或让GC处理它。

答案 1 :(得分:0)

要从usercontrol获取父级,我使用此

var parentWindow = Window.GetWindow(this);

但我同意安德烈亚斯,如果条件不满足,甚至不加载它。

一个想法可以绑定网格内容可能从绑定对象中删除usercontrol。

吉姆

答案 2 :(得分:0)

我猜你已经在xaml中添加了你的用户控件。这就是为什么你甚至担心卸载它。尝试在代码中加载它。在xaml中有一个容器,例如堆栈面板,用于保存用户控件。

除非你的条件不符合,否则不要加载它。

例如:

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>

代码;

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