WPF User Control Parent

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

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

提交回复
热议问题