WPF User Control Parent

后端 未结 17 997
不知归路
不知归路 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:43

    It's working for me:

    DependencyObject GetTopLevelControl(DependencyObject control)
    {
        DependencyObject tmp = control;
        DependencyObject parent = null;
        while((tmp = VisualTreeHelper.GetParent(tmp)) != null)
        {
            parent = tmp;
        }
        return parent;
    }
    
    0 讨论(0)
  • 2020-11-28 02:44

    Try using the following:

    Window parentWindow = Window.GetWindow(userControlReference);
    

    The GetWindow method will walk the VisualTree for you and locate the window that is hosting your control.

    You should run this code after the control has loaded (and not in the Window constructor) to prevent the GetWindow method from returning null. E.g. wire up an event:

    this.Loaded += new RoutedEventHandler(UserControl_Loaded); 
    
    0 讨论(0)
  • 2020-11-28 02:45

    This didn't work for me, as it went too far up the tree, and got the absolute root window for the entire application:

    Window parentWindow = Window.GetWindow(userControlReference);
    

    However, this worked to get the immediate window:

    DependencyObject parent = uiElement;
    int avoidInfiniteLoop = 0;
    while ((parent is Window)==false)
    {
        parent = VisualTreeHelper.GetParent(parent);
        avoidInfiniteLoop++;
        if (avoidInfiniteLoop == 1000)
        {
            // Something is wrong - we could not find the parent window.
            break;
        }
    }
    Window window = parent as Window;
    window.DragMove();
    
    0 讨论(0)
  • 2020-11-28 02:45
    DependencyObject parent = ExVisualTreeHelper.FindVisualParent<UserControl>(this);
    
    0 讨论(0)
  • 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<T>(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.

    0 讨论(0)
  • 2020-11-28 02:46
    DependencyObject GetTopParent(DependencyObject current)
    {
        while (VisualTreeHelper.GetParent(current) != null)
        {
            current = VisualTreeHelper.GetParent(current);
        }
        return current;
    }
    
    DependencyObject parent = GetTopParent(thisUserControl);
    
    0 讨论(0)
提交回复
热议问题