FindParentWindow(this).Name returns 空

FindParentWindow(this).Name returns null

我有一个用户控件,它是我的应用程序的页脚 windows。我正在尝试获取当前托管用户控件的 Window 的名称,顺便说一句,它有几个元素很深,所以我不能只调用它的父级。

我已经阅读了有关 VisualTreeHelper 的信息,我什至尝试了几个不同的代码示例,如下所示,但无论我做什么,我都得到了 'System.NullReferenceException' 类型的异常发生在 xxxx.exe 但未在用户代码中处理。附加信息:未将对象引用设置为对象的实例。

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);
}