c# WPF Cant get Parent Window
I have a wpf page hosted in a Window. But i get Null exception when i tries to get use this. It works then i use this code in another method but not in alla methods why is it that way? please advice.
NewPage page = new NewPage ();
Window w = Window.GetWindow(this.Parent);
w.Content = page;
Edit:
heres the full code:
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();
}
The error :
{"Value cannot be null.\r\nParameter name: dependencyObject"}
I get this when using immediate window
?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'
开发者_StackOverflow社区 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"}
Is the code that you posted in your constructor method?
The parent of a UserControl
is always null in its constructor, so this.Parent
is returning a null reference. Thus, calling Window.GetWindow(this.Parent)
raises an ArgumentNullException
because the dependency object that you specified has not been created yet.
To fix this, you need to place the code in the Initialized
event handler. When this event is raised, you can be sure that the UserControl
has been created.
Try Owner property, you have to assign it.
Sample:
public Activity ShowLookUp(Window owner)
{
ActivityLookUp lookup = new ActivityLookUp();
lookup.Owner = owner;
lookup.ShowDialog();
}
What context are you in when you call this.Parent
? Are you expecting this
to be a reference to the page
object? From the code sample you've added, that won't be the case. I would suggest you put a breakpoint at the Window.GetWindow
line and do ?this.GetType()
in the immediate window to see what's going on.
Tag can be useful sometimes.
Why not try this.
// "this" is your Window
YourFrame.Content = new YourPage() { Tag = this };
and in your Page, try this
Window w = (Window)this.Tag;
// and do all the Window wonders
:)
Though there are acceptable answers listed, they all seem to be way over complicating the matter.
A Page has no parent, but as a Page is only a page and not a window calling get window on itself will return the window reference and not the page, thus all you need is;
Window w = Window.GetWindow(this);
Simply omit the .Parent
You can use different options:
From the Code Behind of the Child UserControl
- VisualTreeHelper.GetParent(this)
- LogicalTreeHelper.GetParent(this)
- this.Parent
- Window.GetWindow(this); → if you want the container Window
But all of them will return null if called in the constructor, because the initialization of the child happen before attaching the control to the visual tree.
So you have to call them after the child User Control has completed it's loading.
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
};
}
As this guy https://stackoverflow.com/a/39477256/196210
精彩评论