从框架内部关闭WPF窗口

5

我正在将一个Winform项目移植到WPF,并开始使用Windows和Pages(使用帧控件)。基本上,我的意图是在用户成功登录之前从一页导航到下一页。现在由于登录是在Page级别处理的...我的问题是:

页面如何关闭父窗口?

如果您知道vb代码,感谢您提前告知。如果不知道,我会在C#中弄清楚。

Public Sub CloseLogIn()
    Dim LogIn = TryCast(Me.Parent, Window)
    If LogIn IsNot Nothing Then
        LogIn.Close()
    End If
End Sub

“关闭父窗口”是什么意思?您是想关闭它吗?还是想退出应用程序? - DHN
抱歉,只是关闭它。 - CogentP
2个回答

3

尝试

Public Sub CloseLogIn()
    Dim LogIn = Window.GetWindow(Me)
    If LogIn IsNot Nothing Then
        LogIn.Close()
    End If
End Sub

Window.GetWindow() 方法返回一个引用,指向包含依赖对象的内容树所在的 Window 对象。


0

你可以通过在页面实例上使用 Parent 属性来获取承载 页面 的窗口。

该属性的类型为 DependencyObject,因此您需要将值转换为所需的类型。在这种情况下,您需要将其转换为 Window

public class MyPage : Page{

   public void CloseWindow(){
     var parentWindow = this.Parent as Window;

     if (parentWindow != null) {
       parentWindow.Close();
     }
   }
}

谢谢Jehof,我认为你走在正确的轨道上,但是我刚试了一下这段代码,This.Parent为空(什么也没有)。 - CogentP
@user1603568,“this.Parent” 真的是空的吗?还是在 as 转换后的变量 parentWindow 是空的? - Jehof
Dim LogIn = TryCast(Me.Parent, Window),这是我在vb.net中所做的。基本上,在TryCast中,Me.Parent出现为nothing。因此,变量LogIn也是一样的。 - CogentP
@user1603568,我认为你应该添加更多的代码来得到你问题的答案。 - Jehof
公共子 CloseLogIn() Dim LogIn = TryCast(Me.Parent, Window) 如果 LogIn IsNot Nothing Then LogIn.Close() End If End Sub - CogentP

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接