c#WPF无法获取父窗口

c#WPF无法获取父窗口,c#,wpf,C#,Wpf,我有一个wpf页面托管在一个窗口中。但当我尝试使用它时,会得到Null异常。 它可以工作,然后我在另一个方法中使用这段代码,但在alla方法中不使用,为什么会这样? 请给我一些建议 NewPage page = new NewPage (); Window w = Window.GetWindow(this.Parent); w.Content = page; 编辑: 以下是完整的代码: public HandOverListPage() { Initialize

我有一个wpf页面托管在一个窗口中。但当我尝试使用它时,会得到Null异常。 它可以工作,然后我在另一个方法中使用这段代码,但在alla方法中不使用,为什么会这样? 请给我一些建议

 NewPage page = new NewPage ();
 Window w = Window.GetWindow(this.Parent);
 w.Content = page;
编辑:

以下是完整的代码:

    public HandOverListPage() {
        InitializeComponent();

        _settings = new Settings();
    }


    public void ShowCurrentInUseAssignment() {

        _currentDoc = (App.Current as App).SelectedHandOverDoc;

        var r = from item in (App.Current as App).SelectedHandOverDoc.Items
                where item.Status != 20
                select item;

        if(r.Count() == 0) {
            //Report assignment to QP with status finished
            ReportAssignment();

            HandOverPage page = new HandOverPage();

            Window w = Window.GetWindow(this.Parent);
            w.Content = page;

            return;
        } else {
            ICollectionView view = CollectionViewSource.GetDefaultView((App.Current as App).SelectedHandOverDoc.Items);
            view.SortDescriptions.Add(new SortDescription("Status", ListSortDirection.Ascending));

            ListBoxAssignmentItems.ItemsSource = view;
        }

        TxtBlockCounter.Text = r.Count().ToString();
    }
错误:

{“值不能为空。\r\n参数名称:dependencyObject”}

我在使用即时窗口时得到这个

    ?this.GetType()
{Name = "HandOverListPage" FullName = "QP_Truck.Pages.HandOverListPage"}
    [System.RuntimeType]: {Name = "HandOverListPage" FullName = "QP_Truck.Pages.HandOverListPage"}
    base {System.Reflection.MemberInfo}: {Name = "HandOverListPage" FullName = "QP_Truck.Pages.HandOverListPage"}
    Assembly: {QP Truck, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null}
    AssemblyQualifiedName: "QP_Truck.Pages.HandOverListPage, QP Truck, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
    Attributes: Public | BeforeFieldInit
    BaseType: {Name = "Page" FullName = "System.Windows.Controls.Page"}
    ContainsGenericParameters: false
    DeclaringMethod: 'this.GetType().DeclaringMethod' threw an exception of type 'System.InvalidOperationException'
    DeclaringType: null
    FullName: "QP_Truck.Pages.HandOverListPage"
    GenericParameterAttributes: 'this.GetType().GenericParameterAttributes' threw an exception of type 'System.InvalidOperationException'
    GenericParameterPosition: 'this.GetType().GenericParameterPosition' threw an exception of type 'System.InvalidOperationException'
    GUID: {93eb30b9-a64e-3c6b-9182-0f93582d188d}
    HasElementType: false
    IsAbstract: false
    IsAnsiClass: true
    IsArray: false
    IsAutoClass: false
    IsAutoLayout: true
    IsByRef: false
    IsClass: true
    IsCOMObject: false
    IsContextful: false
    IsEnum: false
    IsExplicitLayout: false
    IsGenericParameter: false
    IsGenericType: false
    IsGenericTypeDefinition: false
    IsImport: false
    IsInterface: false
    IsLayoutSequential: false
    IsMarshalByRef: false
    IsNested: false
    IsNestedAssembly: false
    IsNestedFamANDAssem: false
    IsNestedFamily: false
    IsNestedFamORAssem: false
    IsNestedPrivate: false
    IsNestedPublic: false
    IsNotPublic: false
    IsPointer: false
    IsPrimitive: false
    IsPublic: true
    IsSealed: false
    IsSerializable: false
    IsSpecialName: false
    IsUnicodeClass: false
    IsValueType: false
    IsVisible: true
    MemberType: TypeInfo
    Module: {QP Truck.exe}
    Namespace: "QP_Truck.Pages"
    ReflectedType: null
    StructLayoutAttribute: {System.Runtime.InteropServices.StructLayoutAttribute}
    TypeHandle: {System.RuntimeTypeHandle}
    TypeInitializer: null
    UnderlyingSystemType: {Name = "HandOverListPage" FullName = "QP_Truck.Pages.HandOverListPage"}

调用this.Parent时,您处于什么上下文中?您是否希望
是对
页面
对象的引用?从您添加的代码示例来看,情况并非如此。我建议您在
窗口.GetWindow
行中放置一个断点,并在即时窗口中执行
?this.GetType()
,以查看发生了什么。

是您在构造函数方法中发布的代码吗?

UserControl
的父级在其构造函数中始终为null,因此
this.parent
将返回null引用。因此,调用
Window.GetWindow(this.Parent)
会引发
ArgumentNullException
,因为您指定的依赖项对象尚未创建


要解决此问题,您需要将代码放入
初始化的事件处理程序中。引发此事件时,您可以确保已创建
UserControl

尝试Owner属性,您必须分配它

样本:

public Activity ShowLookUp(Window owner)
{
     ActivityLookUp lookup = new ActivityLookUp();
     lookup.Owner = owner;
     lookup.ShowDialog();
}

标签有时很有用

为什么不试试这个呢

// "this" is your Window
YourFrame.Content = new YourPage() { Tag = this };
在你的页面中,试试这个

Window w = (Window)this.Tag;
// and do all the Window wonders

:)

虽然列出了一些可以接受的答案,但它们似乎都过于复杂化了

一个页面没有父页面,但由于一个页面只是一个页面,而不是一个调用get window的窗口,它本身将返回窗口引用而不是页面,因此您所需要的只是

Window w = Window.GetWindow(this);

只需省略.Parent

即可使用不同的选项:

子用户控件的代码隐藏

  • VisualTreeHelper.GetParent(此)
  • LogicalTreeHelper.GetParent(此)
  • 这个,家长
  • GetWindow(这个);→ 如果你想要容器窗口
但是,如果在构造函数中调用,它们都将返回null,因为子控件的初始化发生在将控件附加到可视化树之前

因此,您必须在子用户控件完成加载后调用它们

public MyChildUserControl()
{
    InitializeComponent();
    
    //Postponing the retrieval of the parent using the OnLoaded event
    Loaded += (s, e) =>
    {
        var p = VisualTreeHelper.GetParent(this);

        while (!(ucParent is UserControl))
        {
            ucParent = LogicalTreeHelper.GetParent((DependencyObject) this);
        }



        _parentWindow = Window.GetWindow(this);
        /// whatever you are going to do with parent window
    };
}

作为这个家伙

我不确定我是否理解这一点。为什么这是一个比
Window.GetWindow
更好的解决方案?你能再解释一下吗?我并不是说这是更好的解决方案。这正是我解决问题的方法。我同意-页面没有神奇的所有者,你必须明确地设置它的所有者。我已经在我的帖子中添加了即时窗口的输出。这对我很有用。这可能是被接受的答案。这正是我怀疑为什么我永远无法获得父窗口的原因+1在我的情况下,我不得不在
Loaded
中调用它,而不是
Initialized
。WPF可能会多次加载运行。