WPF 계층 구조에서 객체의 기본 부모에 어떻게 액세스 할 수 있습니까?
문제
내 WPF 객체 안에 깊숙이 Hiearchy 창 개체를 만듭니다.
그러나 나는 원한다 소유자 이 창 객체의 베이스 윈도우 객체.
다음 유형의 코드로 "트리를 등반"하려고 시도했지만이 접근법은 차선책:
(((((((TabGroupPane)((ContentPane) this.Parent).Parent).Parent as
SplitPane).Parent as DocumentContentHost).Parent as
XamDockManager).Parent as ContentControl).Parent as
StackPanel).Parent...
기본 창 객체에 어떻게 액세스 할 수 있습니까?
나는 다음과 같은 것을 생각하고있다 :
의사 코드 :
Window baseWindow = this.BaseParent as Window;
해결책
모든 유형에 맞는 접근법은 필요한 유형의 노드를 찾을 때까지 논리적 트리를 걸어가는 것입니다.
Window baseWindow = FindLogicalParent<Window>(this);
이 방법은 프레임 워크에 존재하지 않으므로 구현이 있습니다.
internal static T FindLogicalParent<T>(DependencyObject obj)
where T : DependencyObject
{
DependencyObject parent = obj;
while (parent != null)
{
T correctlyTyped = parent as T;
if (correctlyTyped != null)
return correctlyTyped;
parent = LogicalTreeHelper.GetParent(parent);
}
return null;
}
을 위한 Window
구체적으로, 당신은 다음을 사용할 수 있습니다.
Window.GetWindow(this);
다른 팁
내가 이것에 대답 할 수있게 해주세요 :
Window baseWindow = Application.Current.Windows[0];
제휴하지 않습니다 StackOverflow