WPF User Control Parent

后端 未结 17 1059
不知归路
不知归路 2020-11-28 02:18

I have a user control that I load into a MainWindow at runtime. I cannot get a handle on the containing window from the UserControl.

I hav

17条回答
  •  遥遥无期
    2020-11-28 02:45

    If you just want to get a specific parent, not only the window, a specific parent in the tree structure, and also not using recursion, or hard break loop counters, you can use the following:

    public static T FindParent(DependencyObject current)
        where T : class 
    {
        var dependency = current;
    
        while((dependency = VisualTreeHelper.GetParent(dependency) ?? LogicalTreeHelper.GetParent(dependency)) != null
            && !(dependency is T)) { }
    
        return dependency as T;
    }
    

    Just don't put this call in a constructor (since the Parent property is not yet initialized). Add it in the loading event handler, or in other parts of your application.

提交回复
热议问题