esc_toe_account
asked on
WPF C# Find Window Instance
I have a click event button handler in which I need to find out the instance (not the class) of the window in which the button resides.
I know that Application.Current.MainWi ndow will tell me the name of the main window but the application launches several windows so there is no guarantee this button click occurred in the main window.
(P.S. the button resides on a page which is held in a frame of the window)
I know that Application.Current.MainWi
(P.S. the button resides on a page which is held in a frame of the window)
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Don't know if this is relevant but the page is navigated to using the navigation service:
theWindow.frame.Navigate(m yPage);
where the button in question resides on myPage;
theWindow.frame.Navigate(m
where the button in question resides on myPage;
RoutedEventArgs has a property Source which could be type casted to button and use the Parent property of the button
Buttong b = e.Source as Button;
b.Parent as Window;
Buttong b = e.Source as Button;
b.Parent as Window;
ASKER
Not sure what I was looking at before. Of-course, VisualTreeHelper does go all the way up the tree. So your suggestion was accruate. In fact, here is a static method I wrote to browse up the tree looking for a specific type of control object (e.g. Window, Frame, etc.)
public static DependencyObject GetVisualParent(Dependency Object UIObj, string parentType)
{
DependencyObject parent = new DependencyObject();
do
{
parent = VisualTreeHelper.GetParent (UIObj);
if (parent.DependencyObjectTy pe.Name == parentType)
{
return parent;
}
UIObj = parent;
} while (UIObj != null);
return null;
}
public static DependencyObject GetVisualParent(Dependency
{
DependencyObject parent = new DependencyObject();
do
{
parent = VisualTreeHelper.GetParent
if (parent.DependencyObjectTy
{
return parent;
}
UIObj = parent;
} while (UIObj != null);
return null;
}
ASKER
Oops, somehow I started using VisualTreeHelper, instead of LogicalTreeHelper which you suggested. That must explain why the former worked and the latter stopped at the page reference. Never noticed the difference till I posted the response! Regardless, you got me to the right solution so points still seem appropriate.
ASKER
((Button)sender.Owner is not valid as Button does not have an Owner property.
And LogicalTreeHelper.GetParen