繁体   English   中英

c# WPF 无法获取父窗口

[英]c# WPF Cant get Parent Window

我在窗口中托管了一个 wpf 页面。 但是当我尝试使用它时,我得到了 Null 异常。 它工作然后我在另一种方法中使用此代码但不是在所有方法中为什么会这样? 请指教。

 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"}

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

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

要解决此问题,您需要将代码放在Initialized事件处理程序中。 引发此事件时,您可以确定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

:)

尽管列出了可接受的答案,但它们似乎都使问题复杂化了。

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

Window w = Window.GetWindow(this);

只需省略 .Parent

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

您可以使用不同的选项:

用户控件背后的代码

  • VisualTreeHelper.GetParent(this)
  • LogicalTreeHelper.GetParent(this)
  • this.Parent
  • Window.GetWindow(this); → 如果你想要容器 Window

但是如果在构造函数中调用它们,它们都将返回 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
    };
}

作为这个人https://stackoverflow.com/a/39477256/196210

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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