【问题标题】:closing wpf window from within frame从框架内关闭 wpf 窗口
【发布时间】:2013-03-02 20:42:23
【问题描述】:

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

页面如何关闭父窗口?!?

如果您知道 vb 中的代码,请提前致谢。如果不是,我会在 C# 中解决。

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

【问题讨论】:

  • 关闭父窗口是什么意思?你想关闭它吗?还是要退出应用程序?
  • 对不起。关闭它。

标签: wpf vb.net navigation


【解决方案1】:

试试

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

Window.GetWindow() 方法返回对 Window 对象的引用,该对象承载依赖对象所在的内容树。

【讨论】:

    【解决方案2】:

    您应该通过使用 Page 实例上的属性 Parent 来获取承载 Page 的 Window。

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

    public class MyPage : Page{
    
       public void CloseWindow(){
         var parentWindow = this.Parent as Window;
    
         if (parentWindow != null) {
           parentWindow.Close();
         }
       }
    }
    

    【讨论】:

    • 感谢 Jehof,我认为您的方法是正确的,但只是尝试了代码,而 This.Parent 是空的(什么都没有)。
    • @user1603568 是this.Parent 真的什么都不是,或者是parentWindow 转换后的变量as 什么都没有
    • Dim LogIn = TryCast(Me.Parent, Window),这就是我在 vb.net 中所做的。基本上在 TryCast 中,Me.Parent 什么都没有出现。所以很明显变量LogIn是一样的。
    • @user1603568 我认为您应该添加更多代码来获得您问题的答案。
    • Public Sub CloseLogIn() Dim LogIn = TryCast(Me.Parent, Window) If LogIn is Not Nothing Then LogIn.Close() End If End Sub
    猜你喜欢
    • 2014-04-05
    • 1970-01-01
    • 1970-01-01
    • 2020-09-04
    • 1970-01-01
    • 2011-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多