내 응용 프로그램 창에 대한 바닥 글 인 사용자 컨트롤이 있습니다. 나는 현재 usercontrol을 호스팅하는 Window의 이름을 얻으려고하는데, 그건 그렇고 여러 요소가 깊기 때문에 부모를 호출 할 수는 없습니다.
VisualTreeHelper에 대해 읽었으며 아래의 것과 같은 여러 코드 샘플을 시도해 보았지만 무엇을하든 상관없이 xxxx.exe에서 'System.NullReferenceException'유형의 예외가 발생했지만 사용자 코드에서 처리되지 않았습니다. 추가 정보 : 개체 참조가 개체의 인스턴스로 설정되지 않았습니다.
public partial class ucFooter : UserControl
{
public ucFooter()
{
InitializeComponent();
tbParent.Text = FindParentWindow(this).Name;
}
private static Window FindParentWindow(DependencyObject child)
{
DependencyObject parent = VisualTreeHelper.GetParent(child);
//CHeck if this is the end of the tree
if (parent == null) return null;
Window parentWindow = parent as Window;
if (parentWindow != null)
{
return parentWindow;
}
else
{
//use recursion until it reaches a Window
return FindParentWindow(parent);
}
}
}
코드를 단계별로 실행하면 If Parent == null 검사가 전달되지 않습니다. 그래서 두 가지 질문이 있습니다. 이 작업을 수행하려면 무엇이 수정되어야하며 그렇지 않은데 부모가 null이라고 생각하는 이유는 무엇입니까?
컨트롤의 생성자를 실행하는 동안 시각적 트리는 아직 설정되지 않았습니다. 메서드 호출을 Loaded
이벤트 처리기로 이동 합니다.
public ucFooter()
{
InitializeComponent();
Loaded += OnLoaded;
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
tbParent.Text = FindParentWindow(this).Name;
}
private static Window FindParentWindow(DependencyObject child)
{
var parent = VisualTreeHelper.GetParent(child);
if (parent == null)
{
return null;
}
return (parent as Window) ?? FindParentWindow(parent);
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다