WPF User Control Parent

后端 未结 17 1126
不知归路
不知归路 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条回答
  •  旧时难觅i
    2020-11-28 02:51

    If you are finding this question and the VisualTreeHelper isn't working for you or working sporadically, you may need to include LogicalTreeHelper in your algorithm.

    Here is what I am using:

    public static T TryFindParent(DependencyObject current) where T : class
    {
        DependencyObject parent = VisualTreeHelper.GetParent(current);
        if( parent == null )
            parent = LogicalTreeHelper.GetParent(current);
        if( parent == null )
            return null;
    
        if( parent is T )
            return parent as T;
        else
            return TryFindParent(parent);
    }
    

提交回复
热议问题